text
stringlengths 256
65.5k
|
|---|
I'm creating an app that allows users to use their own domain. What method do I use in my Rails app to automatically register their chosen domain with Heroku? I'll also need to deregister it if they change it.
I have contacted Heroku for the same thing, and they just pointed me at their api, and said it is fine to use it that way.
Here's the simple how-to:
require 'heroku'
heroku = Heroku::Client.new('heroku_username', 'heroku_password')
heroku.add_domain('heroku_app_name', 'example.com')
heroku.remove_domain('heroku_app_name','example.com')
See the api for more.
Of course I'd recommend against putting a plaintext password into your code. A nice thing you can do is use the heroku environment variables to get your passwords out of the code.
heroku = Heroku::Client.new(ENV['HEROKU_USER'], ENV['HEROKU_PASSWORD'])
and then you can set the environment variables on your app with
from the command line.
The heroku gem has now been deprecated. You should use the heroku.rb gem instead. The commands have changed slightly, but it's essentially the same.
require 'heroku-api'
heroku = Heroku::API.new(:api_key => API_KEY) # use API Key
heroku = Heroku::API.new(:username => USERNAME, :password => PASSWORD) # use username and password
heroku = Heroku::API.new(:headers => {'User-Agent' => 'custom'}) # use custom header
heroku.delete_domain('app', 'example.com') # remove the 'example.com' domain from the 'app' app
heroku.get_domains('app') # list configured domains for the 'app' app
heroku.post_domain('app', 'example.com') # add 'example.com' domain to the 'app' app
As I said before, the client calls the Heroku API. You can extract the Heroku Domain API information from the library and create a custom script that calls the Heroku API to add and remove a domain from your app.
Here's the client source code.
Note. Because you are "reverse engineering" and API which appears to be not documented, you should ask Heroku permission to do that, just to be sure you are not creating something against their TOS.
The gem is from heroku and is the recommended approach. I just contacted Heroku with the same question and this was there response:
You need to tell Heroku about the domain and where to route it as well. The CNAME tells DNS how to get the request to Heroku. Now you must tell Heroku which app to send it to. You do this by adding the domain to your app. In your case you would need to run "heroku domains:add my.domain.com" to your app. You can also do this programmatically from inside your application over our API. See the Heroku gem (http://github.com/heroku/heroku) for an example of how to connect and use the API.
|
The kernel in use: 3.2.0-23-generic on Ubuntu 12.04LTS
For example, I issue the following command:
sudo cpufreq-set -c 0 -g performance
Then I go to /sys/devices/system/cpu/cpu0/cpufreq and type in the following:
sudo cat cpuinfo_cur_freq
Sometimes I get the max frequency (3600 MHz) when I do this and sometimes I get the min frequency (1600 MHz).
If I do:
cat scaling_governor
The output is performance, showing that the governor is in fact set to performance.
Then, to make it even more weird, if I do:
cpufreq-info
I get:
analyzing CPU 0:
driver: acpi-cpufreq
CPUs which run at the same hardware frequency: 0 1 2 3 8 9 10 11
CPUs which need to have their frequency coordinated by software: 0
maximum transition latency: 10.0 us.
hardware limits: 1.60 GHz - 3.60 GHz
available frequency steps: 3.60 GHz, 3.60 GHz, 3.47 GHz, 3.33 GHz, 3.20 GHz, 3.07 GHz, 2.93 GHz, 2.80 GHz, 2.67 GHz, 2.53 GHz, 2.40 GHz, 2.27 GHz, 2.13 GHz, 2.00 GHz, 1.87 GHz, 1.73 GHz, 1.60 GHz
available cpufreq governors: conservative, ondemand, userspace, powersave, performance
current policy: frequency should be within 3.60 GHz and 3.60 GHz.
The governor "performance" may decide which speed to use
within this range.
current CPU frequency is 3.60 GHz.
...
If you look at the current policy above, you will notice that it is telling me that the CPU should be pegged at 3.60 GHz. Yet, cpuinfo_cur_freq seems to tell a different story.
|
Initially I installed Python 3.3 from source, but then I removed and deleted the directory /usr/lib/python3.3.
When I am installing it using aptitude, I am getting this error.
Unpacking python3.3 (from .../python3.3_3.3.1-1ubuntu5_i386.deb) ...
Processing triggers for man-db ...
Processing triggers for bamfdaemon ...
Rebuilding /usr/share/applications/bamf-2.index...
Processing triggers for desktop-file-utils ...
Setting up python3.3 (3.3.1-1ubuntu5) ...
python3.3: can't open file '/usr/lib/python3.3/py_compile.py': [Errno 2] No such file or directory
dpkg: error processing python3.3 (--configure):
subprocess installed post-installation script returned error exit status 2
Errors were encountered while processing:
python3.3
E: Sub-process /usr/bin/dpkg returned an error code (1)
A package failed to install. Trying to recover:
Setting up python3.3 (3.3.1-1ubuntu5) ...
python3.3: can't open file '/usr/lib/python3.3/py_compile.py': [Errno 2] No such file or directory
dpkg: error processing python3.3 (--configure):
subprocess installed post-installation script returned error exit status 2
Errors were encountered while processing:
Any idea how to rectify the error?
|
maided
ImportError: No module named GursorMaker
Salut,
J' ai installé Gursormaker mais quand je le lance, j'ai ce joli message :
Traceback (most recent call last):
File "/usr/bin/gursormaker", line 23, in <module>
import GursorMaker
ImportError: No module named GursorMaker
C'est moche et ça m'énerve :mad:quelqu'un sait comment résoudre ça (en plus avec compiz fusion le changement de curseur est pas pris en compte completement) ?
Merci d'avance
Hors ligne
00zely
Re : ImportError: No module named GursorMaker
Bon bah... UP, moi aussi!
00zely
Hors ligne
Pl°°m
Re : ImportError: No module named GursorMaker
Un peu tard peut-être mais ...
Note 1 : même message d'erreurNote 2 : Gutsy
1. Vérifier les dépendances ?
Elles sont installées par défaut dans le système de base ...
2. Une recherche avec "No module named GursorMaker" sur le Net ?
Une solution sur le forum ubuntuforum.org (http://ubuntuforums.org/showthread.php?t=496871)
Well, do like this:
Edit a textfile named cursor.txt and put this information in it:
32 1 1 plugL.png 0
Save the file. Make sure your png-file is in the same directory. Open a console in that directory and use this command:
xcursorgen cursor.txt left_ptr
Now you have a new file in the same directory, named left_ptr, that is an X-cursor file.
Find out which cursor theme you are currently using, using System > Preferences > Mouse. Say it's the one named redglass.
Cursors are saved under /usr/share/icons/name_of_theme/cursors
Save the original cursor like this (substitute redglass with whatever theme you are using):
cp /usr/share/icons/redglass/cursors/left_ptr ~/cursor.bak
Copy your new one into place like so:
sudo cp left_ptr /usr/share/icons/redglass/cursors/left_ptr
Close all programs and logout (no reboot necessary). Login again and your new cursor should now be used instead of the original. Note that this is a rather quick and dirty approach but it should work.
Mais comme le dit l'auteur lui-même, ce n'est pas très propre ... et cela revient à faire la manip à la main ...
3. Tenter l'install par les sources ?
Télécharger les sources (http://gursormaker.sourceforge.net/)
cp gursormaker-0.6.0.tar.bz2 /tmp && cd /tmp
tar jxvf gursormaker-0.6.0.tar.bz2
cd gursormaker-0.6.0
Un petit tour par les instructions d'installations ...
sudo ./setup.py install
Ça marche
Edit :
Eh ben non ça ne suffit pas avec Karmic : ne nouvelle erreur apparaît : ImportError: No module named Numeric
Pour y pallier il faut installer le paquet python-numeric (dépôt Universe).
>> et alors ... ça marche !
Dernière modification par Pl°°m (Le 31/10/2009, à 13:14)
La plus grande difficulté de GNU/Linux : le choix !
Hors ligne
Srassasin
Re : ImportError: No module named GursorMaker
*s'évanouit* comment on fait pour trouver se genre de résolution de problèmes?
Hors ligne
Pl°°m
Re : ImportError: No module named GursorMaker
???
La plus grande difficulté de GNU/Linux : le choix !
Hors ligne
Mcready1
Re : ImportError: No module named GursorMaker
Salut à tous.
Désolé de réveiller ce thread, mais en le relisant, les choses ne sont pas bien claires, pour moi.
Si je prends la version dite "manuelle" :
Je créé un document "cursor.txt" ? Je suis censé en trouver un quelque part qu'il faudrait éditer ?
Autre chose, admettons qu'il faille le créer. il est sur mon bureau. A côté, j'ai mon curseur que j'ai converti en PNG (parce que c'était un .cur), j'en fais quoi ?
Je veux dire, si je les mets ensemble, par exemple, dans mon /home, et que j'ouvre une console et que je tape "xcursorgen cursor.txt left_ptr", je me retrouve avec "PNG error while reading plugL.png!".
C'est parce qu'il y a un endroit vraiment précis ?
Parce que là, je pige rien.
Merci à celles et ceux qui ont la solution.
EDIT : je ne l'avais pas vu, mais, effectivement, un fichier "left_ptr" s'est créé.
En cherchant dans "Cursor Selection", je vois que j'utilise "DMZ-White".
Pas de problème, je fais la manip' suivante : cp /usr/share/icons/DMZ-White/cursors/left_ptr ~/cursor.bak
Puis : sudo cp left_ptr /usr/share/icons/DMZ-White/cursors/left_ptr.
Je coupe Ubunut et je le remets en marche.
Et là, non seulement mon nouveau curseur n'y est pas, mais en plus, DMZ-White n'apparaît plus dans "Cursor Selection" (par contre, il est toujours dans /usr).
A la place, je me retrouve d'office avec DMZ-Black.
Certains ont-ils déjà été confrontés à ce problème ?
Merci encore.
RE-EDIT : Bon, j'ai suivi ce tuto, qui me semblait plus clair. La conversion de mon png au format X11 s'est parfaitement déroulée.
Par contre, ça n'est peut-être pas très académique, mais, pour sa prise en charge, j'y suis allé en mode "bourrin" : J'ai renommé mon nouveau X11 en "arrow" et je l'ai mis à la place de celui existant.
Je ne sais pas si c'est vraiment conseillé, mais, en tout cas, ça marche parfaitement.
Dernière modification par Mcready1 (Le 06/12/2010, à 14:20)
The Precise Pangolin (23 bits)
Nvidia GeForce 405
Hors ligne
|
Test-Driven Development in Python
by Jason Diamond
12/02/2004
Introduction
Python's unittest Module
Motivation
Sample Input
Getting Started
Baby Steps
Refactoring
Conclusion
Introduction
Test-driven development is not about testing. Test-driven development is about development (and design), specifically improving the quality and design of code. The resulting unit tests are just an extremely useful by-product.
That's all I'm going to tell you about test-driven development. The rest of this article will show you how it works. Come work on a project with me; we'll build a very simple tool together. I'll make mistakes, fix them, and change designs in response to what the tests tell me. Along the way, we'll throw in a few refactorings, design patterns, and object-oriented design principles.
To make this project fun, we'll do it in Python.
Python is an excellent language for test-driven development because it (usually) does exactly what you want it to without getting in your way. The standard library even comes with everything you need in order to start developing TDD-style.
I assume that you're familiar with Python but not necessarily familiar with test-driven development or Python's unittest module. You need to know only a little in order to start testing.
Python's unittest Module
Since version 2.1, Python's standard library has included a unittest module, based on JUnit (by Kent Beck and Erich Gamma), the de facto standard unit test framework for Java developers. Formerly known as PyUnit, it also runs on Python versions prior to 2.1 with a separate download.
Let's jump right in. Here's a "unit" and its tests--all in one file:
import unittest
# Here's our "unit".
def IsOdd(n):
return n % 2 == 1
# Here's our "unit tests".
class IsOddTests(unittest.TestCase):
def testOne(self):
self.failUnless(IsOdd(1))
def testTwo(self):
self.failIf(IsOdd(2))
def main():
unittest.main()
if __name__ == '__main__':
main()
Lights
Throughout this article, I'll use a traffic light to show the state of the tests. Green indicates that the tests pass, and red warns that they fail. A shining yellow light indicates a problem that prevents us from completing a test. TDD practitioners often talk about receiving a "green light" or "green bar" from the graphical test runner that comes with JUnit.
Methods whose names start with the string test with one argument (self) in classes derived from unittest.TestCase are test cases. In the above example, testOne and testTwo are test cases.
Grouping related test cases together, test fixtures are classes that derive from unittest.TestCase. In the above example, IsOddTests is a test fixture. This is true even though IsOddTests derives from a class called TestCase, not TestFixture. Trust me on this.
Test fixtures can contain setUp and tearDown methods, which the test runner will call before and after every test case, respectively. Having a setUp method is the real justification for fixtures, because it allows us to extract common setup code from multiple test cases into the one setUp method.
In Python we typically don't need a tearDown method, because we can usually rely on Python's garbage collection facilities to clean up our objects for us. When testing against a database, however, tearDown could be useful for closing connections, deleting tables, and so on.
Looking back at our example, the main function defined in the unittest module makes it possible to execute the tests in the same manner as executing any other script. This function examines sys.argv, making it possible to supply command-line arguments to customize the test output or to run only specific fixtures or cases (use --help to see the arguments). The default behavior is to run all test cases in all test fixtures found in the file containing the call to unittest.main.
Executing the test script above should produce output that resembles:
.. ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK
If the second test had failed, the output would have looked something like this:
.F
======================================================================
FAIL: testTwo (__main__.IsOddTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\jason\projects\tdd-py\test.py", line 14, in testTwo
self.failIf(IsOdd(2))
File "C:\Python23\lib\unittest.py", line 274, in failIf
if expr: raise self.failureException, msg
AssertionError
----------------------------------------------------------------------
Ran 2 tests in 0.000s
FAILED (failures=1)
Typically, we wouldn't have the tests and the unit being tested in the same file, but it doesn't hurt to start out that way and then extract the code or the tests later.
Motivation
Guess what I have trouble remembering to do:
0 0 * * * [ `date +\%m` -ne `date -d +4days +\%m` ] \
&& mail -s 'Pay the rent!' me-and-my-wife@example.org < /dev/null
Related Reading
That little puzzle is a line out of my crontab that emails me a reminder to pay the rent on the last four days of each month. Pathetic? Probably. It works, though. I haven't been late paying rent since I started using it.
As clever as I thought I was for coming up with this, it wasn't practical for everything--especially for events that occur only once. Also, there's no way I could teach my wife enough bash scripting techniques in order to add a reminder to our calendar.
Most people use a good old-fashioned wall calendar for this type of thing. That's not techno-geeky enough for me.
I could use Outlook or Evolution or some productivity application, but that would open up a whole new can of worms. We don't use just one computer. We both use multiple computers and operating systems at home and at work. How could we easily synchronize all of those machines?
It was after realizing that our email is available to us no matter where we were that I hit upon the motivation for my project. The email reminding me to pay the rent was with me no matter what machine I'm on because I always check my email via IMAP, so my email is accessible from everywhere.
Why not email the upcoming events in my calendar to me just like my reminder to pay the rent? Brilliant, I thought. I know just the tools that can do this, too: the BSD calendar application and the new kid on the block, pal.
My wife and I have a private wiki that we use for keeping track of notes. It's great. Despite the fact that my wife's an accountant and not a geek, she has no trouble using it. I figured we could use the wiki to edit our calendar file. I would write a little cron job to fetch the calendar file--probably using wget--from the wiki and pipe that into whatever tool best fit our needs.
Unfortunately, after looking at both calendar and pal, I discovered that neither was what I was looking for.
The calendar file format requires a <tab> character between dates and descriptions. Since I wanted to use our personal wiki to edit the calendar file, inserting <tab> characters would be an issue (upon hitting <tab>, focus jumps out of the text area to the next form control). calendar also doesn't support any of the fancy output options that pal does.
The pal format was much too geeky for even me to want to use, and it didn't support the one really important use case I had so far: setting a reminder for the last day of the month.
Sample Input
My wife and I sat down and came up with something both of us would want to use. Here are some examples:
30 Nov 2004: Dinner with the Darghams. April 10: Happy Anniversary! Wednesday: Piano lesson. Last Thursday: Goody night at book study. Yum. -1: Pay the rent!
Unlike the calendar format, a colon separates dates from descriptions. How Pythonic.
Like the calendar format, omitted certain fields are wildcards. The April 10 event happens every year. The Last Thursday event happens on the final Thursday of every month of every year.
The -1 event happens on the last day of every month of every year too. I took this idea from Python's array subscript syntax, where foo[-1] selects the last element in the foo array. I thought it was a little geeky, but my wife understood it right away.
My goal is to write a small application that can run from cron to read a file in this format and email my wife and me the events we have scheduled for the next seven days. That shouldn't be too hard, should it?
From this point on, I'm writing this article in real time, having contrived nothing. I didn't write the code first and then write the article--I'm writing the article as I write the code. Yes, I expect to make mistakes. In fact, I'm counting on it. Making mistakes is the best way to learn.
Getting Started
Being test infected means that I must write this tool by writing all of my unit tests before writing the code I expect the tests to exercise.
The first thing I do when starting a new project is to create an empty fixture that fails:
import unittest
class FooTests(unittest.TestCase):
def testFoo(self):
self.failUnless(False)
def main():
unittest.main()
if __name__ == '__main__':
main()
I do this out of habit, just to make sure I have everything typed in correctly and to test that the test runner can find the fixture.
Notice the class named FooTests and its testFoo method. At this point I have no idea what I'm going to test first. I just want to make sure that I have everything ready once things get going.
Let's start out easy and test the first example from above with the full day, month, and year specified for the event. In order to create this test, I need know what to test. Am I testing a class? A function?
This is where we put on our designer hats for a brief moment and try to use our experience and intuition to come up with some piece to the puzzle that will help us reach our goal. It's OK if we make a mistake here; the tests will reveal that right away, before we invest too much in this design. We certainly don't want to draft any documents filled with diagrams. Save those for later, after we have a clue about what will actually work.
For this project, I should probably create objects that can say whether they "match" a given date. These objects will act as a "pattern" for dates. (I'm using regular expressions as a metaphor here.)
Eventually, I'll have to write a parser that will read in a file and create these pattern objects, but I'll do that later. These pattern objects are probably an easier place to start.
There might be multiple types of patterns--but I won't think about that now, because I could be wrong. Instead, I'll start coding so I can let it tell me what it wants to become:
def testMatches(self):
p = DatePattern(2004, 9, 28)
d = datetime.date(2004, 9, 28)
self.failUnless(p.matches(d))
Notice that I changed the name of the method from testFoo to something more appropriate, because I now have an idea about what to test. I've also invented a class name, DatePattern, and a method name, matches. (The datetime module is part of Python 2.3 and up--I had to import it at the top of my file in order to use it.)
This test, of course, fails miserably--the DatePattern class doesn't even exist yet! But I at least know now the name of the class I need to implement. I also know the name and signature of one of its methods and the signature for its __init__ method. Here's what I can do with this knowledge:
class DatePattern:
def __init__(self, year, month, day):
pass
def matches(self, date):
return True
Now the test passes! It's time to move on to the next test.
You probably think I'm joking, don't you? I'm not.
Baby Steps
Test-driven development is best when you move in the smallest possible increments. You should only be writing code that makes the current failing test case(s) pass. Once the tests pass, you're done writing code. Stop!
The above code is worthless, right? It basically says that every pattern matches every date. How can I justify spending the time to come up with a "real" implementation? By adding another test:
def testMatchesFalse(self):
p = DatePattern(2004, 9, 28)
d = datetime.date(2004, 9, 29)
self.failIf(p.matches(d))
We now have one passing test and one failing test.
I could change the matches method to return False in order to make this new test case pass, but that would break the old one! I now have no choice but to implement DatePattern correctly so that both tests can pass. Here's what I came up with:
class DatePattern:
def __init__(self, year, month, day):
self.date = datetime.date(year, month, day)
def matches(self, date):
return self.date == date
Both tests now pass. Woo-hoo! I'm not happy with the DatePattern class, though. So far, it's nothing more than a simple wrapper around Python's date class. Why am I not just using date instances for my "patterns"?
It might turn out that the DatePattern class is unnecessary, but I'm not going to make that decision on my own. Instead, I'm going to write another test--one that I think will confirm the necessity of the DatePattern class:
def testMatchesYearAsWildCard(self):
p = DatePattern(0, 4, 10)
d = datetime.date(2005, 4, 10)
self.failUnless(p.matches(d))
Voilà! This test fails!
Why am I so happy about a failing test? My reasoning is simple: this proves that the current implementation of DatePattern is insufficient. It can't be just a simple wrapper around date and therefore can't be just a date.
While typing this test, I had to make a decision about how to represent wildcards. What occurred to me first was to use 0. After all, there's no year 0 (contrary to popular belief), month 0, or day 0. This may not have been the best choice, but I'm going to roll with it for now.
It's time to make the new test pass (while making sure not to break the old ones):
class DatePattern:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def matches(self, date):
return ((self.year and self.year == date.year or True) and
self.month == date.month and
self.day == date.day)
To be honest, I'm already starting to feel like I'll need to do some refactoring as I add more wildcard functionality to the class, but I want to write a few more tests first.
Let's add a test where the month is a wildcard:
def testMatchesYearAndMonthAsWildCards(self):
p = DatePattern(0, 0, 1)
d = datetime.date(2004, 10, 1)
self.failUnless(p.matches(d))
Fixing matches so that the test passes results in this:
def matches(self, date):
return ((self.year and self.year == date.year or True) and
(self.month and self.month == date.month or True) and
self.day == date.day)
This method is getting uglier every time we touch it--I'm now positive that it will be my first refactoring victim.
I now have a test for using wildcards for both years and months. Will I need one for days? A pattern containing nothing but wildcards would match every day. When would that be useful?
At this point I can't think of a reason to support wildcard days, so I won't bother writing a test for it. Because of that, I also won't bother implementing any code to support it in the DatePattern class. Remember, code gets written only when there's a failing test that needs the new code in order to pass. This prevents us from writing code that should not exist in our application, which should help keep it from becoming unnecessarily complex.
Let's move on. We need to support events that occur on a specified day of every week:
def testMatchesWeekday(self):
p = DatePattern(
Uh, what now?
At this point, I realized that the DatePattern class might not be what I want to use for this test. Its __init__ method doesn't accept a weekday. Should I use a different class, or modify the existing one?
I decided to modify the existing one for now, as that will require the least amount of work. If this turns out to be a bad idea, I can always refactor later.
def testMatchesWeekday(self):
p = DatePattern(0, 0, 0, 2) # 2 is Wednesday
d = datetime.date(2004, 9, 29)
self.failUnless(p.matches(d))
This doesn't pass because DatePattern.__init__ doesn't accept five arguments (counting self). I modified __init__ to look like this:
def __init__(self, year, month, day, weekday=0):
self.year = year
self.month = month
self.day = day
self.weekday = weekday
I gave weekday a default value so that I wouldn't need to update the other test cases. Everything compiles and runs, but the new test case doesn't pass.
The astute reader has probably already realized that I'm now passing in 0 for the day argument. There's the wildcard I didn't think I would need--now I need it!
Here's my new matches method:
def matches(self, date):
return ((self.year and self.year == date.year or True) and
(self.month and self.month == date.month or True) and
(self.day and self.day == date.day or True) and
(self.weekday and self.weekday == date.weekday() or True))
Now all of the components of a pattern allow for wildcards. How very interesting.
With this new method, testMatchesWeekday passes but testMatchesFalse now fails! What gives?
Refactoring
I honestly can't tell why testMatchesFalse fails by looking at the code. This is going to call for some simple debugging. Unfortunately, I tried to cram all of the logic for the matches method into one expression (spanning four lines!), so there's no place for me to insert any print statements to help me see which part is failing. It's finally time to do that refactoring I've been wanting to do.
The refactoring I want to apply is the Compose Method from Joshua Kerievsky's excellent book, Refactoring to Patterns. By extracting smaller methods from the current matches method, I can not only make matches clearer but also make it possible to debug whichever part is currently causing me grief.
This is the result:
def matches(self, date):
return (self.yearMatches(date) and
self.monthMatches(date) and
self.dayMatches(date) and
self.weekdayMatches(date))
def yearMatches(self, date):
if not self.year: return True
return self.year == date.year
def monthMatches(self, date):
if not self.month: return True
return self.month == date.month
def dayMatches(self, date):
if not self.day: return True
return self.day == date.day
def weekdayMatches(self, date):
if not self.weekday: return True
return self.weekday == date.weekday()
Code Pickiness
I recently read a weblog post by Ian Bicking about what he considers to be code smells in Python code.
The matches method is now much clearer, don't you agree? It might seem like a ridiculous thing to do, but writing intention-revealing code is much more important than being clever. I was trying to be too clever before and it caused a bug--one that I wouldn't have come across if I had done this from the beginning.
After applying this refactoring and rerunning the tests, I expected to see the testMatchesFalse test still failing, but it's now passing. Somewhere in my original logic I made an error, and I have no idea where it was--I'll leave finding it as an exercise for the reader. In the meantime, not only do I have simpler code now but it also actually works the way I expect it to. Take that!
Would I have noticed this bug without tests? I have no doubt that I would, but how long would it have been before I realized that this was a problem? With my unit tests, I noticed it immediately, so I knew exactly what to fix.
Wildcards essentially work for all of the components I'm testing so far. This is good, but I think the next test will cause trouble. It starts out innocently enough:
def testMatchesLastWeekday(self):
p = DatePattern(0, 0, 0, 3
Er, I'm stuck again.
In case it's not obvious (and it's not--why didn't Python's datetime module define constants for weekdays?), the 3 represents Thursday.
How do I indicate that I only want to match the last Thursday in a month? Do I need to add yet another argument to DatePattern.__init__?
This is where that sneaking suspicion in the back of my head is finally starting to warrant some closer attention. I might be trying to cram too much functionality into one class.
Conclusion
I haven't written much code yet, but that's a good thing, since it seems that the code I have written might not have been sufficient for what I want to do with it. Without the tests, I might not have discovered what a mess I was writing until it was too late. At this point, I haven't invested too much time into the DatePattern class, so I won't feel bad about throwing it away if that's what I'll need to do.
I have some ideas about how to restructure the code so that it's as simple and yet as functional as I want it to be, but we're going to have to save those for Part 2 of this article, which will be published shortly.
Jason Diamond is a consultant specializing in C++, C#, and XML, and is located in sunny Southern California.
Return to the Python DevCenter.
|
Tony95
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
Salut à tous je savais pas trop où poster donc je le fais ici. J'ai un petit soucis en GTK, j'aimerais créer une interface permettant de charger et sauvegarder des fichiers mais j'arrive vraiment pas à m'en sortir pour le code. En gros j'ai une fenetre qui me sert de menu avec 4 boutons dont deux servant respectivement à charger et à sauvegarder des fichiers.
J'ai du mal à connecter chaque bouton à la fonction qui va avec (c'est mon premier soucis). Ce que je veux dire c'est qu'après avoir cliqué sur le bouton "sauvegarder" j'aimerais avoir l'affichage de la fenêtre de chargement des fichiers. Et la même chose pour sauvegarder aussi. J'ai juste trouvé une fonction pour renvoyer le chemin du fichier sélectionné mais elle est un peu inutile.
Je tien sà préciser que je suis nul en GTK et que j'ai juste des notions de base. Merci d'avance pour votre aide.
Hors ligne
philarmonie
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
@ kevlar: c'est surtout les abscisses dont tu as besoin pour la position des events, non? et la police a un impact dessus?
Pour ce qui est de la technique de surcharge, là ça rentre dans du C donc je ne comprends pas tout, mais on doit pouvoir faire sans.
Normalement quelque soient les containers dans lesquels se trouve ton widget, ça n'a pas d'impact sur la façon de gérer les events.
Pour le motion-notify-event en python je peux le capter sans problème
#!/usr/bin/pyhton
import gtk
class Win:
def __init__(self):
self.win = gtk.Window()
self.ruler = gtk.HRuler()
self.ruler.set_size_request(200, 20)
self.ruler.set_range(0, 200, 10, 200)
# rajoute la gestion du clic pour le ruler
self.ruler.add_events(gtk.gdk.BUTTON_PRESS_MASK)
self.win.connect("delete-event", gtk.main_quit)
self.win.add(self.ruler)
self.ruler.connect('button-press-event', self.press)
self.ruler.connect('motion-notify-event', self.move)
self.win.show_all()
def press(self, widget, event):
print 'pressed on', event.get_coords()
def move(self, widget, event):
print 'move on', event.get_coords()
if __name__ == '__main__':
win = Win()
gtk.main()
Edit: ce n'est pas la peine de rajouter cet event, il est déjà capté par le ruler (et a déjà un callback dessus) il faut juste rajouter un callback dessus.
@ Tony95: ouvre ton propre sujet et précise dans quel langage tu codes.
Dernière modification par philarmonie (Le 08/06/2009, à 20:12)
kevlar
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
merci Philarmonie. En fait, je me débrouille en utilisant la dernière version(message #25), et maintenant, le déplacement de la règle est coordonné avec celui de la timeline, de l'indicateur de position dans l'animation, et cela sans utiliser les GTkRulers. Reste à terminer de répondre au défi en trouvant un moyen d'installer un "balayage" de la position courante, comme sur Macromedia Flash Pro, mais à mon avis ça peut se résoudre avec une gestion "habile" des icônes ...
Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1
Projet Ella sur launchpad : https://launchpad.net/ella
Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance
et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html
Hors ligne
kevlar
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
eh bien, la solution aux limites de Gtk est un projet complémentaire, goocanvas ; il permet enfin une gestion "moderne" des éléments graphiques, permettant entre autres de faire répondre des morceaux de dessins à des clics souris, etc .. .
Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1
Projet Ella sur launchpad : https://launchpad.net/ella
Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance
et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html
Hors ligne
philarmonie
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
eh bien, la solution aux limites de Gtk est un projet complémentaire,
goocanvas; il permet enfin une gestion "moderne" des éléments graphiques,permettant entre autres de faire répondre des morceaux de dessins à des clics souris, etc.. .
Bah on peut le faire en gtk sans goocanvas.
J'ai fait une logiciel de création de thème usplash, j'ai une DrawingArea dans laquelle je dessine le thème avec son arrière plan, sa barre et sa zone de texte, et elle réagit très bien aux actions de la souris. Il me manque juste le redimensionnement des objets avec la souris mais c'est pas un problème de gestion des événements, mais plutôt d'apprendre à dessiner des rectangles transparents avec cairo.
kevlar
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
intéressant, tu peux mettre une copie d'écran ? (moi je ne peux pas, ImageShack ne répond pas en ce moment ...)
Dernière modification par kevlar (Le 15/06/2009, à 17:31)
Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1
Projet Ella sur launchpad : https://launchpad.net/ella
Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance
et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html
Hors ligne
kevlar
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
Voici une copie :
la règle ne provient pas de Gtk : elle est gérée par goocanvas. Elle est composée d'éléments graphiques standards (lignes, texte) qui peuvent chacun émettre des événements. Ainsi, un clic sur une des graduations, ou sur le numéro de l'image, renvoit à un traitement à callback.
A titre de comparaison, la dernière version "pure Gtk" est ci-dessous :
Il est facile de voir qu'il me fallait TROIS lignes de widgets pour faire la même règle (capable, bien entendu, de réagir aux clics, il ne s'agissait déjà plus d'un GtkRuler).
De plus, avec goocanvas, l'espace est mieux géré, je peux contrôler le rendu de la règle (car goocanvas s'appuie sur cairo )
Dernière modification par kevlar (Le 15/06/2009, à 17:42)
Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1
Projet Ella sur launchpad : https://launchpad.net/ella
Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance
et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html
Hors ligne
philarmonie
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
L'image est composée de 3 éléments chacun dans un pixbuf: le fond, la barre et la zone de texte.
Je peux déplacer la barre et la zone de texte avec la souris, comme on peut le faire avec n'importe quel icône sur le bureau par exemple. Si je fais un clic-droit sur la barre elle fait une rotation, Shif+clic gauche c'est un centrage verticale, shif+clic gauche c'est un centrage horizontale.
Dernière modification par philarmonie (Le 15/06/2009, à 17:46)
kevlar
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
L'image est composée de 3 éléments chacun dans un pixbuf: le fond, la barre et la zone de texte.
Je peux déplacer la barre et la zone de texte avec la souris, comme on peut le faire avec n'importe quel icône sur le bureau par exemple. Si je fais un clic-droit sur la barre elle fait une rotation, Shif+clic gauche c'est un centrage verticale, shif+clic gauche c'est un centrage horizontale.
D'abord, une remarque : superbe !
Ensuite : pour déplacer les éléments visuels, tu dois faire un drag'n' drop ? Sache que sous goocanvas, il est très facile de faire des "poignées" autour d'un objet ; pour peu que ces "poignées" soient le dernier élément ajouté, il se comporte comme un sprite, et n'efface pas le contexte en arrière-plan. Cela devrait donc répondre à ta préoccupation.
Voici comment je procède pour afficher/ effacer la position sur la timeline (petit triangle gris sur la règle) :afficher à la position image "position" en tenant compte de la taille des graduations :
/************************************/
/* afficher le curseur de la règle */
/**********************************/
void affiche_curseur_regle(GooCanvasItem *root, gint position)
{
pRulerCursorItem = goo_canvas_image_new(root,
GDK_PIXBUF(pIcoRulerCursor),
position*RULER_WIDTH+(RULER_WIDTH/2)-6,
RULER_HEIGHT-12,NULL);
}
effacer le curseur sans abîmer l'arrière-plan (une seule ligne de code ...) :
/**********************************/
/* effacer le curseur de la règle */
/**********************************/
void efface_curseur_regle(void)
{
goo_canvas_item_remove(pRulerCursorItem);
}
Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1
Projet Ella sur launchpad : https://launchpad.net/ella
Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance
et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html
Hors ligne
philarmonie
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
D'abord, une remarque : superbe !
Merci, c'est le thème que j'ai au démarrage de mon pc
Ensuite : pour déplacer les éléments visuels, tu dois faire un drag'n' drop ? Sache que sous goocanvas, il est très facile de faire des "poignées" autour d'un objet ; pour peu que ces "poignées" soient le dernier élément ajouté, il se comporte comme un sprite, et n'efface pas le contexte en arrière-plan. Cela devrait donc répondre à ta préoccupation.
Oui c'est du drag'n drop. Qu'entends tu par sprite et n'efface pas le contexte en arrière plan? Tu veux dire que si je déplace la barre par exemple, la partie du background qui occupe l'ancienne position redevient visible? Ce comportement j'ai effectivement du en écrire le code.
Voici comment je procède pour afficher/ effacer la position sur la timeline (petit triangle gris sur la règle) :
afficher à la position image "position" en tenant compte de la taille des graduations :<metadata lang=R prob=0.14 />
/************************************/
/* afficher le curseur de la règle */
/**********************************/
void affiche_curseur_regle(GooCanvasItem *root, gint position)
{
pRulerCursorItem = goo_canvas_image_new(root,
GDK_PIXBUF(pIcoRulerCursor),
position*RULER_WIDTH+(RULER_WIDTH/2)-6,
RULER_HEIGHT-12,NULL);
}
effacer le curseur sans abîmer l'arrière-plan (une seule ligne de code ...) :<metadata lang=CSS prob=0.12 />
/**********************************/
/* effacer le curseur de la règle */
/**********************************/
void efface_curseur_regle(void)
{
goo_canvas_item_remove(pRulerCursorItem);
}
Effectivement ça demande pas beaucoup de ligne de code, c'est pratique.
Comme je code en python, faut que je regarde si goocanvas a été porté en python.
Dernière modification par philarmonie (Le 15/06/2009, à 18:11)
kevlar
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
> oui, un sprite est un objet, initialement destiné aux jeux videos, dont le comportement s'apparente à ton pointeur de souris : déplacement propre, se met en superposition en respectant le fond pour peu que le GdkPixbuf source ait des parties transparentes.
> tu as de la chance : porté en Python, et en plus, Google te renverra une foultitude d'exemples en python, et quasiment rien en C
> en fait, goocanvas contient l'essentiel pour faire un éditeur vectoriel, un peu ce que fais ton programme ...
Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1
Projet Ella sur launchpad : https://launchpad.net/ella
Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance
et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html
Hors ligne
kevlar
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
voici la nouvelle version : au menu, utilisation, comme dit précédemment, de la bibliothèque goocanvas, et, nouveauté, du modèle GtkListStore, GtkTreeView :
- la partie "calques" à gauche est une GtkTreeView, parfaitement fonctionnelle (édition, duplication ...)
- la partie de droite(règle, time line) est construite à partir de goocanvas.
Dernière modification par kevlar (Le 18/06/2009, à 17:27)
Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1
Projet Ella sur launchpad : https://launchpad.net/ella
Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance
et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html
Hors ligne
kevlar
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
le code est très simple :
1- créer une fonction génératrice pour le menu déroulant :
void timeline_popup_menu_(GdkEventButton *event)
{
GtkWidget *menu, *item;
menu = gtk_menu_new ();
// this opens the downloader window, or brings it to the foreground if already open
item = gtk_menu_item_new_with_mnemonic (("_Créer une image-clé"));
g_signal_connect_swapped (item, "activate",G_CALLBACK (cb_new_keyframe), NULL);
gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
item = gtk_menu_item_new_with_mnemonic (("_Supprimer l'image-clé"));
g_signal_connect_swapped (item, "activate",G_CALLBACK (cb_remove_keyframe), NULL);
gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
gtk_widget_show_all (menu);
gtk_menu_popup (GTK_MENU (menu), NULL, NULL, NULL,
NULL,/* pointeur datas */
event->button, /* bouton de la souris, automatique */
event->time); /* moment du clic, automatique */
}
2- brancher cette fonction dans la callback répondant aux clics-souris :
/****************************
* réponse aux clics-souris
* sur la timeline
* *************************/
static gboolean
on_timeline_button_press(GooCanvasItem *item,
GooCanvasItem *target,
GdkEventButton *event,
GtkWidget *win)
{
/* clic-gauche ou clic-droit ? */
if (event->button==3)
/* clic droit */
{
timeline_popup_menu_(event);
}
Dernière modification par kevlar (Le 20/06/2009, à 17:30)
Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1
Projet Ella sur launchpad : https://launchpad.net/ella
Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance
et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html
Hors ligne
kevlar
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1
Projet Ella sur launchpad : https://launchpad.net/ella
Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance
et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html
Hors ligne
kevlar
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
aujourd'hui : gestion des sélections à la souris sur la time line (partie en vert de cette copie = zone sélectionnée). Les contrôles sont faits : impossible de sélectionner une zone ne contenant pas d'images, par exemple.
en fait, gérer une sélection est très simple, après branchement des événements "motion_notify", et "button-release" sur les éléments du goocanvas.
Reste une limite (si quelqu'un passe avec une idée ... ) : comment, lors de la sélection d'une zone, assurer en même temps le scrolling de la fenêtre dans laquelle se déplace la souris ? Faut-il réutiliser l'événement "motion_notify", et, lorsque le pointeur est à l'une des limites, provoquer le scrolling ? A voir !
Dernière modification par kevlar (Le 22/06/2009, à 14:56)
Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1
Projet Ella sur launchpad : https://launchpad.net/ella
Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance
et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html
Hors ligne
kevlar
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
après une période de sommeil, voici le travail du jour : la mise en place d'une barre d'outils, destinée à l'hypothétique éditeur vectoriel qui sera (peut-être) un jour associé au programme ...
Cette barre est construite avec les méthodes postérieures à Gtk 2.4 (voire même 2.12) ; elle est remplie d'icônes qui sont des gtk_radio_tool_button ; les fonctions de "markup" sont mises à profit pour enrichir le texte du titre de la barre d'outils, et les tooltips sont actifs, comme vous le voyez sur la copie.
Le choix de boutons radio permet de n'avoir, automatiquement, qu'un seul outil activé à la fois, géré avec une callback réagissant à à l'événement toggled
Dernière modification par kevlar (Le 02/07/2009, à 20:43)
Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1
Projet Ella sur launchpad : https://launchpad.net/ella
Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance
et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html
Hors ligne
kevlar
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1
Projet Ella sur launchpad : https://launchpad.net/ella
Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance
et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html
Hors ligne
kevlar
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
Et maintenant, la dernière étape facile ! Intégrer la barre d'outils dans une fenêtre contenant elle-même un GtkNotebook, qui portera, lui, , d'une part, l'éditeur vectoriel (le gros, gros morceau ), et, d'autre part, le lecteur flash, servant à la prévisualisation (beaucoup plus facile, grâce aux bibliothèques swfdec :
L'éditeur vectoriel va utiliser au maximum la bibliothèque goocanvas, parfaitement adaptée à cet usage
Dernière modification par kevlar (Le 03/07/2009, à 14:32)
Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1
Projet Ella sur launchpad : https://launchpad.net/ella
Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance
et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html
Hors ligne
haile_selassie
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
Hop, sujet en marque-pages, ça m'intéresse
Beau boulot, continue à donner des nouvelles!
Hors ligne
kevlar
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
oui, tu devines l'objectif final, mais c'est encore loin, loin ...
Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1
Projet Ella sur launchpad : https://launchpad.net/ella
Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance
et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html
Hors ligne
haile_selassie
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
oui, tu devines l'objectif final, mais c'est encore loin, loin ...
Certainement. Mais perso, quand je programme, ce que j'aime, c'est apprendre de nouveaux trucs. Après, finir les objectifs que tu t'es fixés, c'est sur que c'est super plaisant aussi ^^
Tu es tout seul à le programmer ? non pas que je veuille t'aider, je ne connais pas GTK, mais ça parait quand meme ambitieux pour le réaliser seul, non?
Hors ligne
kevlar
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
oui, tout seul, c'est effectivement fait sur le mode "loisirs", donc pas de contraintes ...:lol:
Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1
Projet Ella sur launchpad : https://launchpad.net/ella
Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance
et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html
Hors ligne
kevlar
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
ce matin, début de mise en place réelle de l'éditeur vectoriel : tracé de lignes simples :
les autres figures ne posent pas plus de problèmes ; ce qu'il faut, maintenant, c'est gérer en interne une base de données référençant tous les goocanvasitem (s) utilisés par l'éditeur vectoriel, et, d'autre part, associer les groupes de dessins au bon calque ...
Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1
Projet Ella sur launchpad : https://launchpad.net/ella
Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance
et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html
Hors ligne
kevlar
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
aujourd'hui :
- éditeur vectoriel complété avec les fonctions de tracés de boîtes (box) et de cercles (ellipses)
- amélioration de la barre d'outils : j'ai ajouté la possibilité de choisir le style de ligne (icône en forme d'engrenage) et le style de texte (icône avec deux "A") ; les icônes de réglage sont regroupées dans la palette dans une rubrique "styles"
- pour le projet lui-même, je pense que je vais associer à chacun des calques de la timeline( voir post #40) un élément très pratique de la bibliothèque goocanvas : les "groupes d'objets" ; l'astuce est de n'avoir qu'un seul canvas, dans lequel chaque calque forme un groupe, et chaque calque pourra pointer sur d'autres groupes d'objets ; ainsi, effacer un calque effacera tous les objets qu'il contient, sans toucher au reste du canvas.
Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1
Projet Ella sur launchpad : https://launchpad.net/ella
Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance
et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html
Hors ligne
kevlar
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
bon, aujourd'hui, grosse rigolade (:(:(:() : tenter de modifier le style de trait en utilisant goocanvas ; pas le moindre exemple sur le net, documentation ultra limitée ; enfin, en croisant avec la documentation de cairo, et quelques erreurs de segmentation après, voici un code tout simple qui permet de préparer la mise en place de la sélection des objets par l'éditeur vectoriel ; voici le code du rectangle de sélection utilisant goocanvas:
/**********************************
* rectangle de sélection en cours
* *******************************/
void selection_box(GooCanvasItem *ancetre, gdouble x1t,gdouble y1t,gdouble x2t,gdouble y2t)
{
gdouble t;
static const double dashed1[] = {4.0, 4.0};
static int len1 = sizeof(dashed1) / sizeof(dashed1[0]);
GooCanvasLineDash *style_trait;
style_trait=goo_canvas_line_dash_newv(len1,(gdouble *)dashed1);
SelectedArea=TRUE;
/* vérifier les valeurs des coins */
if (x2t<x1t)
{
t=x1t;
x1t=x2t;
x2t=t;
}
if (y2t<y1t)
{
t=y1t;
y1t=y2t;
y2t=t;
}
pDrawings=goo_canvas_rect_new(ancetre,
x1t+10,y1t+10,
x2t-x1t,y2t-y1t,
"line-width", 2.0,
"radius-x", 1.0,
"radius-y", 1.0,
"stroke-color", "blue",
"line-dash", style_trait,
NULL);
}
Dernière modification par kevlar (Le 07/07/2009, à 16:30)
Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1
Projet Ella sur launchpad : https://launchpad.net/ella
Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance
et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html
Hors ligne
|
Kalyst
[resolu] (Re)installer Synaptic ?
Bonjour a tous,
Suite au probleme de :
Synaptic Package Manager et mise à jour du 18.8
http://forum.ubuntu-fr.org/viewtopic.php?id=56039
Et bien avant de voir cette solution sur le forum, j'ai voulu reinstaller Synaptic (un vieux reflexe à banir, j'ai bien compris... ). Pour cela j'ai fait un :
apt-get remove synaptic
Alors que je relance l'installation j'ai le retour suivant (apt-get update et upgrade effectué)
root@symoon-desktop:~# sudo apt-get install synaptic
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances... Fait
Aucune version du paquet synaptic n'est disponible, mais il existe dans la base
de données. Cela signifie en général que le paquet est manquant, qu'il est devenu obsolète
ou qu'il n'est disponible que sur une autre source
E: Aucun paquet ne correspond au paquet synaptic
Mes sources depot :
deb-src http://fr.archive.ubuntu.com/ubuntu/ dapper main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://fr.archive.ubuntu.com/ubuntu/ dapper-updates main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu/ dapper-updates main restricted
## Uncomment the following two lines to add software from the 'universe'
## repository.
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## universe WILL NOT receive any review or updates from the Ubuntu security
## team.
deb-src http://fr.archive.ubuntu.com/ubuntu/ dapper universe
## Uncomment the following two lines to add software from the 'backports'
## repository.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://fr.archive.ubuntu.com/ubuntu/ dapper-backports main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ dapper-backports main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu dapper-security main restricted
deb-src http://security.ubuntu.com/ubuntu dapper-security main restricted
# deb http://security.ubuntu.com/ubuntu dapper-security universe
# deb-src http://security.ubuntu.com/ubuntu dapper-security universe
deb http://www.beerorkid.com/compiz/ dapper main
deb http://ubuntu.compiz.net/ dapper main
deb http://packages.freecontrib.org/plf/ dapper free non-free
deb http://packages.freecontrib.org/freecontrib/ dapper free non-free
deb http://people.ubuntubrasil.org/~rclbelem/lives/dapper/ binary/
deb http://theli.free.fr/packages/ dapper listen
deb http://packages.freecontrib.org/ubuntu/plf/ dapper free non-free
Bien à vous,
Kalyst.
Dernière modification par Kalyst (Le 20/08/2006, à 14:06)
Hors ligne
gpocentek
Re : [resolu] (Re)installer Synaptic ?
Ajoute "deb http://fr.archive.ubuntu.com/ubuntu/ dapper main restricted" quelque part.
Hors ligne
Kalyst
Hors ligne
|
I have connected creating of user with the function create_user_profile, the problem comes when i create i user, i seems the connected functions is called twice and UserPRofile is trying to be created twice, witch fires an error
column user_id is not unique
Request Method: POST
Request URL: http://127.0.0.1:8000/register/
Django Version: 1.3
Exception Type: IntegrityError
Exception Value:
column user_id is not unique
Exception Location: c:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 234
Python Executable: c:\Python27\python.exe
Python Version: 2.7.2
here is the debug log:
[13/Apr/2012 10:20:57] "GET /register/ HTTP/1.1" 200 176691
DEBUG:django.db.backends:(0.002) SELECT "auth_user"."id", "auth_user"."username",
"auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_us
er"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_
superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user"
WHERE "auth_user"."last_name" = favicon ; args=(u'favicon',)
DEBUG:django.db.backends:(0.001) SELECT "auth_user"."id", "auth_user"."username",
"auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_us
er"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_
superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user"
WHERE "auth_user"."last_name" = testuser2 ; args=(u'testuser2',)
DEBUG:django.db.backends:(0.000) SELECT "auth_user"."id", "auth_user"."username",
"auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_us
er"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_
superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user"
WHERE "auth_user"."username" LIKE testuser2@gmail.com ESCAPE '\' ; args=(u'testus
er2@gmail.com',)
DEBUG:django.db.backends:(0.001) INSERT INTO "auth_user" ("username", "first_name
", "last_name", "email", "password", "is_staff", "is_active", "is_superuser", "la
st_login", "date_joined") VALUES (testuser2@gmail.com, , , testuser2@gmail.com, s
ha1$9bc1b$c9d377a1bf228ef74eb6931a9ed02d5c455e1576, False, True, False, 2012-04-1
3 10:21:13.949000, 2012-04-13 10:21:13.949000); args=(u'testuser2@gmail.com', '',
'', u'testuser2@gmail.com', 'sha1$9bc1b$c9d377a1bf228ef74eb6931a9ed02d5c455e1576
', False, True, False, u'2012-04-13 10:21:13.949000', u'2012-04-13 10:21:13.94900
0')
====================================
=
DEBUG:django.db.backends:(0.002) INSERT INTO "page_userprofile" ("user_id", "thum
b", "name", "title", "description", "phone", "birthday", "address", "lat", "lng",
"gender", "creation_date", "updation_date") VALUES (13, , , , , , None, , , , ,
2012-04-13 10:21:14.131000, 2012-04-13 10:21:14.131000); args=(13, '', '', '', ''
, '', None, '', '', '', '', u'2012-04-13 10:21:14.131000', u'2012-04-13 10:21:14.
131000')
DEBUG:django.db.backends:(0.002) INSERT INTO "page_pagesettings" ("user_id", "bac
kground_url", "background_repeat", "showAvatar", "showTags", "color_background",
"color_panel_background", "color_panel_background_opacity", "color_name", "color_
title", "color_description", "color_links", "font_name", "font_title", "font_desc
ription", "font_tags_and_links", "font_size_name", "font_size_title", "font_size_
description", "font_size_tags_and_links", "can_contact_via_email", "panel_positio
n") VALUES (13, , 0, False, True, , , , , , , , , , , , , , , , True, ); args=(13
, '', u'0', False, True, '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', True, '')
====================================
=
DEBUG:django.db.backends:(0.002) INSERT INTO "page_userprofile" ("user_id", "thum
b", "name", "title", "description", "phone", "birthday", "address", "lat", "lng",
"gender", "creation_date", "updation_date") VALUES (13, , , , , , None, , , , ,
2012-04-13 10:21:14.442000, 2012-04-13 10:21:14.442000); args=(13, '', '', '', ''
, '', None, '', '', '', '', u'2012-04-13 10:21:14.442000', u'2012-04-13 10:21:14.
442000')
DEBUG:django.db.backends:(0.000) SELECT "page_userprofile"."id", "page_userprofil
e"."user_id", "page_userprofile"."thumb", "page_userprofile"."name", "page_userpr
ofile"."title", "page_userprofile"."description", "page_userprofile"."phone", "pa
ge_userprofile"."birthday", "page_userprofile"."address", "page_userprofile"."lat
", "page_userprofile"."lng", "page_userprofile"."gender", "page_userprofile"."cre
ation_date", "page_userprofile"."updation_date" FROM "page_userprofile" LIMIT 21;
args=()
DEBUG:django.db.backends:(0.000) SELECT "auth_user"."id", "auth_user"."username",
"auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_us
er"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_
superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user"
WHERE "auth_user"."id" = 1 ; args=(1,)
DEBUG:django.db.backends:(0.000) SELECT "auth_user"."id", "auth_user"."username",
"auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_us
er"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_
superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user"
WHERE "auth_user"."id" = 2 ; args=(2,)
DEBUG:django.db.backends:(0.000) SELECT "auth_user"."id", "auth_user"."username",
"auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_us
er"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_
superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user"
WHERE "auth_user"."id" = 4 ; args=(4,)
DEBUG:django.db.backends:(0.000) SELECT "auth_user"."id", "auth_user"."username",
"auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_us
er"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_
superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user"
WHERE "auth_user"."id" = 5 ; args=(5,)
DEBUG:django.db.backends:(0.000) SELECT "auth_user"."id", "auth_user"."username",
"auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_us
er"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_
superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user"
WHERE "auth_user"."id" = 7 ; args=(7,)
DEBUG:django.db.backends:(0.000) SELECT "auth_user"."id", "auth_user"."username",
"auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_us
er"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_
superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user"
WHERE "auth_user"."id" = 8 ; args=(8,)
DEBUG:django.db.backends:(0.001) SELECT "auth_user"."id", "auth_user"."username",
"auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_us
er"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_
superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user"
WHERE "auth_user"."id" = 9 ; args=(9,)
DEBUG:django.db.backends:(0.001) SELECT "auth_user"."id", "auth_user"."username",
"auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_us
er"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_
superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user"
WHERE "auth_user"."id" = 10 ; args=(10,)
DEBUG:django.db.backends:(0.000) SELECT "auth_user"."id", "auth_user"."username",
"auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_us
er"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_
superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user"
WHERE "auth_user"."id" = 11 ; args=(11,)
DEBUG:django.db.backends:(0.000) SELECT "auth_user"."id", "auth_user"."username",
"auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_us
er"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_
superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user"
WHERE "auth_user"."id" = 12 ; args=(12,)
DEBUG:django.db.backends:(0.000) SELECT "auth_user"."id", "auth_user"."username",
"auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_us
er"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_
superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user"
WHERE "auth_user"."id" = 13 ; args=(13,)
[13/Apr/2012 10:21:15] "POST /register/ HTTP/1.1" 500 446959
DEBUG:django.db.backends:(0.001) SELECT "auth_user"."id", "auth_user"."username",
"auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_us
er"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_
superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user"
WHERE "auth_user"."last_name" = favicon ; args=(u'favicon',)
Connection:
def create_user_profile(sender, instance, created, **kwargs):
if created:
print('')
print('')
print('=========================================')
print('')
print('')
UserProfile.objects.create(user=instance)
PageSettings.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
creating the user:
newUser = User.objects.create_user(username, username, password)
newUser.last_name = slug
if(registerAs == 'company'):
newUser.first_name = 'company'
else:
newUser.first_name = 'user'
#newUser.save()
|
I am looking for a definitive answer to MATLAB's parfor for Python (Scipy, Numpy).
Is there a solution similar to parfor? If not, what is the complication for creating one?
UPDATE: Here is a typical numerical computation code that I need speeding up
import numpy as np
N = 2000
output = np.zeros((N,N))
for i in range(N):
for j in range(N):
output(i,j) = HeavyComputationThatIsThreadSafe(i,j)
An example of a heavy computation function is:
import scipy.optimize
def HeavyComputationThatIsThreadSafe(i,j):
n = i * j
return scipy.optimize.anneal(lambda x: np.sum((x-np.arange(n)**2)), np.random.random((n,1)))[0][0,0]
|
def sendmail(self, from_addr, to_addrs, msg='hello', mail_options=[],rcpt_options=[]):
self.ehlo_or_helo_if_needed()
esmtp_opts = []
if self.does_esmtp:
# Hmmm? what's this? -ddm
# self.esmtp_features['7bit']=""
if self.has_extn('size'):
esmtp_opts.append("size=%d" % len(msg))
for option in mail_options:
esmtp_opts.append(option)
(code, resp) = self.mail(from_addr, esmtp_opts)
if code != 250:
self.rset()
#raise SMTPSenderRefused(code, resp, from_addr)
senderrs = {}
if isinstance(to_addrs, basestring):
to_addrs = [to_addrs]
for each in to_addrs:
(code, resp) = self.rcpt(each, rcpt_options)
if (code != 250) and (code != 251):
senderrs[each] = (code, resp)
if len(senderrs) == len(to_addrs):
# the server refused all our recipients
self.rset()
#raise SMTPRecipientsRefused(senderrs)
(code, resp) = self.data(msg)
if code != 250:
self.rset()
#raise SMTPDataError(code, resp)
#if we got here then somebody got our mail
return senderrs
I am trying to build my own smtplib.I am getting TypeError: 'NoneType' object is not iterable when i try
(code, resp) = self.data(msg)
self.data() is defined as- I am using self.data() to put the message to the server.
def data(self, msg):
self.putcmd("data")
(code, repl) = self.getreply()
if self.debuglevel > 0:
print>>stderr, "data:", (code, repl)
if code != 354:
#raise SMTPDataError(code, repl)
print "Err"
else:
q = quotedata(msg)
if q[-2:] != CRLF:
q = q + CRLF
q = q + "." + CRLF
self.send(q)
(code, msg) = self.getreply()
if self.debuglevel > 0:
print>>stderr, "data:", (code, msg)
return (code, msg)
|
smo
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
ola
ok cool je vais regarder ca apres, la j en fais un "normalement" c est un peu (beaucoup...) plus complique pour les ppa
j vous tiens au jus !
et whoue si vous avez des idees, hesitez pas hein ... j aimerais bien avoir des visualisations quand c est un son qui est lu a la place du lecteur video pas que ca reste vide en tout cas !
++
Dernière modification par smo (Le 19/12/2010, à 21:17)
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
smo
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
ola
bon j ai rajoute le paquet dans mon ppa ! (GALERE!!!!)
infos ajoutées au post 1
faut que je refasse des screenshots...
Pensez a faire un sudo python setup.py uninstall avant d installer le ppa
++
Dernière modification par smo (Le 20/12/2010, à 08:24)
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
Merle
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
Pensez a faire un setup.py uninstall avant d installer le ppa
Salut j'ai ça quand j'entre la commande :
root@marijo-Inspiron-530s:~/gmediafinder# setup.py uninstall
setup.py : commande introuvable
Hors ligne
smo
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
Yup
sudo python setup.py uninstall
Pour être plus précis ...
++
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
Merle
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
Pas de veine :
root@marijo-Inspiron-530s:~/gmediafinder# sudo python setup.py uninstall
running uninstall
warning: uninstall: Could not read installed files list .installed_files
Hors ligne
smo
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
ola
non tant mieux c est que t avais rien d installé...
tu peux utiliser le ppa sans soucis...
++
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
Merle
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
Salut j'ai des problèmes avec le moteur tagoo.ru :
Quand je fais une première recherche sur "draconian" le logiciel ferme tout seul :
tagoo.ru engine selected
**
Gdk:ERROR:/build/buildd/gtk+2.0-2.22.0/gdk/gdkregion-generic.c:1110:miUnionNonO: assertion failed: (y1 < y2)
je réouvre et je refais la même recherche :
julien@marijo-Inspiron-530s:~$ gmediafinder
** Message: pygobject_register_sinkfunc is deprecated (GstObject)
/usr/local/lib/python2.6/dist-packages/GmediaFinder/gmediafinder.py:71: GtkWarning: IA__gtk_radio_button_set_group: assertion `!g_slist_find (group, radio_button)' failed
self.gladeGui = gtk.glade.XML(constants.glade_file, None ,constants.app_name)
tagoo.ru engine selected
Unhandled exception in thread started by <bound method GsongFinder.analyse_links of <GmediaFinder.gmediafinder.GsongFinder object at 0xb7778c4c>>
Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/GmediaFinder/gmediafinder.py", line 541, in analyse_links
self.add_sound(name, link_list[i)
File "/usr/local/lib/python2.6/dist-packages/GmediaFinder/gmediafinder.py", line 643, in add_sound
img = gtk.gdk.pixbuf_new_from_file_at_scale(os.path.join(self.img_path,'sound.png'), 64,64, 1)
glib.GError: Impossible d'ouvrir le fichier « /usr/local/share/gmediafinder/sound.png » : Aucun fichier ou dossier de ce type
/usr/local/lib/python2.6/dist-packages/GmediaFinder/gmediafinder.py:228: Warning: unable to set property `text' of type `gchararray' from value of type `GdkPixbuf'
gtk.main()
Dernière modification par Merle (Le 21/12/2010, à 13:15)
Hors ligne
smo
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
Yup
T as une vieille version ...
Refais le sudo setup.py install suivi d' un sudo setup.py uninstall
Et réinstalles le paquet Deb du ppa
++
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
Merle
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
root@marijo-Inspiron-530s:~# cd /home/julien/gmediafinder
root@marijo-Inspiron-530s:~/gmediafinder# sudo setup.py install
sudo: setup.py: command not found
Hors ligne
smo
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
Ola
1/ qu est ce que tu fais en compte root?
2/ tu fais sudo python setup.py install et uninstall après
T as (j'ai) oublie le python ...;)
++
Dernière modification par smo (Le 22/12/2010, à 02:54)
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
bargeot5999
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
ça a l'air bon comme petit soft....bonne continuation
Hors ligne
smo
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
hello
petite maj avec differents petits fix... surtout pour Windows mais aussi ubuntu
juste a mettre a jour par apt/synaptic etc...
le soft marche nickel sur windows aussi! (apres 1 heure pour installer l environnement python/gtk etc... calvaire) sauf la video de youtube qui s affiche sur tout le gui, bug de gtk apparemment sinon ca roule...)
++
Dernière modification par smo (Le 27/12/2010, à 06:16)
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
smo
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
ola
bon j ai refait un deb (en cours sur launchpad)
- ajout des visualisations sur les sons
- qqes fix
- malheureusement tagoo.ru est down !!! donc retiré ...
je vais chercher d autres sites plus tard pour voir...
assurez vous d avoir libvisual-0.4-plugins et libvisual-0.4 installé ( j ajouterais au prochain deb...)
a+
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
frenchy82
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
Salut smo,
En faisant un git pull je n'ai pas de mise à jour.
Tu ne passes plus par git ?
Hors ligne
smo
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
Ola
Yup j ai oublie de maj le git j te fais ça apres
++
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
frenchy82
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
Ok merci, cela marche super
Juste un petit truc : je ne suis pas sur que quand tu quittes GMF il libere la mémoire. Il semblerait que le processus python reste actif avec aux alentours de 80 Mo mais je peux me tromper
Un petit bouton pour arrêter la recherche serait un petit plus
PS: Je viens de voir cette news sur le site de Korben. Non pas que le soft soit intéressant par rapport au tient (il en est bien loin), mais le site à pas mal de mp3.
Hors ligne
smo
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
ola
frenchy
- je n ais pas remarqué ce problem de sortie avec python, je vais regarder de plus pres mais ca m etonnerait (sauf plantage)
- grooveshark c est mort, c est du flash et l api est assez obscure/introuvable j utilise que des sites avec des liens directs vers les mp3 ou des api au point comme youtube
un bouton arreter la recherche ? pour youtube ?
pour le soft, y a 3 soucis...
1/ si j utilise playbin2 on a l affichage de la duree du morceau qui marche nickel mais pas de visualisations du tout...
2/ si j utilise playbin 1 on a les visualisations mais la duree du morceau et donc la progression ne s affiche pas tout le temps, RELOU
actuellement j ai donc laissé sur playbin...
3/ pour dilandau et l ajout d autres moteurs et les problemes de parsing de page html, ca vient de beautifulsoup 3.1 qui a ete (betement pour moi) mis dans maverick voir lucid alors qu il est fait pour python3 que pas grand monde utilise encore et ca fou le bordel, c est de la que viennent les soucis de lecture des pages html !!!
je suis repasse en 3.0.8 et tout marche nickel mais des que je vais faire un apt-get upgrade y va me remettre la 3.1, donc faut que je cherche un moyen d interdire l installation de la version 3.1 et force la 3.0.8 depuis mon ppa ou truc du genre...
voila pour les infos, j ai rajoute un moteur mais je ne posterais plus de maj tant que ces soucis ne seront pas regles
++
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
smo
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
solution 1:
j ai testé la version 3.2 qui remarche correctement (debile...) du coup je fais mon propre paquet deb de cette librairie dans mon ppa comme ca tout le monde pourra l avoir et voila
edit:
bon cool, ca marche pepere et ca prend le dessus sur le paquet ubuntu comme il se doit et ca corrige donc le plus gros bug du soft...
du coup je post une maj avec un nouveau moteur, iwantmuzik.com
si vous trouvez des sites avec des mp3 en lien direct postez les !!!
reste a voir cette histoire de playbin/playbin2 ...
++
Dernière modification par smo (Le 30/12/2010, à 04:13)
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
frenchy82
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
Salut,
Je viens d'installer gmf par le depot.
Aucun probeme avec l'installation mais par contre j'ai bien un soucis de processus qui ne se ferme pas.
Je lance gmf, je le ferme par la croix et j'ai bien un processus gmf qui reste actif.
Si je le relance j'ai du coup un 2eme processus actif et ainsi de suite.
Je ne sais si quelqu'un d'autre peut le confirmer?
EDIT : si je lance gmediafinder par la console
** Message: pygobject_register_sinkfunc is deprecated (GstObject)
/usr/lib/pymodules/python2.6/GmediaFinder/gmediafinder.py:73: GtkWarning: IA__gtk_radio_button_set_group: assertion `!g_slist_find (group, radio_button)' failed
self.gladeGui = gtk.glade.XML(constants.glade_file, None ,constants.app_name)
^CTraceback (most recent call last):
File "/usr/bin/gmediafinder", line 26, in <module>
gmediafinder.GsongFinder()
File "/usr/lib/pymodules/python2.6/GmediaFinder/gmediafinder.py", line 242, in __init__
gobject.MainLoop().run()
KeyboardInterrupt
Le "KeyboardInterrupt", c'est parce que je dois faire un ctrl C pour reprendre la main sur la console après avoir quitté gmf
en sachant que les lignes
Traceback (most recent call last):
File "/usr/bin/gmediafinder", line 26, in <module>
gmediafinder.GsongFinder()
File "/usr/lib/pymodules/python2.6/GmediaFinder/gmediafinder.py", line 242, in __init__
gobject.MainLoop().run()
apparaissent apres le controle break
Dernière modification par frenchy82 (Le 30/12/2010, à 09:00)
Hors ligne
smo
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
Ola
Ok frenchy merci pour le retour je regarde ça en détail ce soir
++
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
smo
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
ola
bon je viens de faire un push dans le git et un nouveau deb est en cours, c est la fete!!, au menu :
- bug de la barre de progression et recuperation de la durée du morceau corrigé (cool!!) et ca fixe le probleme de bloquage du curseur quand on avance/recule dans le son par la meme occasion!
- bug de sortie du soft corrigé aussi j avais pas fait gaffe... merci frenchy pour le retour !
- fix sur l activation des options loop et continue, ca ne marchait pas correctement...
- tagoo.ru reouvert donc remis en place !!! (cool)
- j ai aussi reorganisé chouilla la position des boutons dans le gui, j attend vos avis la dessus...!! please !!
voila, pour moi en gros y a plus de bug ! hormis quelques warnings... !
j ai passé le bouzin en version 0.2 (faut que je fasse un about dialog quand meme..)
bon reveillon a tout le monde
++
Dernière modification par smo (Le 31/12/2010, à 05:05)
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
frenchy82
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
Tout marche nickel maintenant, félicitation
Vraiment, c'est un super soft!
Hors ligne
frenchy82
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
Salut smo,
J'imagine que le plein ecran s'annonce plutot complexe
Tu penses que ce serait faisable d'avoir un bouton "ouvrir la video dans le lecteur video par defaut"
Hors ligne
smo
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
ola
bah je vais bien y arriver y a un ptit truc qui doit m échapper normalement c est tout bête a faire ça me dit pas trop de faire un bouton ouvrir ...
Je vous tiens au courant
++
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
smo
Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus....
re
bon ja i pris ca pour un défi frenchy
Ajout du mode fullscreen ! suis assez content d moi sur ce coup la ...
ptite video de demo :
restera pt etre un fonction pour cacher automatiquement le petit player... (la j vois pas comment faire..)
creation du deb en cours sur le ppa
edit:
finalement j ai aussi reussi a cacher le petit player automatiquement
pour resumer :
- pour entrer en fulllscreen, soit double cliquer dans la video, soit touche f
- pour sortir, double clique ou touche echap
- par defaut la barre de controle reste affichee, si pas de mouvement de souris pdt 5 sec elle disparait OU simplement mettre la souris tout en bas pour l afficher ou la cacher
nouveau deb online sur le ppa, enjoy
++
Dernière modification par smo (Le 08/01/2011, à 04:40)
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
|
Deploying a Flask App on ep.io
Documenting my experience deploying a non-trivial Flask app to ep.io (in particular, one that needed custom per instance config and DB access).
PyBossa is a Flask app. ep.io have docs for Flask. However, the documentation is rather sparse and does not cover how to set up DB — tricky because ep.io provide DB connection info in a local python module — and do not cover, more generally, how to allow your Flask app access to standard Flask custom config.
The Process
Here’s how I did it.
Ensure your Flask App allows itself (using app.config.from_envvar) to get path to a custom config from an environment variable. E.g. in PyBossa have:
app.config.from_envvar('PYBOSSA_SETTINGS', silent=True)
Create a settings_epio.py (you could call this anything) as per a normal custom settings file. However we need to get DB info from ep.io bundle_config system.
I’m using SQLAlchemy and have its config stored in SQLALCHEMY_DATABASE_URI variable but this is easy to change if you have a different set up. So what we need to do is grab ep.io’s config info from bundle_config (see ep.io postgres service docs and use it to set our applications DB info:
from bundle_config import config
SQLALCHEMY_DATABASE_URI = 'postgresql://%s:%s@%s:%s/%s' % (
config['postgres']['username'],
config['postgres']['password'],
config['postgres']['host'],
int(config['postgres']['port']),
config['postgres']['database']
)
Finally, we need to have ep.io set up a database and set and environment variable so our app will pick up our config file. To do this edit your epio.ini file and add:
[services]
postgres = true
[env]
PYBOSSA_SETTINGS = ../settings_epio.py
Note that:
You will need to change PYBOSSA_SETTINGS to whatever environment variable you used in your app.config.from_pyvar (see abbove)
We have to use a relative path (you can work out the absolute path to your app by doing something like epio run_command pwd. However, this directory seems to change from moment to moment!)
Finally: let’s upload our work (automatically reloading the server):
epio upload
And you can see it all working at: http://pybossa.ep.io/
Other tips and tricks
You can run commands via run_command. For example, to initialize the PyBossa database we need to use the cli.py script (also uploaded to the server):
epio run_command "./cli.py db_create"
|
put the following in your db.py model (or any other)
import os.path
if not auth.is_logged_in() and db(db.auth_user.id>0).count() and not os.path.exists(os.path.join(request.folder, 'LOCK')) and (request.env.remote_addr in '127.0.0.1 localhost'.split()):
from gluon.storage import Storage
user = db(db.auth_user.id==1).select().first()
auth.user = Storage(auth.settings.table_user._filter_fields(user, id=True))
auth.environment.session.auth = Storage(user=user, last_visit=request.now,
expiration=auth.settings.expiration)
response.flash = 'You were automatically logged in as %s %s.<br/> To prevent this create the file %s'%(user.first_name, user.last_name, os.path.join(request.folder, 'LOCK'))
You will be automatically logged in as the first user if you call your web2py app from localhost or 127.0.0.1 you can prevent this behavior by creating a file called LOCK in your application root directory
|
AnsuzPeorth
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Re,
La suppression des logs se fait au démarrage de l'appli, pas du mediacenter ! (en tout cas chez moi ça marche).
Pour le systray, je t'ai ajouté une petit image clicable gnome
J'ai ajouté la possibilité de créer/supprimer les lanceurs depuis l'appli (il est aussi possible de le faire depuis install_lanceur.py directement.)
Pour l'installation, je pense pas nécessaire de faire un script dédié, il suffit juste de coller le dossier dans médiacenter et lancer start.py (c'est à la portée de tout le monde !).
Pour le full_install (ton mediacenter et mon script), pareil, suffit de coller le dossier contenant l'ensemble où l'on veut , lancer start.py, c'est tout !
J'ai modifié le module de gestion des fichiers conf, il renumerote aussi lors d'un ajout.
A ce sujet, ca serait peut être bien de modifier le script perl qui gère ça dans mediacenter, pour que lui aussi renumerote correctement ? J'y connait rien en perl, mais je suis sure qu'une âme charitable sur ce forum pourrait s'y atteler (ca devrait pas être dur, 5 mn pour qql'un qui maîtrise perl ) ... c'est du pinaillage, j'avoue !
Enfin, ça c'est toi qui décide, c'est toi qui gère ta version du médiacenter
Je pense que tout est OK !!!
EDIT: Jai tjrs cette erreur :
apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName
Dans mon fichier de conf → Listen 192.168.1.20:26180
Si ca lui convient pas, pourquoi la config se mets sur cette adresse ???
Dernière modification par AnsuzPeorth (Le 10/03/2010, à 20:07)
Hors ligne
AnsuzPeorth
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Bon,
Y a un bug que je comprends pas trop, faudra que je m'y atèle serieux....
Problème de path pour la création des lanceurs (incomprehensible !) .... C'est pas commode sous python les path !
si je lance en console, de mon n'importe où, ca fonctionne, si je lance direct ou depuis le lanceur, plus accès à cette boite de dialogue .....!!!! Je comprends po!!!
Hors ligne
AnsuzPeorth
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
A y est .... (c'est vraiment spécial les path sous python, ou alors il existe une fonction que je ne connais pas..,ca doit être ça, sinon ....)
Enfin, le principal, c'est que ça fonctionne !
http://gwebradio.googlecode.com/files/G … ter.tar.gz
Hors ligne
perolrom
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Bonjour
Pour le message d'erreur, c'est un message qui n'a aucun impact, je n'ai jamais regardé comment l'enlever
Effectivement, la modification du fichier configure pour re-numéroter les partages serait bien mais il faudrait alors regarder si on a besoin de changer aussi cela lorsque les gens passe par le site web pour rajouter/supprimer des partages
Je t'avoue que j'ai eu la flemme de regarder toute cette partie en détails (je maitrise bien php pour les page web mais un peu moins perl)
Je regarde ta nouvelle version ce soir
A+
Rom1
Hors ligne
perolrom
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Salut!
Tout semble OK, il ne me manque l'icône que tu as rajouté pour envoyer l'appli au systray.
A+
Hors ligne
AnsuzPeorth
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Salut!
Tout semble OK, il ne me manque l'icône que tu as rajouté pour envoyer l'appli au systray.
A+
??? Ah bon, c'est une icones systeme pourtant !
Si tu pouvais regarder si elle est chez toi ?
/usr/share/icons/hicolor/16x16/apps/application-gnome.png
Thx
Hors ligne
perolrom
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Voici ce que j'ai dans le dossier :
rom1@rom1laptop:~$ ls -l /usr/share/icons/hicolor/16x16/apps/
total 596
-rw-r--r-- 1 root root 685 2009-10-05 14:07 alacarte.png
-rw-r--r-- 1 root root 725 2009-10-14 21:34 bluetooth-active.png
-rw-r--r-- 1 root root 725 2009-10-14 21:33 bluetooth.png
-rw-r--r-- 1 root root 899 2009-10-30 11:02 brasero.png
-rw-r--r-- 1 root root 692 2009-03-05 04:28 ccsm.png
-rw-r--r-- 1 root root 702 2009-11-06 00:10 checkbox.png
-rw-r--r-- 1 root root 645 2009-10-20 02:56 cheese.png
-rw-r--r-- 1 root root 367 2009-08-24 16:17 classviewer-class.png
-rw-r--r-- 1 root root 332 2009-08-24 16:17 classviewer-macro.png
-rw-r--r-- 1 root root 321 2009-08-24 16:17 classviewer-member.png
-rw-r--r-- 1 root root 320 2009-08-24 16:17 classviewer-method.png
-rw-r--r-- 1 root root 310 2009-08-24 16:17 classviewer-namespace.png
-rw-r--r-- 1 root root 287 2009-08-24 16:17 classviewer-other.png
-rw-r--r-- 1 root root 355 2009-08-24 16:17 classviewer-struct.png
-rw-r--r-- 1 root root 293 2009-08-24 16:17 classviewer-var.png
-rw-r--r-- 1 root root 797 2009-10-29 16:59 empathy.png
-rw-r--r-- 1 root root 732 2009-10-20 07:46 eog.png
-rw-r--r-- 1 root root 840 2009-11-11 10:04 evince.png
-rw-r--r-- 1 root root 617 2009-11-03 23:37 evolution-mail.png
-rw-r--r-- 1 root root 617 2009-11-03 23:37 evolution-memos.png
-rw-r--r-- 1 root root 769 2009-11-03 23:37 evolution.png
-rw-r--r-- 1 root root 818 2009-11-03 23:37 evolution-tasks.png
-rw-r--r-- 1 root root 856 2009-10-20 03:17 file-roller.png
-rw-r--r-- 1 root root 477 2009-10-14 01:36 filezilla.png
-rw-r--r-- 1 root root 1054 2009-11-06 11:26 f-spot.png
-rw-r--r-- 1 root root 429 2009-12-08 13:38 gdm-xnest.png
-rw-r--r-- 1 root root 866 2009-10-12 19:49 gdu-check-disk.png
-rw-r--r-- 1 root root 594 2009-10-12 19:49 gdu-detach.png
-rw-r--r-- 1 root root 696 2009-10-12 19:49 gdu-eject.png
-rw-r--r-- 1 root root 709 2009-10-12 19:49 gdu-encrypted-lock.png
-rw-r--r-- 1 root root 640 2009-10-12 19:49 gdu-encrypted-unlock.png
-rw-r--r-- 1 root root 783 2009-10-12 19:49 gdu-error.png
-rw-r--r-- 1 root root 730 2009-10-12 19:49 gdu-info.png
-rw-r--r-- 1 root root 657 2009-10-12 19:49 gdu-mount.png
-rw-r--r-- 1 root root 626 2009-10-12 19:49 gdu-raid-array.png
-rw-r--r-- 1 root root 690 2009-10-12 19:49 gdu-raid-array-start.png
-rw-r--r-- 1 root root 541 2009-10-12 19:49 gdu-raid-array-stop.png
-rw-r--r-- 1 root root 662 2009-10-12 19:49 gdu-smart-failing.png
-rw-r--r-- 1 root root 689 2009-10-12 19:49 gdu-smart-healthy.png
-rw-r--r-- 1 root root 658 2009-10-12 19:49 gdu-smart-threshold.png
-rw-r--r-- 1 root root 636 2009-10-12 19:49 gdu-smart-unknown.png
-rw-r--r-- 1 root root 778 2009-10-12 19:49 gdu-unmountable.png
-rw-r--r-- 1 root root 721 2009-10-12 19:49 gdu-unmount.png
-rw-r--r-- 1 root root 757 2009-10-12 19:49 gdu-warning.png
-rw-r--r-- 1 root root 830 2009-08-24 16:17 geany.png
-rw-r--r-- 1 root root 765 2010-01-05 17:29 gimp.png
-rw-r--r-- 1 root root 699 2009-09-22 11:26 gnome-aisleriot.png
-rw-r--r-- 1 root root 855 2009-09-22 11:26 gnome-blackjack.png
-rw-r--r-- 1 root root 546 2010-01-28 12:43 gnome-brightness-applet.png
-rw-r--r-- 1 root root 665 2009-10-20 12:08 gnome-codec-install.png
-rw-r--r-- 1 root root 743 2009-10-20 11:35 gnome-cpu-frequency-applet.png
-rw-r--r-- 1 root root 613 2009-10-20 08:03 gnome-display-properties.png
-rw-r--r-- 1 root root 651 2009-10-20 11:35 gnome-eyes-applet.png
-rw-r--r-- 1 root root 568 2009-09-22 11:26 gnome-glchess.png
-rw-r--r-- 1 root root 675 2009-09-22 11:26 gnome-glines.png
-rw-r--r-- 1 root root 562 2009-09-22 11:26 gnome-gnect.png
-rw-r--r-- 1 root root 749 2009-09-22 11:26 gnome-gnibbles.png
-rw-r--r-- 1 root root 649 2009-09-22 11:26 gnome-gnometris.png
-rw-r--r-- 1 root root 856 2009-09-22 11:26 gnome-iagno.png
-rw-r--r-- 1 root root 801 2010-01-28 12:43 gnome-inhibit-applet.png
-rw-r--r-- 1 root root 554 2009-09-22 11:26 gnome-klotski.png
-rw-r--r-- 1 root root 598 2009-09-22 11:26 gnome-mahjongg.png
-rw-r--r-- 1 root root 736 2009-09-22 11:26 gnome-mines.png
-rw-r--r-- 1 root root 598 2009-09-23 13:20 gnome-nettool.png
-rw-r--r-- 1 root root 824 2009-10-20 08:03 gnome-network-properties.png
-rw-r--r-- 1 root root 887 2009-10-19 15:59 gnome-panel-clock.png
-rw-r--r-- 1 root root 444 2009-10-19 15:59 gnome-panel-drawer.png
-rw-r--r-- 1 root root 740 2009-10-19 15:59 gnome-panel-fish.png
-rw-r--r-- 1 root root 711 2009-10-19 15:59 gnome-panel-force-quit.png
-rw-r--r-- 1 root root 571 2009-10-19 15:59 gnome-panel-launcher.png
-rw-r--r-- 1 root root 812 2009-10-19 15:59 gnome-panel-notification-area.png
-rw-r--r-- 1 root root 354 2009-10-19 15:59 gnome-panel.png
-rw-r--r-- 1 root root 160 2009-10-19 15:59 gnome-panel-separator.png
-rw-r--r-- 1 root root 390 2009-10-19 15:59 gnome-panel-window-list.png
-rw-r--r-- 1 root root 545 2009-10-19 15:59 gnome-panel-window-menu.png
-rw-r--r-- 1 root root 400 2009-10-19 15:59 gnome-panel-workspace-switcher.png
-rw-r--r-- 1 root root 1404 2010-01-28 12:43 gnome-power-manager.png
-rw-r--r-- 1 root root 738 2010-01-28 12:43 gnome-power-statistics.png
-rw-r--r-- 1 root root 864 2009-09-22 11:26 gnome-robots.png
-rw-r--r-- 1 root root 876 2009-09-22 11:26 gnome-samegnome.png
-rw-r--r-- 1 root root 748 2009-10-20 08:03 gnome-settings-default-applications.png
-rw-r--r-- 1 root root 846 2009-10-07 18:58 gnome-sound-recorder.png
-rw-r--r-- 1 root root 667 2009-10-20 11:35 gnome-sticky-notes-applet.png
-rw-r--r-- 1 root root 490 2009-09-22 11:26 gnome-sudoku.png
-rw-r--r-- 1 root root 641 2009-09-22 11:26 gnome-tali.png
-rw-r--r-- 1 root root 838 2009-09-22 11:26 gnome-tetravex.png
-rw-r--r-- 1 root root 917 2009-10-07 18:58 gnome-volume-control.png
-rw-r--r-- 1 root root 26840 2009-10-07 18:58 gnome-volume-control.svg
-rw-r--r-- 1 root root 782 2009-10-06 10:41 gparted.png
-rw-r--r-- 1 root root 613 2009-11-05 12:37 gsd-xrandr.png
-rw-r--r-- 1 root root 3479 2009-05-15 00:24 gsmartcontrol.png
-rw-r--r-- 1 root root 761 2009-10-15 19:01 hook-notifier.png
-rw-r--r-- 1 root root 746 2009-10-20 11:35 invest-applet.png
-rw-r--r-- 1 root root 793 2008-11-24 17:08 jockey-kde.png
-rw-r--r-- 1 root root 713 2008-11-24 17:08 jockey.png
-rw-r--r-- 1 root root 865 2009-09-24 19:18 lpi-bug.png
-rw-r--r-- 1 root root 7040 2009-09-24 19:18 lpi-bug.svg
-rw-r--r-- 1 root root 981 2009-09-24 19:18 lpi-help.png
-rw-r--r-- 1 root root 572 2009-09-24 19:18 lpi-translate.png
-rw-r--r-- 1 root root 8019 2009-09-24 19:18 lpi-translate.svg
-rw-r--r-- 1 root root 768 2009-10-12 19:49 nautilus-gdu.png
-rw-r--r-- 1 root root 874 2009-11-23 12:19 nautilus.png
-rw-r--r-- 1 root root 473 2009-10-15 04:48 nm-device-wired.png
-rw-r--r-- 1 root root 601 2009-10-15 04:48 nm-no-connection.png
-rw-r--r-- 1 root root 595 2009-10-15 04:48 nm-vpn-standalone-lock.png
lrwxrwxrwx 1 root root 44 2009-11-05 08:14 nxclient-admin.png -> /usr/NX/share/icons/16x16/nxclient-admin.png
lrwxrwxrwx 1 root root 46 2009-11-05 08:14 nxclient-desktop.png -> /usr/NX/share/icons/16x16/nxclient-desktop.png
lrwxrwxrwx 1 root root 43 2009-11-05 08:14 nxclient-icon.png -> /usr/NX/share/icons/16x16/nxclient-icon.png
lrwxrwxrwx 1 root root 45 2009-11-05 08:14 nxclient-wizard.png -> /usr/NX/share/icons/16x16/nxclient-wizard.png
-rw-r--r-- 1 root root 949 2010-02-20 09:51 ooo-base.png
-rw-r--r-- 1 root root 986 2010-02-20 09:51 ooo-calc.png
-rw-r--r-- 1 root root 972 2010-02-20 09:51 ooo-draw.png
-rw-r--r-- 1 root root 880 2010-02-20 09:51 ooo-gulls.png
-rw-r--r-- 1 root root 651 2010-02-20 09:51 ooo-impress.png
-rw-r--r-- 1 root root 872 2010-02-20 09:51 ooo-math.png
-rw-r--r-- 1 root root 850 2010-02-20 09:51 ooo-printeradmin.png
-rw-r--r-- 1 root root 947 2010-02-20 09:51 ooo-web.png
-rw-r--r-- 1 root root 796 2010-02-20 09:51 ooo-writer.png
-rw-r--r-- 1 root root 3618 2010-02-20 09:51 openofficeorg3-base.png
-rw-r--r-- 1 root root 3629 2010-02-20 09:51 openofficeorg3-calc.png
-rw-r--r-- 1 root root 3606 2010-02-20 09:51 openofficeorg3-draw.png
-rw-r--r-- 1 root root 3608 2010-02-20 09:51 openofficeorg3-impress.png
-rw-r--r-- 1 root root 3607 2010-02-20 09:51 openofficeorg3-math.png
-rw-r--r-- 1 root root 963 2010-02-20 09:51 openofficeorg3-printeradmin.png
-rw-r--r-- 1 root root 1043 2010-02-20 09:51 openofficeorg3-startcenter.png
-rw-r--r-- 1 root root 3586 2010-02-20 09:51 openofficeorg3-writer.png
-rw-r--r-- 1 root root 685 2009-10-20 05:33 orca.png
-rw-r--r-- 1 root root 678 2009-10-12 19:49 palimpsest.png
-rw-r--r-- 1 root root 878 2009-05-23 05:49 qutecom.png
-rw-r--r-- 1 root root 898 2009-10-15 19:01 reboot-notifier.png
-rw-r--r-- 1 root root 745 2010-01-16 17:32 rhythmbox.png
-rw-r--r-- 1 root root 773 2009-10-19 12:21 seahorse.png
-rw-r--r-- 1 root root 1005 2009-10-19 12:21 seahorse-preferences.png
-rw-r--r-- 1 root root 595 2009-10-23 12:51 session-properties.png
-rw-r--r-- 1 root root 913 2010-01-13 10:43 softwarecenter.png
-rw-r--r-- 1 root root 697 2009-10-15 19:01 software-update-available.png
-rw-r--r-- 1 root root 697 2009-10-15 19:01 software-update-urgent.png
-rw-r--r-- 1 root root 795 2009-10-23 05:08 time-admin.png
-rw-r--r-- 1 root root 617 2009-10-06 09:36 tomboy.png
-rw-r--r-- 1 root root 911 2009-11-11 10:08 totem.png
-rw-r--r-- 1 root root 841 2010-01-13 21:22 transmission.png
-rw-r--r-- 1 root root 986 2009-12-21 20:43 ubuntuone-client.png
-rw-r--r-- 1 root root 1031 2010-03-01 13:11 ubuntu-tweak.png
-rw-r--r-- 1 root root 964 2009-11-02 09:05 update-manager.png
-rw-r--r-- 1 root root 821 2009-10-19 14:36 vinagre.png
Hors ligne
perolrom
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
L'icone dont tu parles fait partie de gnome-app-install qui n'est pas installé par défaut
http://packages.ubuntu.com/search?searchon=contents&keywords=application-gnome.png&mode=filename&suite=karmic&arch=any
Hors ligne
AnsuzPeorth
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Ah bon, je me souviens plus d'avoir installé ça moi !!!! (ca commence à remonter aussi, suis tjrs sous hardy )
Je l'ai ajouté au package, qqles kilos de plus, c'est pas bien méchant !
Le post 1 a été mis à jour.
lien Gm9diaCenter :http://gwebradio2.googlecode.com/files/ … 1.1.tar.gz
lien full (mediacenter et Gm9diaCenter):http://gwebradio2.googlecode.com/files/ … ull.tar.gz
Dernière modification par AnsuzPeorth (Le 12/03/2010, à 00:31)
Hors ligne
ovalie
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Bonjour, petit souci quand je veux installer les lanceur :
ACTION ajouter lanceur menu applications
Traceback (most recent call last):
File "/home/ubuntu/mediacenter/Gm9diaCenter/install_lanceur.py", line 54, in ajout
f_app=open(lanceur_app,'w')
IOError: [Errno 2] Aucun fichier ou dossier de ce type: '/home/ubuntu/.local/share/applications/Gm9diaCenter.desktop'
je n'y comprend rien...
(je suis sous lucid)
Hors ligne
AnsuzPeorth-out
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Bjr,
Ce message apparait car le dossier n'existe pas !!!
Je vois que l'utilisateur est ubuntu, tu ne serais pas en live ?
J'ai pas fait d'essais sous lucid, mais je pense qu'il a garder l'architecture des dossiers qd même ?
Il suffit de créer le dossier, normalement, les logiciels installés en user installent leurs lanceurs dans ce dossier.
Le dossier local est caché (point devant son nom), CTRL+h pour les afficher.
/home/<user>/.local/share/applications
Hors ligne
ovalie
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Merci,
non je ne suis pas en live, j'ai mis "ubuntu" comme nom d'utilisateur.
j'ai créé le dossier "application" dans /home/ubuntu/.local/share/ puis ca a fonctionné.
sous karmic je n'avais pas eu a faire ça et mon nom était aussi ubuntu.
est ce normal que j'ai eu à créer ce dossier?
quoi qu'il en soit maintenant c'est bon.
Encore merci
Hors ligne
AnsuzPeorth-out
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
est ce normal que j'ai eu à créer ce dossier?
Tu n'as surement pas encore installé de soft en local, c'est sans doute pour ça !
Maintenant c'est fait, les autres softs n'auront plus à le faire (mais je pensais que c'était d'origine...faudra que je modifie mon script en sorte ...)
Hors ligne
fabeer
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
salut et merci pour le boulot qui a été fait...pour ma part je touche au but....j'arrive a voir la liste des films qui sont sur le dd du pc,depuis le média center de la tv...mais quand je clic pour démarrer la lecture, ça me dit :"chargement de la vidéo en cours" et puis ça retourne sur l'écran de sélection des films...une idée du problème?
Edit: et une question bete en passant....comment creer un raccourci sur le bureau pour demarrer l'interface graphique?
Merci par avance
Edit 2: problèmes resolus: pour le premier avec un reboot electrique du decodeur TV,pour le deuxieme,en cherchant un peu,un click droit sur la fenetre du programme et on envoie une icone sur le bureau...Merci a vous pour ce super travail
Dernière modification par fabeer (Le 13/08/2010, à 16:45)
Hors ligne
Gérard
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Bonsoir,
J'ai fait toutes les manipulations décrites.
Lorsque je lance install_lanceur.py, la petite fenêtre dans laquelle on choisi de cocher où mettre l'icone de lancement.
Un lanceur se met bien dans le dossier "applications /accessoires" Sur le bureau un icone de dossier sous-titré Gm9diaCenter.desktop.
Lorsque j'essaye de lancer le programme avec cette icone, qui est installée sur le bureau voici le message qui m'est retourné :
Lanceur d'application non fiable
Le lanceur d'application « Gm9diaCenter.desktop » n'est pas marqué comme fiable. Si vous ne connaissez pas la provenance de ce fichier, son lancement est potentiellement dangereux.
Je suis sous Ubuntu 10.10
Lorsque j'avais la version 10.04 tous fonctionnait bien.
D'où peu provenir le problème ?
Merci par avance pour l'aide apportée
Gérard
Dernière modification par Gérard (Le 25/10/2010, à 19:19)
En retard dans ce bas monde, pas en avance dans l'autre !
Hors ligne
AnsuzPeorth
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Lorsque j'avais la version 10.04 tous fonctionnait bien.
D'où peu provenir le problème ?
Peux être que les normes .desktop se sont renforcées, en tout cas, il y a une vérification maintenant ! (on se croirait sous windows !)
En ce moment, j'ai pas bien le temps d'y regarder (je suis sous hardy encore, donc ...).
Il faudrait que tu crée ton lanceur sur le bureau et dans le menu. Il devra pointer sur start.py qui se trouve dans le dossier Gm9diaCenter, qui lui même se trouve dans le dossier mediacenter, selon ton installation.
Hors ligne
Gérard
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Bonsoir AnsuzPeorth
Aucun résultat.
Rien ne se lance, dommage, ton programme était génial.
J'attends si tu avais un peu de temps à consacrer.
Bonne fin de semaine
Cordialement
En retard dans ce bas monde, pas en avance dans l'autre !
Hors ligne
tcit
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Re,
apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName
?
essaye ça
Cela avait fonctionné chez moi...mais je ne peux plus essayer pour les raisons que rom1 comprendra (j'ai plus le mediacenter).
Sinon pourrait-on essayer de distribuer le programme en .deb ? Y a des méthodes pour le python. Le développeur pourrait reprendre les fichiers glade et les faire passer sur quickly. Sinon y a Py2deb qui pourrait peut-etre marcher.
Je dis cela car j'ai essayé moi même de faire mon petit programme tout a fait identique en packet (ici si ca intéresse qqn). mais cela n'avait jamais fonctionné, je n'avais en plus pas le temps...
Dernière modification par tcit (Le 03/11/2010, à 21:43)
Hors ligne
Kanor
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
J'ai trouvé un bug le status affiché n'est pas correct j'ai une correction possible mais c'est vraiment pas jolie
dans actionmedia.py
def status():
#os.chdir(os.pardir)
lacmd =subprocess.Popen(['../mediacenter','status'],
stdout=subprocess.PIPE)
var =lacmd.communicate()
#os.chdir('Gm9diaCenter')
print 'RESULT status :',var
if re.search('running',var[0]):
return ' Status : running'
elif re.search('stopped',var[0]):
return ' Status : stopped'
else:
return ' Status impossible'
tu devrais penser à utiliser des espace à la place des tabulations
Hors ligne
AnsuzPeorth
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
@Gérard
Dsl, mais pa eu le temps d'y regarder... Et j'ai tjrs pas upgrade, donc ....
J'ai trouvé un bug le status affiché n'est pas correct j'ai une correction possible mais c'est vraiment pas jolie
dans actionmedia.py
Ah bon ! quel bug ? Tes modifications ne sont que sur le chemin (.. au lieur des os.chdir qui sont effectivement inutiles, je sais plus pourquoi j'ai fait ça ! Faut dire que c'était mon premier script pygtk !)
tu devrais penser à utiliser des espace à la place des tabulations
Arfff, fainéantise, qd tu nous tiens ....! C'est plus rapide une tab que des espaces ...
Hors ligne
Yafa
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Bonjour à toutezétous !
Je profite de cette petite appli bien sympatoche depuis bientôt 1 mois et j'aimerais relancer ce sujet avec une petite question !
J'ai configuré le lancement de Gm9diaCenter au démarrage de ma machine, jusque là tout se passe bien.
Mon ordinateur s'allume donc avec ce programme actif et l'icône de connexion allumé en vert.
Sur ma télévision, à l'allumage du décodeur sfr/neuf, l'ordinateur apparaît déconnecté. J'ai donc besoin de repasser Gm9diaCenter sur Rouge puis sur Vert pour l'obtenir.
Une explication à me fournir ? Voire même un solution pour m'économiser cette petite manip' ?
Hors ligne
AnsuzPeorth
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Bjr,
J'avais également ce problème, cela ne vient pas de l'appli, ni même d'apache. C'est le mediacenter qui merdoit.
A la page d'acceuil du mediacenter, là où sont les icones activé ou pas, je faisais une détection manuelle en plus, pour que le mediacenter puisse trouver le serveur et les partages.
Hors ligne
grandtoubab
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Salut,
Celui là me donne satisfaction
http://forum.sfr.fr/c-/t181645-mediacenter-linux.htm
Linux tout seul sur le disque dur Acer Aspire T650 :=))
RAM: 1,7 Gio, CPU: Intel® Pentium(R) 4 CPU 3.06GHz × 2. Carte graphique Gallium 0.4 on ATI RC410 (Radeon Xpress200)
Partition 1: Debian Jessie & Gnome Version 3.12, kernel 3.16.2-031602-generic
Partition 2: Ubuntu Trusty 14.04 & Unity
Hors ligne
Yafa
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Merci !!
Hors ligne
azorth
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Bonjour, et tout d'abord un grand merci pour cette appli que j'utilise depuis plus d'un an sans souci (sous 10.04).
J'ai quelques questions/remarques dû à ma récente installation de Precise Pangolin.
J'ai donc installé Ubuntu 12.04 hier et réinstallé quelques indispensables aujourd'hui dont Gm9diaCenter.
1. Problème au lancement du "start.py"
Désolé je n'ai malheureusement pas gardé le message d'erreur mais j'ai résolu le problème en installant des paquets "glade" supplémentaires qui ne semblent pas être par défaut dans la distribution 12.04. Maintenant ça semble ok, mais au final je ne sais même pas quel paquet permet l'utilisation correcte de l'appli puisque j'en ai installé plusieurs...
>> Si quelqu'un identifie le paquet précis il faudrait peut-être mettre à jour les infos d'installation.
2. Zone de notification
Avec Unity, lorsque je je veux mettre en notification avec la patte de Gnome, l'appli n’apparaît pas dans les notifications puisqu'il ne doit pas y avoir les notifications Gnome.
Quelqu'un aurait une solution ?
3. Tableau de bord
Je retrouve bien l'application via le tableau de bord sans rien faire de spécial (j'imagine grâce a la première exécution ok). Mais celle-ci apparaît dans les filtre "Accessoire".
Est-ce qu'il existe un moyen de l'associer au filtre "Multimédia" ?
Au final il y a 2 question plus lié a Unity qu'a l'application mais si vous avez des réponse je suis preneur
Hors ligne
|
I have an array that I have to add a new value to array value. I am new to arrays. how do I loop thru the array and add to the value in the existing array.
>>> print [x+2 for x in [1,2,3]]
[3, 4, 5]
>>>
a = [2, 3, 4]
for i in range(0, len(a)):
a[i] += 3
print a #prints [5, 6, 7]
If you are working with arrays and need to do some math I would definitely recommend you
Reason: The code reads more clearly and is very likely to be faster. Here an example what numpy can do:
In [1]: import numpy as np
In [2]: x = np.array([4,5,6,7,8])
In [3]: x+3
Out[3]: array([ 7, 8, 9, 10, 11])
In [4]: x**2
Out[4]: array([16, 25, 36, 49, 64])
In [5]: x>=6
Out[5]: array([False, False, True, True, True], dtype=bool)
For further reading I recommend the numpy tutorial.
|
i have two models
class A(models.Model):
name = models.CharField(50)
type = models.CharField(50)
class B(models.Model):
field1 = ForeignKeyField(A)
value = IntegerField()
I'd like to display a number of forms via a ModelFormSet (from model A) where each one of the forms displays in turn InlineFormSets (from model B) for all objects connected to the object.
How can i combine both modelformsets (model A) and inline formsets (mdoel B) on save method in django views?
|
I wrote a couple of Java classes—SingleThreadedCompute and MultithreadedCompute—to demonstrate the fact (or what I always thought was a fact!) that if you parallelize a compute-centric (no I/O) task on a single core machine, you don't get a speedup. Indeed my understanding is that parallelizing such tasks actually slows things down because now you have to deal with context-switching overhead. Well, I ran the classes and the parallel version unexpectedly runs faster: the single-threaded version is consistently running at just over 7 seconds on my machine, and the multithreaded version is consistently running at just over 6 seconds on my machine. Can anybody explain how this is possible?
Here are the classes if anybody wants to look or try it for themselves.
public final class SingleThreadedCompute {
private static final long _1B = 1000000000L; // one billion
public static void main(String[] args) {
long startMs = System.currentTimeMillis();
long total = 0;
for (long i = 0; i < _1B; i++) { total += i; }
System.out.println("total=" + total);
long elapsedMs = System.currentTimeMillis() - startMs;
System.out.println("Elapsed time: " + elapsedMs + " ms");
}
}
Here's the multithreaded version:
public final class MultithreadedCompute {
private static final long _1B = 1000000000L; // one billion
private static final long _100M = _1B / 10L;
public static void main(String[] args) {
long startMs = System.currentTimeMillis();
System.out.println("Creating workers");
Worker[] workers = new Worker[10];
for (int i = 0; i < 10; i++) {
workers[i] = new Worker(i * _100M, (i+1) * _100M);
}
System.out.println("Starting workers");
for (int i = 0; i < 10; i++) { workers[i].start(); }
for (int i = 0; i < 10; i++) {
try {
workers[i].join();
System.out.println("Joined with thread " + i);
} catch (InterruptedException e) { /* can't happen */ }
}
System.out.println("Summing worker totals");
long total = 0;
for (int i = 0; i < 10; i++) { total += workers[i].getTotal(); }
System.out.println("total=" + total);
long elapsedMs = System.currentTimeMillis() - startMs;
System.out.println("Elapsed time: " + elapsedMs + " ms");
}
private static class Worker extends Thread {
private long start, end;
private long total;
public Worker(long start, long end) {
this.start = start;
this.end = end;
}
public void run() {
System.out.println("Computing sum " + start + " + ... + (" + end + " - 1)");
for (long i = start; i < end; i++) { total += i; }
}
public long getTotal() { return total; }
}
}
Here's the output from running the single-threaded version:
total=499999999500000000
Elapsed time: 7031 ms
And here's the output from running the multithreaded version:
Creating workers
Starting workers
Computing sum 0 + ... + (100000000 - 1)
Computing sum 100000000 + ... + (200000000 - 1)
Computing sum 200000000 + ... + (300000000 - 1)
Computing sum 300000000 + ... + (400000000 - 1)
Computing sum 400000000 + ... + (500000000 - 1)
Computing sum 500000000 + ... + (600000000 - 1)
Computing sum 600000000 + ... + (700000000 - 1)
Computing sum 700000000 + ... + (800000000 - 1)
Computing sum 800000000 + ... + (900000000 - 1)
Computing sum 900000000 + ... + (1000000000 - 1)
Joined with thread 0
Joined with thread 1
Joined with thread 2
Joined with thread 3
Joined with thread 4
Joined with thread 5
Joined with thread 6
Joined with thread 7
Joined with thread 8
Joined with thread 9
Summing worker totals
total=499999999500000000
Elapsed time: 6172 ms
EDIT: Information on the environment:
Microsoft Windows XP Professional Version 2002, SP3
Dell Precision 670
Intel Xeon CPU 2.80GHz, 1 MB L2 cache
Not sure how to prove it's a single core machine other than by stating the spec above and by noting that back when I bought the machine (Aug 2005), single cores were the standard and I didn't upgrade to multicore (if that was even an option... I don't remember). If there's somewhere in Windows I can check other than System Properties (which shows the info above) let me know and I'll check.
Here are five consecutive ST and MT runs:
FIVE SINGLETHREADED RUNS:
total=499999999500000000 Elapsed time: 7000 ms
total=499999999500000000 Elapsed time: 7031 ms
total=499999999500000000 Elapsed time: 6922 ms
total=499999999500000000 Elapsed time: 6968 ms
total=499999999500000000 Elapsed time: 6938 ms
FIVE MULTITHREADED RUNS:
total=499999999500000000 Elapsed time: 6047 ms
total=499999999500000000 Elapsed time: 6141 ms
total=499999999500000000 Elapsed time: 6063 ms
total=499999999500000000 Elapsed time: 6282 ms
total=499999999500000000 Elapsed time: 6125 ms
|
Iam facing issue while reading the document when runnning code from IIS. It is not reading the document and throwirng an error "No document is opne when trying to save the activedocument.".
m_word.Documents.Open(ref FileName,
ref missing, ref readOnly, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
m_word.ActiveDocument.SaveAs2(ref FileName_rtf, ref FileFormat, ref missing1, ref missing1,
ref missing1, ref missing1, ref missing1, ref missing1,
ref missing1, ref missing1, ref missing1,
ref missing1, ref missing1, ref missing1, ref missing1, ref missing1, ref missing1);
m_word.ActiveDocument is giving error when running from IIS. It is working in visual studio debugging mode.
I also tried the below code:
Document doc_open = m_word.Documents.Open(ref FileName,
ref missing, ref readOnly, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
doc_open.Activate();
doc_open is retruning null and it throws object reference error in the second line. this works when code is in debugging mode. Error occurs when ran from IIS on development server where we have IIS 7 and MS offices too.
|
I couldnt find anything in the API. Is there a way to return the row number or coordinate of a cell based on a string match? For instance: You give the script a string and it scans through the .xls file and when it finds a cell with the matching string, it returns the coordinate or row number.
for i in range(sheet.nrows):
row = sheet.row_values(i)
for j in range(len(row)):
if row[j] == search_value:
return i,j
return None
something like that... just a basic search
|
PostgreSQL substring search
As most of you have probably discovered there is no nice way to do substring search in PostgreSQL however where’s a will there’s a way. The following post is about overcoming this limit, as with all such cases it is somewhat specific to the problem that we are solving and has it’s drawbacks. However i hope this might be of some help for the really desperate folks.This somewhat hackish approach relies on the full text search contrib module called Tsearch2 by Oleg Bartunov and Teodor Sigaev. I tried to use their trigram module first but it didn’t really help me out so here is the solution: Let’s create a really simple substring search on email addresses, for input we have the following table:
Table "public.tmp_email" Column | Type | Modifiers ----------+----------+----------- email | text | trigrams | tsvector |
trigrams is a column added solely for the purpose of being able to help us to search emails by substrings, it contains all the unique sequential 3 letter combinations used in the email field. For example for an email ‘kristo@eesti.ee’ it would consist of
o@e est sti .ee @ee sto ris ees ist ti. kri i.e to@
We will do this with a simple plpython function (can be done in plpgsql also but it looks nicer in python)
CREATE FUNCTION text_to_trigrams(i_txt text) RETURNS text AS $$
trigrams = {}
for i in range(len(i_txt)-2):
trigrams[i_txt[i:i+3]] = 1
return ' '.join(trigrams.keys())
$$ LANGUAGE plpythonu SECURITY DEFINER;
In a production system you would probably be calculating the trigrams in an update/insert trigger on the table doing the same operation provided in the following query:
update tmp_email set trigrams = to_tsvector('simple',text_to_trigrams(email));
The principle itself is really simple, after splitting up the string in email column into these unique 3 letter combinations we will create a full text index on that column (trigram column) which will enable us to search for a predefined set of trigrams inside a string.
create index idx_email_substring on tmp_email using gin (trigrams);
Be warned that the index is quite hefty. In my testcase with live e-mail addresses the index was just a bit bigger than the table itself, remember i warned you about the drawbacks ;) However the search itself has a quite acceptable performance, but before doing the search we will have to create the search condition. This is achived by creating a query that consists of the trigrams that we are looking for, eg. we want to find users with e-mail address that includes the substring ‘%to@skype%’
test=# select replace(text_to_trigrams('to@skype'),' ',' & ');
replace
-----------------------------------
o@s & sky & @sk & ype & to@ & kyp
This query will find all the trigrams that are contained within the string and replace the spaces we needed for tsvector creation with & operations needed for the tsquery. So using this generated string we can do the search in the following way:
test=# explain analyze select * from tmp_email where trigrams @@ to_tsquery('simple','o@s & sky & @sk & ype & to@ & kyp');
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------
Index Scan using idx_email_substring on tmp_email (cost=0.00..15.50 rows=14 width=64) (actual time=0.086..3.349 rows=2 loops=1)
Index Cond: (trigrams @@ '''o'' & ''s'' & ''sky'' & ''sk'' & ''ype'' & ''to'' & ''kyp'''::tsquery)
Total runtime: 3.379 ms
test=# explain analyze select count(*) from tmp_email ;
QUERY PLAN
--------------------------------------------------------------------------------------------------------------------
Aggregate (cost=676.60..676.61 rows=1 width=0) (actual time=45.656..45.657 rows=1 loops=1)
-> Seq Scan on tmp_email (cost=0.00..642.28 rows=13728 width=0) (actual time=0.009..27.038 rows=13728 loops=1)
Total runtiows=13728 loops=1) Total runtime: 45.701 ms(3 rows)test=# select count(*) from tmp_email ; count ------- 13728
test=# select count(*) from tmp_email ;
count
-------
13728
I know that this is not the nicest way to do this but until we have some generic substring search implemented into PostgreSQL this is at least one way to do it for certain cases. If you want to know in more detail how the previously described solution works i suggest you take a loot at the GIN spec. Be aware that this currently only works if the substring is at least 3 characters long.
|
Iâm interested in using libhid to access a custom HID device that we are developing on a PIC microcontroller. I have been able to successfully get the test_libhid code to run. The instructions for reading and writing to devices using this library are provided as comments in the test_libhid code.
I have attempted to follow the documented techniques for reading and writing, but so far, I have not been to successfully read or write to the device. I suspect the reason may be that the report descriptor for the device specifies a 64 byte array for both the input and output data reports.
I have read the details contained in the Device Class Definition for HID section from usb.org, and I think that I understand how descriptors work in general and how they translate to HID paths, but my attempts to read and write data to the device have failed.
I have verified that the device works in Windows, so my problem appears to lie on the Linux side. I donât think that it should matter, but I should note that Iâm currently working in a VMWare virtual machine, loaded with Ubuntu 8.04 server
Can anyone provide some guidance on how to specify he HID path for the following report descriptor (generated from lsusb âvvv):
Report Descriptor: (length is 29)
Item(Global): Usage Page, data= [ 0x00 0xff ] 65280
(null)
Item(Local ): Usage, data= [ 0x01 ] 1
(null)
Item(Main ): Collection, data= [ 0x01 ] 1
Application
Item(Local ): Usage Minimum, data= [ 0x01 ] 1
(null)
Item(Local ): Usage Maximum, data= [ 0x40 ] 64
(null)
Item(Global): Logical Minimum, data= [ 0x00 ] 0
Item(Global): Logical Maximum, data= [ 0xff 0x00 ] 255
Item(Global): Report Size, data= [ 0x08 ] 8
Item(Global): Report Count, data= [ 0x40 ] 64
Item(Main ): Input, data= [ 0x02 ] 2
Data Variable Absolute No_Wrap Linear
Preferred_State No_Null_Position Non_Volatile Bitfield
Item(Local ): Usage Minimum, data= [ 0x01 ] 1
(null)
Item(Local ): Usage Maximum, data= [ 0x40 ] 64
(null)
Item(Main ): Output, data= [ 0x02 ] 2
Data Variable Absolute No_Wrap Linear
Preferred_State No_Null_Position Non_Volatile Bitfield
Item(Main ): End Collection, data=none
Also, when I run the test_libhid program, it dumps the parse tree as 64 identical entries that look like this:
path: 0xff000001.0x00000000; type: 0x80
These are presumably the inputs. This list is followed by another 64 entries that look like this:
path: 0xff000001.0x00000000; type: 0x90
I have posted to the libhid mailing list, but there has not been much activity there recently, so I thought that I would bring my question here. If anyone can provide guidance on how the HID path for this input and output report should be specified, it would be a tremendous help.
Thanks.
|
ã¹ã¯ãªãã: æåã®ã¹ããã
ã¯ããæãScripting Guys ã®ã ãããã¾ã çã¾ãã¦ããªãããã人ã ã¯ããå ´æããå¥ã®å ´æã¸æ©ãã¦è¡ãã¾ãããéåãæ°æ´ããã®ããã§ã¯ãªããããã¸è¡ãå¿ è¦ãããããã§ããã幸éã«ãä»ã®å½¢æ ã®ç§»åææ®µããã£ã人ã ã¯ã馬ãããã ã象ãã¾ãã¯äººã«æ £ãã身è¿ãªãã®ä»ã®åç©ã«ä¹ã£ã¦ããå°ãéãç§»åãããã¨ãã§ãã¾ãã (ç§ãã¡ã次ã«äº¤éæ¸æ»ã«åºããããã¨ãã«ã¯ãä»ã§ããã®ãããªåå§çãªç§»åææ®µãå©ç¨ãã¦ãã人ã ã®ãã¨ãæãåºãã§ããã)ã
ããã¦ãèªåè»ã¨å¼ã°ãããã®ãç»å ´ãã¾ããå¤ãã®äººã ã¯ç¬ãã¾ãããå½¼ãã¯ããããªãã®ã¯ä¸æçãªæµè¡ã ããã¨ããããããªãã®å¿ è¦ãªãããã¨ãããå±éºããããã¨ã¾ã§è¨ã£ã¦ãã¾ããããããã¤ã¯ãããããã²è©¦ãã¦ã¿ããããã¨è¨ãå è¦ã®æã®ãã人ã¯ãããããã§ããããã®å è¦ã®æã®ãã人ã ã«ã¯ãèªåè»ã楽ãããã®ã ã¨ãããã¨ã ãã§ãªããããå ´æããå¥ã®å ´æã¸ç§»åããæéã使éãããããã¯ä½æ¥éãç¯ç´ã§ããæ¥ããã¤ãæ¥ããã¨ãããã£ã¦ãã¾ããã
仿¥ã®äººã ã¯ãã¯ããæã«è»ã«å¯¾é¢ãã人ã ã¨åãåå¿ãã¹ã¯ãªããã«ã¤ãã¦ç¤ºãã¾ããããã¹ã¯ãªãããªãã¦å¿ è¦ãªãããã¨ãããã¹ã¯ãªãããªãã¦ãä»ã®äººã¨åããã¨ãããããªãããã¢ã®ããã®ãã®ã«ãããªãããã¨ãããã¹ã¯ãªãããªãã¦å±éºã ããã¨è¨ã人ã¾ã§ãã¾ãããããå®éã«ã¯ãã¹ã¯ãªããã試ãã®ã«å è¦ã®æã¯ããããåéºå¿ãå¿ è¦ãªããã§ãããã¾ãããæéãç¯ç´ãããã¨æã人ã§ããã°ããã®ã§ã (ããã¢ã¨ããã®ã¯ãã¹ã¯ãªãããæ¥½ããã¨æã人ã ãã§ã)ãã¹ã¯ãªããã¯ä½æ¥ã®é度ãä¸ããã ãã§ãªããä»äºãç°¡åã«ããã¾ããã¾ããåºæ¬çãªäº¤éè¦åãå¦ç¿ããã°ãé転ã¯ã¾ã£ããé£ããããã¾ãã (ããã«äº¤éæ¸æ»ããããã§ã)ã
æé 1
ããã¯ãMicrosoft Windows ã·ã¹ãã ã管çããã¹ã¯ãªããã使ãå§ããã«ããã£ã¦æåã«ç¥ã£ã¦ããå¿ è¦ã®ãããã¨ã§ããå³å¯ã«ã¯ã2 çªç®ã«ç¥ã£ã¦ããå¿ è¦ã®ãããã¨ã§ãããã¾ãæåã«ç¥ã£ã¦ããå¿ è¦ãããã®ã¯ã¹ã¯ãªãã ã»ã³ã¿ã¼ã®è¦ã¤ãæ¹ã§ãããçãããããããåç¥ã§ããã®ã¯æãããªã®ã§ããã®æé ã¯çç¥ãããã¨ã«ãã¾ããã
ã¹ã¯ãªãã ã»ã³ã¿ã¼ã«ã¯ (ã¤ã³ã¿ã¼ãããä¸ã®ä»ã®å ´æã«ãããããããã¾ããããããã«ã¤ãã¦ã¯ä¿è¨¼ã§ãã¾ãã)ã使æ¸ã¿ã®ããã«ä½¿ããã¹ã¯ãªãããæ°å¤ãããã¾ããã¹ã¯ãªããã¨ã¯ã次ã®ãããªãã®ã§ãã
ããã§ãããã® 1 è¡ãã¹ã¯ãªããã§ããããã¯é常ã«åç´ãªã¹ã¯ãªããã§ãããããã¦ãã®ã¹ã¯ãªããã¯ããããé·ããªãã¾ããããããã¹ã¯ãªããã§ããããã§ããã® 1 è¡ãã©ã®ããã«å¦çããã°ããã®ãã¨ããçåãããã¦ãã¾ããããã¯é常ã«åç´ã§ãã
ããã§ã³ãã³ã ã¦ã£ã³ãã¦ãéãããã¡ã¤ã«ãä¿åãããã©ã«ãã«ç§»åããæ¬¡ã®ããã«å ¥åãã¾ãã
åè¿°ã®ã¹ã¯ãªããã§ãã®æä½ãè¡ã£ãå ´åãåºåã¯æ¬¡ã®ããã«ãªãã¾ãã
ãããã®æé ãå®è¡ããã¨ãã¹ã¯ãªãã ã»ã³ã¿ã¼ã«ããã©ã®ã¹ã¯ãªãããåãããã«å®è¡ã§ãã¾ããããã§ã¯ã¹ã¯ãªããããæ¥½ãã¿ãã ããã
ã
ã¹ã¯ãªããã¨ã¯ãã£ããä½ã
ã¹ã¯ãªããã«ã¤ãã¦ãã£ã¨è©³ããç¥ãããã®ã§ãããããã§ã¯ãå°ãæ»ã£ã¦ (æé 0 ã¾ã§æ»ãã¾ã)ãã¹ã¯ãªããã¨ã¯ä½ããã¹ã¯ãªããããªã使ç¨ããã®ãã«ã¤ãã¦èª¬æãã¾ãããã
ã¹ã¯ãªããã¯ãèªåã®ã³ã³ãã¥ã¼ã¿ (ããã³ãã®ä»ã®ã³ã³ãã¥ã¼ã¿) ã¨ã®æ å ±ã®ããåããèªååããæ¹æ³ã«ããã¾ãããæåã«ç¤ºããã¹ã¯ãªããã§ã¯ãã³ã³ãã¥ã¼ã¿ã«æãä¸ããã³ã³ãã¥ã¼ã¿ããåãæãåå¾ãã¾ãããç¹ã«ä¾¿å©ãªæ©è½ã¨ã¯æããªãããããã¾ããããããã¯æåã®ä¸æ©ã«ããã¾ããã䏿©ã ãã§ã¯ãã¢ããåºããã¨ã¯ããããé¨å±ã®ä¸ãæ©ããã¨ããã§ãã¾ããã(Scripting Guys ã® 1 人ã¯ãã¤ã¦ä¸æ©ã§é¨å±ã®ä¸ã®ã©ãã«ã§ãè¡ããã¢ãã¼ãã«ä½ãã§ãããã¨ãããã¾ããããããå¯ããããã¨ã巨大ãªã¯ã¢ãåºããã¨ãªã©ã詳ããã¯èª¬æããããªããã¾ãã¾ãªçç±ããããã®ã¢ãã¼ãã¯ããã«ç¤ºããæåã®ã¹ã¯ãªããããã¯ããã«å½¹ã«ç«ããªããã®ã§ãã)ãã¹ã¯ãªãããæ¬å½ã«å½¹ç«ã¤ç¶æ³ã¯å¤æ°ããã¾ãããã®ä¾ã次ã«ããã¤ã示ãã¾ãã
ã·ã¹ãã 管çè ã¨ãã¦è¡ãå¿ è¦ã®ãã使¥ã«ã¤ãã¦èããå ´åã«ãã¹ã¯ãªããã使ããã¿ã¹ã¯ãæ¢ã«èãããã¨ãããããããã¾ããã
ã
ããã§ããã¹ã¯ãªããã®å 容ã¯ã³ã¼ãã®ããã«è¦ãã
ã¹ã¯ãªãã ã»ã³ã¿ã¼ã¯æ¢ã«ã覧ã«ãªããæ¯æ¥çºè¡ãããã Hey, Scripting Guy!ãã®è¨äºãããã¤ããèªã¿ã«ãªããæ¬¡ã®ãããªã¹ã¯ãªãããç®ã«ããããã¨ã¨æãã¾ãã
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'Dfrgntfs.exe'")
If colProcesses.Count = 0 Then
Wscript.Echo " Dfrgntfs.exe is not running."
Else
Wscript.Echo " Dfrgntfs.exe is running."
End If
ããã®ã¹ã¯ãªããã®å 容ã¯ããªãè¤éã«è¦ãããã¨æãããããã¾ãããä¿¡ããããªãããããã¾ããããå®ã¯ãã¹ã¯ãªããã¯ããã®ã³ã³ãã¥ã¼ã¿ ããã°ã©ãã®ããã ãã®ãã®ã§ã¯ããã¾ãããããã°ã©ãåãã«ã¯ãã¯ããã«å¼·åã§è¤éãªãã¼ã«ãããã¾ãã誤解ããªãã§ããã ãããã®ã§ãããã¹ã¯ãªããã¯å¼·åã§è¤éã«ãããã¨ãã§ãã¾ãããé常ã«å½¹ç«ã¤ããªãåç´ãªã¹ã¯ãªããã使ã§ãã¾ããã§ãããããã®å 容ãæããã "ã³ã¼ã" ã¨ã¯èããªãã§ãã ãããããã°ã©ãã³ã°çµé¨ãçç¡ã§ããããªãç°¡åã«è¡ãããã¨ã夿°ããã¾ãã
ä»ã®ç¨®é¡ã®ããã°ã©ãã³ã°ãããã¹ã¯ãªããã®æ¹ãåªãã¦ããç¹ã® 1 ã¤ã¯ãå¿ è¦ãªãã®ããªãã¬ã¼ãã£ã³ã° ã·ã¹ãã ã«çµã¿è¾¼ã¾ãã¦ãããã¨ã§ããVBScriptãWSHãWMI ãªã©ã®ããã¤ãã®é åèªã«ã¤ãã¦ã¯å¾ã»ã©ç°¡åã«èª¬æãã¾ãããããã§ã¯ãããããã¹ã¦ã¹ã¯ãªããã®ä¸é¨ã§ããããã¹ã¦ Windows ã«çµã¿è¾¼ã¾ãã¦ããã¨ãããã¨ãè¿°ã¹ã¦ããã¾ããã¹ã¯ãªããã使ããããã«ã¯ãæã®è¾¼ãã é«ä¾¡ãªã½ããã¦ã§ã¢ãä¸è¦ã§ããæ¢ã«èª¬æããããã«ãå¿ è¦ãªã®ã¯ã¡ã¢å¸³ã ãã§ãããããã Windows ã«çµã¿è¾¼ã¾ãã¦ãã¾ãã
ã¾ããã¹ã¯ãªããã¯ãªãã¬ã¼ãã£ã³ã° ã·ã¹ãã ã®ç®¡çã«å½¹ç«ã¤ããã«è¨è¨ããã¦ãã¾ããéå¸¸ã«æè½ã®ããããã°ã©ãã§ãããã¹ã¯ãªããã使ç¨ã㦠Word ã Excel ãªã©ã®æçããã½ããã¦ã§ã¢ ã¢ããªã±ã¼ã·ã§ã³ã使ãããã¨ãããã¨ã¯ããã¾ãããã¹ã¯ãªããã使ç¨ããã¨ãã·ã¹ãã 管çã¿ã¹ã¯ãèªååã§ããã®ã§ãã
ããã§èª¬æããã¹ã¯ãªãã (ã¾ããã¹ã¯ãªãã ã»ã³ã¿ã¼ã§æ±ãã»ã¨ãã©ã®ã¹ã¯ãªãã) ã®ç¨®é¡ã¯ãã·ã¹ãã 管çã¹ã¯ãªããã§ããä»ã®ç¨®é¡ã®ã¹ã¯ãªãã (Web ã¹ã¯ãªãããªã©) ãããã¾ãããããã«ã¤ãã¦ã¯ä»ã®å ´æã§å¦ç¿ãã¦ãã ããã
VBScript 以å¤ã«ãã¹ã¯ãªããè¨èªã¯ãããã¡ã¢å¸³ä»¥å¤ã«ãã¹ã¯ãªããã®ä½æã«ä½¿ç¨ã§ãããã¼ã«ã¯ããã¾ããããããããããã¹ã¦ã«ã¤ãã¦ã¯ãã¹ã¯ãªãããå°ãçµé¨ããã¨èªåã§èª¿ã¹ããã¨ãã§ããããã«ãªãã¾ããã¹ã¯ãªãã ã»ã³ã¿ã¼ã®ã¹ã¯ãªããã¨ä¾ã®ã»ã¨ãã©ã¯ãVBScript ã使ç¨ãã¦ãã¾ãã
ã
ã¹ã¯ãªããã®å®è¡
å 容ã«é¢ããèæ¯æ å ±ãååã«çè§£ããã¨ããã§ãããã¤ãã®ã¹ã¯ãªããã®å®è¡ã«æ»ãã¾ããCscript ã使ç¨ãã¦ã³ãã³ã ã©ã¤ã³ããã¹ã¯ãªãããå®è¡ããæ¹æ³ã¯æ¢ã«ç¤ºãã¾ãã (ãã¹ã¯ãªããã®å®è¡ãã¨ããã¿ã¤ãã«ã«æ¹ããã¦ç´æ¥ãã®ã»ã¯ã·ã§ã³ã«æ¥ãæ¹ã¯ãå¿ãè½ã¡çãã¦æ¯ãæ´ããä¸çªä¸ã«æ»ã£ã¦æé 1 ãèªãã§ãã ãã)ãã¹ã¯ãªããã¯ã[ã㤠ã³ã³ãã¥ã¼ã¿] ã¾ã㯠Windows ã¨ã¯ã¹ããã¼ã©ã§ããã«ã¯ãªãã¯ããã ãã§ãå®è¡ã§ãã¾ããéãã¯ãã¹ã¯ãªããããã®åºåãã³ãã³ã ã¦ã£ã³ãã¦ã«è¡¨ç¤ºããã代ããã«ãã¡ãã»ã¼ã¸ ããã¯ã¹ã«ãããã¢ãã表示ããããã¨ã§ããæ¢ã«ä½æããã¹ã¯ãªããã§ããã試ãã¦ã¿ã¾ããããtest.vbs ãã¡ã¤ã«ãåç´ã«ããã«ã¯ãªãã¯ãã¦ãã ãããããã¨ã次ã®ãããªã¡ãã»ã¼ã¸ ããã¯ã¹ã表示ããã¾ãã
ç°¡åã§ãããããããæåã«è¡ããªãã£ãã®ã¯ãªãã ã¨æãã¾ãããã³ãã³ã ã¦ã£ã³ãã¦ã¯ä½ã®ããã«å¿ è¦ãªã®ã§ããããããã®è³ªåã«çããåã«ãæ¬¡ã®æä½ã試ãã¾ããæ¬¡ã®ã¹ã¯ãªãããã¡ã¢å¸³ã«è²¼ãä»ããæ¡å¼µå .vbs ãä»ãã¦ä¿åãããã®ãã¡ã¤ã«ãããã«ã¯ãªãã¯ãã¦ãã ããã
For i = 1 to 5
Wscript.echo i
Next
ã©ããªãã¾ãããã5 ã¤ã®ã¡ãã»ã¼ã¸ ããã¯ã¹ããããã§ [OK] ãã¯ãªãã¯ããå¿ è¦ãããã¾ããããããã§ãã¹ã¯ãªããããã³ã³ãã¥ã¼ã¿ä¸ã§å®è¡ããã¦ãããã¹ã¦ã®ããã»ã¹ãããã¡ã¤ã³å ã®ãã¹ã¦ã®ã³ã³ãã¥ã¼ã¿åãè¿ãå ´åãæ³åãã¦ãã ãããã¯ãªãã¯ãä½åº¦ãå¿ è¦ã«ãªãã¾ãããCscript ã使ç¨ãã¦ã¹ã¯ãªãããå®è¡ããã¨ããã®åºåãã³ãã³ã ã¦ã£ã³ãã¦ã«ãã¹ã¦ç´æ¥éä¿¡ãããããããããã®ã¡ãã»ã¼ã¸ ããã¯ã¹ããã¹ã¦æä½ããå¿ è¦ã¯ããã¾ããã
ã¹ã¯ãªããã®å®è¡ã®è©³ç´°ã«ã¤ãã¦ã¯ããWindows 2000 Scripting Guideãã®ã Running WSH Scriptsã(è±èª) ãåç §ãã¦ãã ããã
ã
é åèªã«ã¤ãã¦
é åèªã«ã¤ãã¦ã¯å¾ã§è¨åããã¨åã«è¿°ã¹ã¾ãããScripting Guys ã¯æ±ºãã¦åãã¤ããªãã®ã§ (ããã®é«ªåä¼¼åãããã¨è¨ããã¨ã¯ãã¾ã«ããã¾ãã)ãã¹ã¯ãªããé¢é£ã®ãã¯ããã¸ã®ããç°¡åãªå®ç¾©ã¨ãåãã¯ããã¸ã«ã¤ãã¦ãã詳ãã説æãã¦ãããWindows 2000 Scripting Guideãã®ã»ã¯ã·ã§ã³ã以ä¸ã«ç¤ºãã¾ãã
ã¹ã¯ãªãã ã»ã³ã¿ã¼ã®ããã²ã¼ã
ã¹ã¯ãªãã ã»ã³ã¿ã¼ã«ã¯ãã¹ã¯ãªããã®ä½æãéå§ããã¨ããããã³ããã«é«åº¦ãªã¹ã¯ãªãããå¿ è¦ãªã¨ãã«å½¹ç«ã¤å¤æ°ã®ãªã½ã¼ã¹ãç¨æããã¦ãã¾ãã
ã
ç¬ãç«ã¡ã®ã¨ãã§ã
èªè ãç¬ãç«ã¡ãããåã«ã1 ã¤ã®æç¨ãªãã³ãããä¼ããã¾ããã¹ã¯ãªããã§ã¯å¤§æåã¨å°æåãåºå¥ããã¾ããããã¤ãææãã¦ããããã« 1 ã¤ã 2 ã¤ã®ä¾å¤ã¯ããã¾ãããã¹ã¯ãªããã®ã»ã¨ãã©ã®é¨åã¯åã«èªã¿ããããé«ããããã«å¤§æåã¨å°æåãæ··å¨ããã¦ãã¾ããä¹±æ°ãçæããæ¬¡ã®ã¹ã¯ãªããã«ã¤ãã¦èãã¦ã¿ã¾ãããã
intHighNumber = 100
intLowNumber = 1
For i = 1 to 5
Randomize
intNumber = Int((intHighNumber - intLowNumber + 1) * Rnd + intLowNumber)
Wscript.Echo intNumber
Next
ãã®ã¹ã¯ãªããã¯ã次ã®ã¹ã¯ãªããã¨ã¾ã£ããåãåä½ããã¾ãã
inthighnumber = 100
intlownumber = 1
for i = 1 to 5
randomize
intnumber = int((inthighnumber - intlownumber + 1) * rnd + intlownumber)
wscript.echo intnumber
Next
ããã§ãã¹ã¯ãªãã ã»ã³ã¿ã¼ã®ä»ã®é¨åã«é²ã¿ã使¥ãè¡ãæºåãã§ãã¾ãããã©ããã¦ãè¡ãè©°ã¾ã£ãå ´åã¯ã scripter@microsoft.com (è±èªã®ã¿) ã«é»åã¡ã¼ã«ã§æ¯æ´ãæ±ãããã¨ãã§ãã¾ããããã§ã¯ã楽ãã¿ãã ããã
ã
åå¿è ã®ããã«
ã¹ã¯ãªããã«é¢ãããã®ç´¹ä»ããæ¥½ãã¿ããã ãããå½¹ã«ç«ã¦ããªãããããã§ããã¹ã¯ãªãã使éå§ã®è©³ç´°ã«ã¤ãã¦ã¯ãã
ã
ç®æ¬¡
ã¯ããã«
ãã¼ã«ã®ãã¦ã³ãã¼ã
ã¹ã¯ãªãããæ¢ã
|
I have two large figures that I'd like to put on an extra page, meaning there should be no text on that page, only the figures.
Bla bla.
\begin{figure}[t] ... \end{figure}
\begin{figure}[b] ... \end{figure}
Lorem ipsum.
I'd like that to come out as:
Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla
bla bla bla bla bla bla bla bla bla bla bla.
Lorem ipsum bla bla bla bla bla bla bla bla bla bla bla bla
bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla
-- pagebreak
Figure 1 (at the top)
Figure 2 (at the bottom)
-- pagebreak
bla bla bla bla bla bla bla bla.
I haven't found anything on Google - inserting pagebreaks manually may work but won't make the text continue (the "Lorem Ipsum" part would be after the figures, even when there is some space left on the page before).
Any idea how this can be done?
|
Custom Fields in Django
I was helping someone today in the Django IRC channel and the question came across about storing a denormalized data set in a single field. Typically I do such things by either serializing the data, or by separating the values with a token (comma for example).
Django has a built-in field type for CommaSeparatedIntegerField, but most of the time I'm storing strings, as I already have the integers available elsewhere. As I began to answer the person's question by giving him an example of usage of serialization + custom properties, until I realized that it would be much easier to just write this as a Field subclass.
So I quickly did, and replaced a few lines of repetitive code with two new field classes in our source:
Update: There were some issues with my understanding of how the metaclass was working. I've corrected the code and it should function properly now.
SerializedDataField
This field is typically used to store raw data, such as a dictionary, or a list of items, or could even be used for more complex objects.
from django.db import models try: import cPickle as pickle except: import pickle import base64 class SerializedDataField(models.TextField): """Because Django for some reason feels its needed to repeatedly call to_python even after it's been converted this does not support strings.""" __metaclass__ = models.SubfieldBase def to_python(self, value): if value is None: return if not isinstance(value, basestring): return value value = pickle.loads(base64.b64decode(value)) return value def get_db_prep_save(self, value): if value is None: return return base64.b64encode(pickle.dumps(value))
SeparatedValuesField
An alternative to the CommaSeparatedIntegerField, it allows you to store any separated values. You can also optionally specify atoken parameter.<metadata lang=Python prob=1.00 />
from django.db import models class SeparatedValuesField(models.TextField): __metaclass__ = models.SubfieldBase def __init__(self, *args, **kwargs): self.token = kwargs.pop('token', ',') super(SeparatedValuesField, self).__init__(*args, **kwargs) def to_python(self, value): if not value: return if isinstance(value, list): return value return value.split(self.token) def get_db_prep_value(self, value): if not value: return assert(isinstance(value, list) or isinstance(value, tuple)) return self.token.join([unicode(s) for s in value]) def value_to_string(self, obj): value = self._get_val_from_obj(obj) return self.get_db_prep_value(value)
|
#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
|
mars
Connaissances de base pour Kubuntu
Bienvenue à tous les lecteurs.
Ce sujet a pour but d'apporter les connaissances de base à toute personne débutant sous Kubuntu.
Il est très bon pour tout débutant de lire ce post, mais il est aussi très conseillé aux personnes plus expérimenté, car il contiendra des conseils de base mais aussi des astuces d'utilisation pas inutiles.
Ce post n'est EN AUCUN CAS réservé à des questions. Les commentaires posté ici doivent être limités à des propositions d'ajouts.
Nous essayerons, dans la limite de nos capacités, de faire en sorte que ce post soit à jour pour chaque version stable de Kubuntu, mais peut-être aussi pour la version LTS de Kubuntu et la version unstable du moment (requiert plus de travail). Bien entendu, toute aide de la part des membres de ce forum pour maintenir ce post est bienvenue.
SOMMAIRE :
- Les dépôts
- Les paquets souvent utilisés (multimédia, autres)
- conseil de bases sur l'utilisation de Kubuntu
- Les dépôts
Un fichier sources.list de base :
Linux utilise pour installer ses logiciels des dépôts. Pour avoir un maximum de logiciels disponibles, ainsi qu'un maximum de fonctionnalités il vous faut un maximum de dépôts. Mais ATTENTION, les dépôts sont une partie sensible de Linux. Si un paquet (conteneur de logiciel) a été mal fait, il peut entièrement casser votre système. Pour cela, nous vous proposons ici un fichier sources.list très complet ne contenant que des dépôts officiels ou maintenus par des gens compétents.
Pour l'utiliser, il vous faudra éditer le fichier sources.list avec cette commande à entrer dans une Konsole
kdesu kwrite /etc/apt/sources.list
et d'y coller ceci en remplacement du contenu de ce fichier :
#
# dépôt du CD utilisé pour l'installation et à utiliser en cas de problème et de pertes du réseau
# deb cdrom:[Kubuntu 6.10 _Edgy Eft_ - Bêta i386 (20060928)]/ edgy main restricted
# dépôt officiel basique de Kubuntu
deb http://archive.ubuntu.com/ubuntu feisty main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu feisty-updates main restricted universe multiverse
# dépôt source officiel basique de Kubuntu ; ces dépôts sont peu utiles au quotidien et sont donc commentés
# deb-src http://fr.archive.ubuntu.com/ubuntu feisty main restricted universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu feisty-updates main restricted universe multiverse
# mise à jour de sécurité de Kubuntu
deb http://security.ubuntu.com/ubuntu feisty-security main restricted universe multiverse
# deb-src http://security.ubuntu.com/ubuntu feisty-security main restricted universe multivers
# dépot backports de Kubuntu ; ces dépôts contiennent des mises à jour de logiciels ne concernant pas la sécurité
deb http://archive.ubuntu.com/ubuntu feisty-backports main universe multiverse restricted
# COMMERCIAL ce dépôt contient des logiciels commerciaux
deb http://archive.canonical.com feisty-commercial main
#LES DÉPÔTS SUIVANT NE SONT PAS SUPPORTES PAR CANNONICAL, LA SOCIÉTÉ DÉVELOPPANT KUBUNTU
#LES BUGS NE SONT DONC PAS IMPUTABLE A CANNONICAL
#VOUS LES UTILISEZ DONC A VOS DÉPEND
#KDE latest : ce dépôt fourni par les développeurs de KDE contient des mises à jour spécifiques à KDE
#deb http://kubuntu.org/packages/kde-latest feisty main
#Koffice latest : ce dépôt fourni par les développeurs de KDE contient des mises a jour de Koffice
#deb http://kubuntu.org/packages/koffice-latest feisty main
#amarok latest : ce dépôt fourni par les développeurs de KDE contient des mises à jour d'Amarok
#deb http://kubuntu.org/packages/amarok-latest feisty main
#medibuntu : ces dépôts contiennent des logiciels à la légalité douteuse dans certains pays, faute de brevets logiciels
deb http://medibuntu.sos-sts.com/repo/ feisty free non-free
il se peut que vous ayez des erreurs lors du lancement de cette commande. Dans ce cas allez voir ce post : http://forum.kubuntu-fr.org/viewtopic.php?id=53202 qui explique comment régler le problème.
Il vous faudra taper cette commande aprés avoir modifier ce fichier. En effet les paquets sont signés pour éviter le piratage mais pour cela il vous faut la clé pour vérifier les paquets :
wget -q http://medibuntu.sos-sts.com/repo/medibuntu-key.gpg -O- | sudo apt-key add - && wget http://people.ubuntu.com/~jriddell/kubuntu-packages-jriddell-key.gpg && sudo apt-key add kubuntu-packages-jriddell-key.gpg && rm kubuntu-packages-jriddell-key.gpg
Les lignes commencant par un # ne sont pas lu par le programme et donc ignoré. Certaines sont des commentaires du fichier, d'autres des dépots utile au développeur (les dépots deb-src) et d'autres (comme les dépots contenant -latest) des dépots de mise a jour non encore activé car n'en contenant pas. Si vous voulez vous tenir au courant de mises a jour vous pouvez le faire en regardant de temps en temps ce site : http://www.kubuntu.org/ ou les mises a jour sont annoncés.
Commandes courantes à utiliser pour gérer les logiciels :
Nous vous donnons ici les commandes de base à utiliser pour gérer les logiciels, en installer, en supprimer, les mettre à jour. Ces commandes seront données deux fois, une à utiliser en console, l'autre, de manière graphique dans le logiciel adept_manager que l'on trouve dans le menu KDE, sous-menu Système, sous le nom de Gestionnaire de paquets Adept. Ces commandes sont équivalentes ; les une se font en ligne de commandes et les autres en graphique, à la souris.
Avant toute chose :
mettre à jour la liste des logiciels fournis par les dépôts avec la commande :
en konsole :
sudo apt-get update
dans adept :
le bouton recharger en haut à gauche du logiciel
Installer un logiciel :
en konsole :
sudo apt-get install le_nom_du_logiciel
dans adept :
rechercher dans la liste des logiciels celui que vous voulez installer. Vous pouvez filtrer la liste grâce à la zone Recherche. Une fois le logiciel trouvé, vous pouvez l'installer en faisant un clic droit sur le nom du logiciel et en choisissant "request install". Lorsque vous avez choisi tous les logiciels à installer, cliquez sur "Appliquer les changements"
Supprimer un logiciel :
en konsole :
sudo apt-get remove le_nom_du_logiciel
dans adept :
rechercher dans la liste des logiciels celui que vous voulez installer comme pour en installer un. Une fois le logiciel trouvé, vous pouvez le supprimer en faisant un clic droit sur le nom du logiciel et en choisissant "request remove". Lorsque vous avez choisi tous les logiciels à supprimer, cliquez sur "Appliquer les changements"
Mettre à jour vos logiciels :
en konsole :
sudo apt-get dist-upgrade
dans adept :
cliquez sur le bouton "Tout mettre a jour" suivi de "Appliquer"
ou alors,
attendez de voir dans votre zone de notification KDE (à gauche de l'heure) de voir une icône "Notification de mise à jour" qui vous permettra d'effectuer les mises à jour
En cas de crash d'adept il se peut que vous n'arriviez plus a utiliser ni adept ni apt-get et qu'il vous gronde avec un message complexe disant qu'une autre instance de apt-get tourne. Dans ce cas essayez ceci (un reboot sera peut étre nécessaire (seulement pour les débutants aprés il faudra apprendre a chercher et tuer un processus)) :
sudo fuser -vki /var/lib/dpkg/lock && sudo dpkg --configure -a
ATTENTION : les commandes donnée ici sont les commandes recommandés par debian et ubuntu. Des alternatives a ces commandes existent tels que aptitude qui peuvent apporter des améliorations a celles ci. Sachez que seul les commandes donné ci dessus sont supporté par debian et ubuntu, les autres peuvent et ont déja causé des problèmes parfois grave et nécessitant une réinstallation complète du système. Nous vous déconseillons d'utiliser ces commandes tant que vous n'avez pas une maîtrise complète de votre système. Cette maîtrise viendra avec le temps.
- Les paquets souvent utilisés (multimédia, autres)
Voici une liste de logiciels que vous trouverez dans les dépôts et qui vous permettront d'améliorer votre expérience sur Linux.
- w32codecs Permet la lecture de formats Microsoft sous linux (wma, wmv, sans DRM)
- libdvdcss2 Permet la lecture de DVD crypté sous linux
- libdvdread3 Permet la lecture de DVD avec les menu sous linux
- libxine-extracodecs Permet d'avoir accès a la lecture d'un maximum de format de média sous Kubuntu
- libk3b2-mp3 Permet de graver des Cd audio depuis K3B
- libtunepimp5-mp3 Permet de compléter les tags de fichier mp3 dans amarok
- sun-java6-plugin Plugin java pour la navigation web
- flashplugin-nonfree Plugin flash pour la navigation web
- printconf Permet la configuration facile d'imprimante (il n'est pas installé par défaut dans feisty)
- Flac et Sox Permettent une gestion de l'encodage plus poussé dans entre autre k3b
conseil de bases sur l'utilisation de Kubuntu
Tout d'abord un premier conseil : oubliez vos réflexes de windowsien. Vous ne savez pas (encore) vous servir de votre systéme, et il peut tout faire pour vous a condition que vous lui parliez gentiment. Sachez que la stabilitéde linux n'est pas une légende, certaines personnes n'éteigne jamais leur pc et font des "combats" d'uptime (l'uptime mesure le temps depuis lequel le pc n'a pas été redémarré). Des valeurs courante d'uptime atteigne plusieurs années, mais pour ca il faut parler gentiment a son systéme.
Un des premiers réflexes a perdre est de chercher a tout prix a installer un antivirus, un firewall et des logiciels créant de beaux effets de bureau.
Dites vous que vous avez le temps et que ces logiciels sont soit inutile (firewall et antivirus) soit nécessite de connaitre son systéme (firewall et effets 3D). Donc prenez votre temps, attendez quelques mois avant d'essayer beryl.
Quelques astuces de kde :
- rajouter la corbeille sur le bureau :
éditer le fichier de la corbeille (sous linux tout est fichier c'est un concept que je développerais peut étre plus tard) :
kate ~/Desktop/trash.desktop
ce fichier doit aprés modification ressembler a ca :
[Desktop Entry]
Comment=Contains removed files
Comment[fr]=Contient les fichiers supprimés
EmptyIcon=trashcan_empty
Encoding=UTF-8
Hidden=false
Icon=trashcan_full
Name=Trash
Name[fr]=Corbeille
Type=Link
URL=trash:/
- sauvegarde de session :
kde comme vous l'avez peut étre remarqué sauvegarde votre session. le probléme est que lorsqu'une application a planté et n'est pas visible kde va la relancer inlassablement a chaque démarrage. pour cela il y a deux parades.
La premiére consiste a arréter cette sauvegarde de session puis de relancer les programmes a chaque démarrage en les placant dans ~/.kde/Autostart
La deuxiéme consiste a sauvegardé une session type qui sera celle lancé a chaque démarrage.
Je ne développe pas plus ici ces deux méthodes car ca nécessiterait bien plus de place et on déja été bien documenté ailleurs : http://forum.kubuntu-fr.org/viewtopic.php?id=107453 (lien temporaire en attendant que je fasse un truc plus clair)
- connexion automatique au réseau :
Un outil trés pratique est maintenant dans kubuntu : Knetworkmanager. Celui ci a pour but de rendre la connexion au réseau transparente. Vous découvrez un réseau knetworkmanager enregistre sa configuration et vous y connectera automatiquement la prochaine fois. Il sait aussi choisir entre plusieurs réseau disponible celui qui offrira la meilleur qualité.
Pour l'utilisé au mieux il vous faut laisser kwalletmanager lancé. Celui ci sert a stocker tout vos mot de passe. Seulement pas soucis de sécurité il demande lui aussi un mot de passe avant de vous laisser accéder a ceux qu'il a enregistré. On est pas la NASA donc par soucis de praticité je vous conseille de mettre un mot de passe vierge.
POST EN COURS DE RÉDACTION
Hors ligne
mars
Re : Connaissances de base pour Kubuntu
réservé
Hors ligne
mars
Re : Connaissances de base pour Kubuntu
réservé
Hors ligne
CorSu
Re : Connaissances de base pour Kubuntu
Bonjour, quand je tape la commande:
kdesu kwrite /etc/apt/sources.list
j'obtiens ca:
X Error: BadDevice, invalid or uninitialized input device 168
Major opcode: 145
Minor opcode: 3
Resource id: 0x0
Failed to open device
X Error: BadDevice, invalid or uninitialized input device 168
Major opcode: 145
Minor opcode: 3
Resource id: 0x0
Failed to open device
Quelqu'un sait d'où ca vient ?
Merci
Woshee
Re : Connaissances de base pour Kubuntu
C'est pas une erreur, tu peux l'ignorer.
Pour mettre a jour les logiciels, utiliser aptitude plutot qu'apt-get, et upgrade, pas dist-upgrade.
Devenez parrain Linux ou trouvez quelqu'un pour vous aider près de chez vous:
http://parrains.linux.free.fr/
Hors ligne
CorSu
Re : Connaissances de base pour Kubuntu
Mais ca ne me permet pas d'ouvrir la liste pour y copier le code...
il n'y a pas un autre moyen d'acceder à cette liste ?
SamheG
Re : Connaissances de base pour Kubuntu
LMAA
Bye ... ça veut dire CIAO en anglais !
Kansas Of Elsass
Hors ligne
CorSu
Re : Connaissances de base pour Kubuntu
C'est bon, merci beaucoup
mars
Re : Connaissances de base pour Kubuntu
C'est pas une erreur, tu peux l'ignorer.
Pour mettre a jour les logiciels, utiliser aptitude plutot qu'apt-get, et upgrade, pas dist-upgrade.
Bon jusqu'a maintenant je disais trop rien mais la j'interviens!
NE SURTOUT PAS UTILISER APTITUDE
il n'apporte rien de plus et apporte des emmerdes! Debian est une distribution pensée, avec des outils pensée et aptitude n'en fait pas partie et comme tout outil non pensé pour debian il est trés bien mais pas pour des débutants.
pour stopper net les controverses sachez que un grand nombre de personnes qui ont fait l'upgrade edgy -> feisty avec aptitude ont risqué de tout casser (quand ils ne l'ont pas fait) car aptitude ne voulait pas supprimer mdadm alors que apt le supprimé.
deuxiéme raison valable : pourquoi tout les "pro" debian utilisent apt-get et pas aptitude.
edit : rajout dans le tuto d'un avertissement sur aptitude et de la modification a faire pour supprimer les messages d'erreur X en console.
Hors ligne
Woshee
Re : Connaissances de base pour Kubuntu
Dis upgrade c'est pour aller d'une version d'ubuntu a l'autre (d'ou le dist comme distribution) et pas pour mettre a jour des paquets.
Aptitude gère merveilleusement mieux les dépendances que apt-get, et tu dois être la seule personne ici qui en dise du mal.
De plus les personnes qui ont fait la migration edgy->feisty en console n'ont pas utilisé les outils graphiques bien plus puissants mis a leur disposition.
Devenez parrain Linux ou trouvez quelqu'un pour vous aider près de chez vous:
http://parrains.linux.free.fr/
Hors ligne
mars
Re : Connaissances de base pour Kubuntu
Dis upgrade c'est pour aller d'une version d'ubuntu a l'autre (d'ou le dist comme distribution) et pas pour mettre a jour des paquets.
Aptitude gère merveilleusement mieux les dépendances que apt-get, et tu dois être la seule personne ici qui en dise du mal.
De plus les personnes qui ont fait la migration edgy->feisty en console n'ont pas utilisé les outils graphiques bien plus puissants mis a leur disposition.
1/ faire un apt-get upgrade n'a aucune raison sous ubuntu ca en a sous debian sid mais aucune sous ubuntu! trouve moi une seule raison valable (avec justification) d'utiliser upgrade a la place de dist-upgrade et je remplace dans le tuto.
2/ t'as raison pour aptitude j'ai tort et tout les dev ubuntu et kubuntu aussi. Comme on avait tort sur les dépots czessi et kubuntu-de. et ceux qui ont cassé leur distrib aussi.
3/ pour ma part j'ai fait ca en console avec apt-get c'est passé comme une lettre a la poste. De plus cette page n'est pas un tuto pour faire une mise a jour edgy -> feisty
Hors ligne
Neuro
Re : Connaissances de base pour Kubuntu
Faut il enlever les # devant les lignes # deb ... ?
Hors ligne
mars
Re : Connaissances de base pour Kubuntu
non. Les # servent a commenté des lignes qui ne sont donc pas prises en compte. Soit ce sont des commentaires soit des dépots qui n'ont pas encore été activé.
Hors ligne
Neuro
Re : Connaissances de base pour Kubuntu
non. Les # servent a commenté des lignes qui ne sont donc pas prises en compte. Soit ce sont des commentaires soit des dépots qui n'ont pas encore été activé.
Et comment savoir quand ils le seront ? (désolé mais j' aimerai comprendre).
Hors ligne
mars
Re : Connaissances de base pour Kubuntu
c'est normal et tu as raison je vais le rajouter dans le post! pour savoir quand ils le seront c'est simple : il faut regarder une fois de temps en temps ici : http://www.kubuntu.org/ des annonces de sortie de mise a jour de logiciels sont faites et a ce moment on peut activer le dépot. Par exemple si une mise a jour amarok sort tu active le dépot d'amarok et quelques jours aprés tu aura la mise a jour de disponible.
Pour étre honnéte, pour feisty il y a TRES peu de chance qu'il y en ait sauf peut étre pour kde mais rien n'est moins sur.
Hors ligne
Neuro
Re : Connaissances de base pour Kubuntu
Merci pour ces précisions et pour ce sujet mars.
Dernière modification par Neuro (Le 21/04/2007, à 14:57)
Hors ligne
beware
Re : Connaissances de base pour Kubuntu
Bonjour
n'y a t il pas un risque d'instabilité a utilisé les backports?
Hors ligne
mars
Re : Connaissances de base pour Kubuntu
oui! mais si tu veux etre absolument stable tu dois utiliser dapper. La on parle d'une distribution desktop personnel. Aprés les risques d'instabilité sont tout de meme TRES limité.
Hors ligne
bruno
Re : Connaissances de base pour Kubuntu
t'as raison pour aptitude j'ai tort et tout les dev ubuntu et kubuntu aussi. Comme on avait tort sur les dépots czessi et kubuntu-de. et ceux qui ont cassé leur distrib aussi.
C'est intéressant cette remarque sur aptitude vs apt-get, personnellement j'ai toujours pensé qu'il valait mieux utiliser aptitude (construction de l'arbre des dépendances, gestions des tags et des informations d'état, suppression des paquets marqués "auto", etc.). Aptitude à toujours beaucoup mieux fonctionné pour moi que apt-get (depuis Edgy, pas Dapper).
Il me semble avoir lu à plusieurs reprises qu'aptitude était l'interface APT recommandée par Debian (cf. http://www.debian.org/doc/manuals/reference/ch-package.fr.html)
As-tu des liens, ou des infos complémentaires là dessus ?
Pour l'utilisation de upgrade / dist-upgrade je ne comprend pas bien ta remarque. Normalement upgrade ne proposera que de mettre à jour des paquets déjà installés, en aucun cas cela ne supprimera ou ajoutera des paquets, alors que dist-upgrade est sensé faire une mise à jour "intelligente" en gérant les conflits et dépendances, avec donc la possibilité de suppression de paquets ou installation de nouveaux paquets. Donc dans le cadre de l'utilisation d'une version desktop stable dist-upgrade est recommandé pour faire une mise à jour complète "intelligente", et commencer par un upgrade (mise à jour plus conservatrice) n'aurait de sens que sur une version instable. Est-ce bien ce que tu as voulu dire ?
Sinon je pense que ce sujet épinglé est réellement très utile
Dernière modification par bruno (Le 22/04/2007, à 08:17)
Hors ligne
mars
Re : Connaissances de base pour Kubuntu
alors :
apt vs aptitude! déja AUCUNE doc debian ne conseil aptitude! ils le donnent juste en front end amélioré de apt-get. Ensuite il faut bien savoir que TOUT ce que fait aptitude apt-get sais le faire. Sauf que les paquets de transition, les paquets un peu particulier sont pensé sur la maniére de réagir de apt-get donc dans 99% des cas aptitude marche nickel et meme selon les gouts de certains mieux que apt-get vue qu'il automatise certaines choses. Seulement dans 1% des cas il va pas marché comme les dév l'ont envisagé (exemple de la mise a jour edgy-> feisty). Et la il va tout cassé.
pour update <-> dist-upgrade tu as tout a fait raison tu as tout compris!
dans debian sid il arrive souvent qu'on ait X mise a jour dont la moitié sont annoncé comme des paquets cassant le systéme avec plein de dépedances croisé... dans ce cas la on veut en général ne mettre a jour que les logiciels n'etant pas touché par ces mises a jour dangereuse et LA update a son utilité. Mais c'est tout.
Sinon pour essayer de faire comprendre mes propos :
debian est un systéme trés solide mais trés complexe. Quoi qu'on fasse on arrivera meme en lisant toutes les docs du monde jamais a le maitriser en quelques mois. Et c'est pour cette raison que je me permets de donner des conseils. Je ne sais pas tout loin de la. Mais j'ai assez d'expérience pour savoir certaines choses :
- les dépots tiers c'est trés bien jusqu'au jour ou c'est a chié
- aptitude c'est trés bien mais ca nécessite une forte expérience de apt-get pour étre sur que aptitude fait pas de bétises.
Et le probléme c'est que souvent des gens avec peu d'expérience arrivent et explique qu'ils savent tout et que les dépots tier c'est le réve surtout avec aptitude... et du coup nous on est décridibilisé parce que c'est vrai que ca semble trés bien. Jusqu'au jour ou ca péte tout. mais la il est trop tard.
Donc voila chacun fait ce qu'il veut moi j'ai fait cette doc, je donne les info que je connais et dont je suis certains. Aprés ........
Hors ligne
Neuro
Re : Connaissances de base pour Kubuntu
Sujet trés utile qui m' a permis d 'aider quelques nouveaux venus alors que mon expérience est plutôt faible.
Hors ligne
Smarter
Re : Connaissances de base pour Kubuntu
Intéressant ce post
Quelques trucs comme ça:
- C'est Canonical, pas Cannonical
- Même si il est vrai qu'il faut faire gaffe à aptitude, apt-get est maintenant fortement déconseillé par Debian
- Je ne sais pas si rajouter un raccourci vers la poubelle est une "connaissance de base pour Kubuntu"
- KDE 3.5.7 est prévu pour dans pas longtemps, pareil pour Amarok 1.4.6 donc oui, les dépots de kubuntu.org serviront bientôt à quelque chose.
- fuser(pratique d'ailleurs, je connaissais pas) n'est pas nécessaire pour réparer apt en cas de mise à jour interrompu.
Voila, à part ça c'est pas mal
Hors ligne
mars
Re : Connaissances de base pour Kubuntu
alors!
- pour cannonica j'ai honte!
- ensuite aptitude trouve moi une doc qui justifie tes propos clairement! pour ma part je connais pas un seul DD ou dev ubuntu qui utilise aptitude alors pour le conseiller je les vois mal le faire. (d'autant plus qu'ils le déconseillent)
-la poubelle c'est vrai mais c'est une question assez souvent posé
- kde 3.5.7 ne sera peut étre pas dans les dépots kubuntu! riddell est pas chaud pour se le faire vue que ca coincider avec pas mal d'autres truc (kde4 alpha, dépots gutsy entre autres, ...)
- j'avoue que c'est loin d'étre obligatoire mais j'ai chopé cette commande "toute faite" sur le chan des devs kubuntu et je me suis dit bon je fais pas comme ca mais ca a l'air a la porté du premier con venu et si eux le donne ca doit marcher. (moi j'utilisais fuser a l'époque pour voir qui m'empéchait de démonter mes périph usb!)
Hors ligne
Smarter
Re : Connaissances de base pour Kubuntu
ensuite aptitude trouve moi une doc qui justifie tes propos clairement! pour ma part je connais pas un seul DD ou dev ubuntu qui utilise aptitude alors pour le conseiller je les vois mal le faire. (d'autant plus qu'ils le déconseillent)
Tout droit sortie de la release note de Etch: http://www.fr.debian.org/releases/etch/i386/release-notes/ch-whats-new.fr.html#s-pkgmgmt
kde 3.5.7 ne sera peut étre pas dans les dépots kubuntu! riddell est pas chaud pour se le faire vue que ca coincider avec pas mal d'autres truc (kde4 alpha, dépots gutsy entre autres, ...)
Ah ouais? Je vais peut-être faire un passage à Gutsy plutôt que prévu, moi qui m'étais promis de me retenir pour cette fois-ci
j'avoue que c'est loin d'étre obligatoire mais j'ai chopé cette commande "toute faite" sur le chan des devs kubuntu et je me suis dit bon je fais pas comme ca mais ca a l'air a la porté du premier con venu et si eux le donne ca doit marcher. (moi j'utilisais fuser a l'époque pour voir qui m'empéchait de démonter mes périph usb!)
D'ailleurs je viens de me rendre compte que c'est ce qui est utilisé(fuser -v ) par KDE quand on a quelque chose qui empéche le démontage d'une clé usb, c'est pratique mais ça ne doit pas dire grand chose à un utilisateur lambda...
Hors ligne
rlb29
Re : Connaissances de base pour Kubuntu
Debian préconise l'utilisation d'aptitude :
http://www.debian.org/doc/manuals/refer … ge.en.html
Il gère mieux les dépendances qu'apt-get...si ils les connait !...donc éviter de faire un coup apt-get, un coup aptitude..etc, car dans ce cas là il sera dans l'ignorance de ce que apt-get a bien pu faire.
Debian-sid - kernel 2.6.30-5-amd64 - gestionnaire de fenêtres : xmonad
Hors ligne
|
Remove Duplicate Array Tests
JavaScript performance comparison
Preparation code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
var array = ['data-control="title"', 'data-control="title"', 'data-control="aa"', 'data-control="title"', 'data-control="flip"', 'data-control="aa"', 'data-control="flip"', 'data-control="title"', 'data-control="flip"', 'data-control="title"', 'data-control="title"', 'data-control="title"', 'data-control="title"', 'data-control="title"', 'data-control="title"', 'data-control="aa"', 'data-control="aa"', 'data-control="aa"'];
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
Test Ops/sec pending…
Using for method #2
var temp = {};
for (var i = 0; i < array.length; i++)
temp[array[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
pending…
Using for object
var u = {},
a = [],
v;
for (var i = 0, l = array.length; i < l; ++i) {
v = array[i];
if (u.hasOwnProperty(v)) {
continue;
}
a.push(v);
u[v] = 1;
}
return a;
pending…
Map
var temp = {},
result = [],
x;
for (var i = array.length; i >= 0; i--) {
x = array[i];
if (!(x in temp)) {
temp[x] = 1;
result.push(x);
}
}
return result;
pending…
sort & step
/*
b: sorted array,
i: current index,
l: last added item,
r: resulting list
start with the last item in b in the results list
for each item in b, starting from the 2nd from the end
if it's not the same as the last added one, add it & update the last added
*/
function removeDuplicates(array) {
var b = array.sort(),
i = b.length,
l, r;
for (; i--;) {
l = b[--i];
r = [l];
if (b[i] !== l) r.push(l = b[i]);
}
return r;
}
removeDuplicates(array);
pending…
remodifiied map
/* can skip the first item check & use the array for the 'in' */
var n = array.length,
i, result;
for (; n--;) {
result = [array[n--]];
i = array[n];
if (!(i in result)) result.push(i);
}
return result;
pending…
Array Proto
Array.prototype.removeDuplicates = function() {
var temp = new Array();
this.sort();
for (i = 0; i < this.length; i++) {
if (this[i] == this[i + 1]) {
continue
}
temp[temp.length] = this[i];
}
return temp;
}
array.removeDuplicates();
pending…
modified map
/* can skip the first item check & use the array for the 'in' */
for (var n = array.length, result = [array[n--]], i; n--;) {
i = array[n];
if (!(i in result)) result.push(i);
}
return result;
pending…
remodified map in array prototype
Array.prototype.removeDuplicates = function() {
var n = array.length,
i, result;
for (; n--;) {
result = [array[n--]];
i = array[n];
if (!(i in result)) result.push(i);
}
return result;
}
array.removeDuplicates();
pending…
remodified in function
function removeDuplicates(array) {
var n = array.length,
i, result;
for (; n--;) {
result = [array[n--]];
i = array[n];
if (!(i in result)) result.push(i);
}
return result;
}
removeDuplicates(array);
pending…
remodified with while
/* can skip the first item check & use the array for the 'in' */
var n = array.length,
i, result;
while (n--) {
result = [array[n--]];
i = array[n];
if (!(i in result)) result.push(i);
}
return result;
pending…
sort2
function remove(array) {
var array = array.sort(),
currentIndex = array.length,
lastAdded = array[--currentIndex],
result = [lastAdded];
for (; currentIndex--;)
if (array[currentIndex] !== lastAdded) result.push(lastAdded = array[currentIndex]);
return result;
}
remove(array);
pending…
sort3
function remove(array) {
var array = array.sort(),
currentIndex = array.length,
lastAdded = array[--currentIndex],
result = [lastAdded];
for (; currentIndex--;) {
(array[currentIndex] !== lastAdded) && (result.push(lastAdded = array[currentIndex]));
}
return result;
}
remove(array);
pending…
sort4
/*
b: sorted array,
i: current index,
l: last added item,
r: resulting list
start with the last item in b in the results list
for each item in b, starting from the 2nd from the end
if it's not the same as the last added one, add it & update the last added
*/
for (var b = array.sort(), i = b.length, l = b[--i], r = [l]; i--;)
if (b[i] !== l) r.push(l = b[i]);
return r;
pending…
Compare results of other browsers
Revisions
You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:
Revision 1: published by Levi Tomes
Revision 2: published
Revision 4: published by Sergey
Revision 5: published
Revision 7: published
Revision 8: published
Revision 9: published by imma
Revision 10: published by imma
Revision 11: published
Revision 12: published by Junxi
Revision 14: published
Revision 15: published
Revision 16: published
Revision 17: published
Revision 18: published by ChrisRaven
|
I can't figure out what I'm doing wrong(or how to correct it). It might be easier to show some code(its a bit simplified from what I'm doing but it proves my point):
from multiprocessing import Pool
import MySQLdb
import sys
#sql connection
try:
conn = MySQLdb.connect (host = "127.0.0.1",user = "user",passwd = "password", db = "mydb")
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit (1)
#with database
cursor = conn.cursor ()
cursor.execute ("DROP TABLE IF EXISTS data_table")
cursor.execute ("""
CREATE TABLE data_table(
value CHAR(80)
) ENGINE=MyISAM
""")
cursor.execute (""" INSERT INTO data_table (value) VALUES ('%s')""" % [0, 0]) #need to insert basecase
conn.commit()
def build_table(i,x): # i is index, x is data[i]
conn = MySQLdb.connect (host = "127.0.0.1",user = "user",passwd = "password", db = "mydb")
cursor = conn.cursor ()
#print i,x
target_sum = 100
for s in range(target_sum + 1):
for c in range(target_sum + 1):
#print c, i
cursor.execute ("""
INSERT INTO data_table (value)
SELECT '%s'
FROM dual
WHERE ( SELECT COUNT(*) FROM data_table WHERE value='%s' )
= 1
AND NOT EXISTS
( SELECT * FROM data_table WHERE value='%s' )
""" % ([s, i+1], [s - c * x, i], [s, i+1]))
conn.commit()
conn.close()
data = [2,5,8]
pool = Pool(processes=4)
for i, x in enumerate(data):
build_table(i,x) #creates 250 records
#pool.apply_async(build_table, (i, x))
pool.close()
pool.join()
print 'completed'
It basically creates a table in mysql. The code above creates 250 entries(which is correct), but if you comment out build_table(i,x) in the for loop and uncomment pool.apply_async(build_table, (i, x)) it creates only 52 records. Why is there a difference when multiprocessing the same function and is there anything I can do to fix it so the results are the same(I thought quickly committing updates would fix it but no luck)?
If I play around pool = Pool(processes=4) and change it to 1, it works but I guess thats expected because its not multiprocessing really at that point. Also, if it helps I'm using InnoDB.
UPDATE: when I change to MyISAM I get 240 results being updated(not quite the 250 I need but much better than 52).
UPDATE2: mysql command was combined into a single command, and results seem to vary. Sometimes I get 248 results in the database, sometimes 240 or less. Maybe multiprocessing is causing this diverge between expected and actual results ?
|
I have looked over quite a few posts on this here as well as googling for it. I have used other languages but still learning Python and I'm also not as familiar with classes so I think I'm down to something I just don't understand about the way classes act.
I wanted to work on an epub reading app and found roberto alasina's project called integrate and it was a good starting point but it didn't collect metadata and also the epub handling libs are not extracted enough for some of the other things I want to do. So I found dustjacket which is an epub reading class.
The reason I need to extract this further is I need to handle reads of data from multiple parts of the app and not just the reader itself. I plan on adding whoosh to it to enable searching and for the indexing I will need to read the chapters and then index the files. I can do this during the import of the book and don't really need a gui for the actual indexing part.
Anyway in dist jacket I have added logging and I can see that my method is correctly grabbing the table of contents from the epub:
def __parse_oebps(self, epub):
'''Construct the chapter list assuming that the ePub has files in OEBPS/.'''
# Parse the chapters
npoints = self.__toc.findall("//{%(tocns)s}navPoint" % {'tocns': self.__namespaces['ncx']})
for p in npoints:
#rt = p.getroottree()
#title = p.findtext("{%(tocns)s}text" % {'tocns': self.__namespaces['ncx']}) # Label text
title = p.find(
'{http://www.daisy.org/z3986/2005/ncx/}navLabel').find(
'{http://www.daisy.org/z3986/2005/ncx/}text').text
contentfile = p.find("{%(tocns)s}content[@src]" % {'tocns':self.__namespaces['ncx']}).attrib['src'] # Contentfile name
#if self.__has_oebps:
# #contentfile = "OEBPS/" + contentfile
# contentfile = "OEBPS/" + contentfile
# log.info("content file: %s", contentfile)
#return contentfile
#self.chapters.append(EpubChapter(epub, p.attrib['id'], p.attrib['playOrder'], contentfile, title))
if title and contentfile:
log.debug("Title: %s", title)
log.debug("content file: %s", contentfile)
self.chapters.append([title, contentfile])
return self.chapters
I put in the debug logging and can easily see that the instance is properly called from the class and that the title and contentfile is there. this is from the ebubtoc class and is called from this method in the epub class:
def __read_toc(self):
'''Construct the table of contents for this epub'''
self.__toc = EpubToc(self)
for l, c in self.__toc:
log.debug("Title: %s", l)
log.debug("content file: %s", c)
now when this method gets that data is when I get this error:
for l, c in self.__toc:
TypeError: iteration over non-sequence
I have no idea at this point what I'm doing wrong and why this is not working. I can post the rest of the classes I'm using if this is not enough.
Thanks
|
try:
last_found = -1
for num in L1:
last_found = L2.index(num, last_found + 1)
return True
except ValueError:
return False
The index method of list L2 returns the position at which the first argument (num) is found in the list; called, like here, with a second arg, it starts looking in the list at that position. If index does not find what it's looking for, it raises a ValueError exception.
So, this code uses this approach to look for each item num of L1, in order, inside L2. The first time it needs to start looking from position 0; each following time, it needs to start looking from the position just after the last one where it found the previous item, i.e. last_found + 1 (so at the start we must set last_found = -1 to start looking from position 0 the first time).
If every item in L1 is found this way (i.e. it's found in L2 after the position where the previous item was found), then the two lists meet the given condition and the code returns True. If any item of L1 is ever not-found, the code catches the resulting ValueError exception and just returns False.
A different approach would be to use iterators over the two lists, that can be formed with the iter built-in function. You can "advance" an iterator by calling built-in next on it; this will raise StopIteration if there is no "next item", i.e., the iterator is exhausted. You can also use for on the iterator for a somewhat smoother interface, where applicable. The low-level approach using the iter/next idea:
i1 = iter(L1)
i2 = iter(L2)
while True:
try:
lookfor = next(i1)
except StopIteration:
# no more items to look for == all good!
return True
while True:
try:
maybe = next(i2)
except StopIteration:
# item lookfor never matched == nope!
return False
if maybe == lookfor:
break
or, a bit higher-level:
i1 = iter(L1)
i2 = iter(L2)
for lookfor in i1:
for maybe in i2:
if maybe == lookfor:
break
else:
# item lookfor never matched == nope!
return False
# no more items to look for == all good!
return True
In fact, the only crucial use of iter here is to get i2 -- having the inner loop as for maybe in i2 guarantees the inner loop won't start looking from the beginning every time, but, rather, it will keep looking where it last left off. The outer loop might as well for for lookfor in L1:, since it has no "restarting" issue.
Key, here, is the else: clause of loops, which triggers if, and only if, the loop was not interrupted by break but rather exited naturally.
Working further on this idea we are again reminded of the in operator, which also can be made to continue where it last left off simply by using an iterator. Big simplification:
i2 = iter(L2)
for lookfor in L1:
if lookfor not in i2:
return False
# no more items to look for == all good!
return True
But now we recognize that is exactly the patter abstracted by the short-circuiting any and all built-in "short-circuiting accumulator" functions, so...:
i2 = iter(L2)
return all(lookfor in i2 for lookfor in L1)
which I believe is just about as simple as you can get. The only non-elementary bit left here is: you need to use an iter(L2) explicitly, just once, to make sure the in operator (intrinsically an inner loop) doesn't restart the search from the beginning but rather continues each time from where it last left off.
|
I want to execute a function every 60 seconds on Python but I don't want to be blocked meanwhile.
How can I do it asynchronously?
import threading
import time
def f():
print("hello world")
threading.Timer(3, f).start()
if __name__ == '__main__':
f()
time.sleep(20)
With this code, the function f is executed every 3 seconds within the 20 seconds time.time. At the end it gives an error and I think that it is because the threading.timer has not been canceled.
How can I cancel it?
Thanks in advance!
|
Today I did a fresh install of ubuntu 12.04 and went about setting up my local development environment. I installed mysql and edited /etc/mysql/my.cnf to optimise InnoDB but when I try to restart mysql, it fails with a error:
[20:53][tom@Pochama:/var/www/website] (master) $ sudo service mysql restart
start: Job failed to start
The syslog reveals there is a problem with the init script:
> tail -f /var/log/syslog
Apr 28 21:17:46 Pochama kernel: [11840.884524] type=1400 audit(1335644266.033:184): apparmor="STATUS" operation="profile_replace" name="/usr/sbin/mysqld" pid=760 comm="apparmor_parser"
Apr 28 21:17:47 Pochama kernel: [11842.603773] init: mysql main process (764) terminated with status 7
Apr 28 21:17:47 Pochama kernel: [11842.603841] init: mysql main process ended, respawning
Apr 28 21:17:48 Pochama kernel: [11842.932462] init: mysql post-start process (765) terminated with status 1
Apr 28 21:17:48 Pochama kernel: [11842.950393] type=1400 audit(1335644268.101:185): apparmor="STATUS" operation="profile_replace" name="/usr/sbin/mysqld" pid=811 comm="apparmor_parser"
Apr 28 21:17:49 Pochama kernel: [11844.656598] init: mysql main process (815) terminated with status 7
Apr 28 21:17:49 Pochama kernel: [11844.656665] init: mysql main process ended, respawning
Apr 28 21:17:50 Pochama kernel: [11845.004435] init: mysql post-start process (816) terminated with status 1
Apr 28 21:17:50 Pochama kernel: [11845.021777] type=1400 audit(1335644270.173:186): apparmor="STATUS" operation="profile_replace" name="/usr/sbin/mysqld" pid=865 comm="apparmor_parser"
Apr 28 21:17:51 Pochama kernel: [11846.721982] init: mysql main process (871) terminated with status 7
Apr 28 21:17:51 Pochama kernel: [11846.722001] init: mysql respawning too fast, stopped
Any ideas?
Things I tried already:
I googled and found a Ubuntu bug with apparmor (https://bugs.launchpad.net/ubuntu/+source/mysql-5.5/+bug/970366), I changed apparmor from enforce mode to complain mode:
sudo apt-get install apparmor-utils
sudo aa-complain /usr/sbin/mysqld
sudo /etc/init.d/apparmor reload
but it didn't help. I still can't start mysql.
I also thought the issue may be because the InnoDB logfiles were a different size than mysql was expecting. I removed the innodb log files before restarting using: sudo mv /var/lib/mysql/ib_logfile* /tmp. No luck though.
Workaround: I re-installed 12.04, made sure not to touch /etc/mysql/my.cnf in any way. Mysql is working so I can get on with what I need to do. But I will need to edit it at some point - Hopefully I'll have figured out a solution, or this question will have been answered by that point...
|
Hizoka
encore du sed et awk
Bonjour !
Je viens vers vous pour demander un peu d'aide...
Voici un exemple de fichier sur lequel je travaille :
poupou (0.0.1~ppa1~precise) precise; urgency=low ()
* blublu de bugs
* blabla
-- Belleguic Terence <hizo@free.fr> Fri, 12 Oct 2012 06:39:46 +0200
poupou (0.0.0~ppa1~precise) precise; urgency=low ()
* Correction de bugs
* Amelioration du systeme de la barre de progression
* Suppression du Service Menu et du script Nautilus car : clic droit > ouvrir avec, affiche le logiciel
-- Belleguic Terence <hizo@free.fr> Fri, 12 Oct 2012 06:29:46 +0200
mkv-extractor-gui (4.8.0~ppa1~lucid) lucid; urgency=low ()
* Ajout des dépendances python-webkit imagemagick mclean mkvalidator
* Suppression du systray qui en prévision du passage a gtk3
* Mise à jour de glade2script
* Mise à jour du système de préférence
* Remise en place du service menu ou du script nautilus
* Et d'autres choses...
-- Belleguic Terence <hizo@free.fr> Tue, 24 Jul 2012 00:35:07 +0200
mkv-extractor-gui (4.7.2~ppa2~precise) precise; urgency=low ()
* Refonte du systeme du systray
* Ajout d'une option pour utiliser le même dossier de sortie que celui d'entrée
* Correction de l'ouverture des fichiers contenant un &
* Correction de l'icone de la zone de notification
* Mise à jour de glade2script
* Utilisation de mktemp pour plus de securite
* Mise à jour des texte FR et US
* Ajout de la prise en charge d'unity pour la zone de notification
* Ajout de la langue Tcheque
-- Belleguic Terence <hizo@free.fr> Mon, 23 Jul 2012 18:50:10 +0200
Soit la variable :
nom_paquet=mkv-extractor-gui OU nom_paquet=poupou
Voila ce que je voudrais faire :
1) Récupérer la version logiciel de nom_paquet :
mkv-extractor-gui (
4.8.0~ppa1~lucid) lucid; urgency=low ()
OU
poupou (
0.0.1~ppa1~precise) precise; urgency=low ()
pour cela je fais :
sed -n "/${nom_paquet}/ s/${nom_paquet} .\(.*\)~ppa.*/\1/p" fichier | head -1
y a-t-il moyen de virer le head sans trop compliquer ?
2) Récupérer le texte commençant par des étoiles du 1er bloc de nom_paquet
et la, je bloque...
Avant (je n'avais qu'un seul nom de paquet par fichier) je faisais ca :
awk 'BEGIN {RS="\n\n";FS="\n"} (NR==2) { for(i=1; i < NF; i++) {printf substr($i,5)"@@"} printf substr($NF,5) }' fichier
qui séparait les bloc via les sauts de lignes.
J'ai également besoin des substitutions qui changent les sauts de ligne en @@.
Voila, merci
Dernière modification par Hizoka (Le 21/10/2012, à 15:11)
Hors ligne
pingouinux
Re : encore du sed et awk
Bonjour,
y a-t-il moyen de virer le head sans trop compliquer ?
sed -n "/${nom_paquet}/ s/${nom_paquet} (\(.*\)~ppa.*/\1/p;T;q" fichier
S'il n'y a pas concordance : T envoie à la fin
Sinon, on quitte
Récupérer le texte commençant par des étoiles du 1er bloc de nom_paquet
awk '/'$nom_paquet'/{getline;RS="\n\n";FS="\n";getline;{ for(i=1; i < NF; i++) {printf substr($i,5)"@@"} printf substr($NF,5)"\n" }exit}' fichier
Dernière modification par pingouinux (Le 12/10/2012, à 09:01)
Hors ligne
pingouinux
Re : encore du sed et awk
J'ai complété ma réponse au moment où tu répondais.
Hors ligne
Hizoka
Re : encore du sed et awk
une derniere question,
un awk qui me permettrait de changer le texte commencant par des etoiles avec un autres texte ?
awk -v OCC=1 -v var="${cacavar}" 'BEGIN{ OLDRS=RS;RS="\n\n\n" } NR==OCC {printf("%s\n\n\n",var);RS=OLDRS} NR!=OCC' "${changelog}" > "${changelog}-new"
Hors ligne
pingouinux
Re : encore du sed et awk
Bonjour,
un awk qui me permettrait de changer le texte commencant par des etoiles avec un autres texte
S'agit-il de ce texte ?
Récupérer le texte commençant par des étoiles du 1er bloc de nom_paquet
Si oui :
nom_paquet=mkv-extractor-gui
mon_texte='Ligne n°1 de mon texte
Ligne n°2 de mon texte
Ligne n°3 de mon texte'
awk -v mon_texte="$mon_texte" '{if(/^'"$nom_paquet"' /&&!deja){print;getline;print;ORS_=ORS;RS_=RS;ORS=RS="\n\n";getline;print mon_texte;deja=1;ORS=ORS_;RS=RS_}else{print}}' fichier
Hors ligne
Hizoka
Re : encore du sed et awk
arf !
il me faut encore modifier le code
Il me faut donc toujours rechercher un bloc a partir d'un nom, mais le rempacement ne doit pas se limiter au texte etoilé mais à tout le bloc.
Donc, si je cherche mkv-extractor-gui :
mkv-extractor-gui (4.8.0~ppa1~lucid) lucid; urgency=low ()
* Ajout des dépendances python-webkit imagemagick mclean mkvalidator
* Suppression du systray qui en prévision du passage a gtk3
* Mise à jour de glade2script
* Mise à jour du système de préférence
* Remise en place du service menu ou du script nautilus
* Et d'autres choses...
-- Belleguic Terence <hizo@free.fr> Tue, 24 Jul 2012 00:35:07 +0200
Désolé et merci
Hors ligne
pingouinux
Re : encore du sed et awk
Bonsoir,
Une solution en python :
$ cat remplacement.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
import sys, re
mon_paquet='mkv-extractor-gui'
mon_texte='''Ligne n°1 de mon texte
Ligne n°2 de mon texte
Ligne n°3 de mon texte'''
with open(sys.argv[1],'r') as f : txt=f.read()
sys.stdout.write( re.sub('(?m)^%s.*\n\n( \*.*\n)+\n --.*$'%mon_paquet,mon_texte,txt,count=1) )
Utilisation :
./remplacement.py fichier
Hors ligne
pingouinux
Re : encore du sed et awk
$ cat remplacement.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
import sys, re
with open(sys.argv[1],'r') as f : txt=f.read()
mon_paquet=sys.argv[2]
mon_texte=sys.argv[3]
sys.stdout.write( re.sub('(?m)^%s.*\n\n( \*.*\n)+\n --.*$'%mon_paquet,mon_texte,txt,count=1) )
Utilisation :
./remplacement.py fichier mkv-extractor-gui 'Ligne n°1 de mon texte
Ligne n°2 de mon texte
Ligne n°3 de mon texte'
Hors ligne
Hizoka
Re : encore du sed et awk
Bon j'ai fait autrement car ca me derangait d'obliger d'utiliser python (et donc son installation) pour un logiciel tout en bash...
voila ma solution :
nom_paquet="mkv-extractor-gui"
tout=$(< "${changelog}")
tout_jusqua_mkv="${tout%%${nom_paquet}*}"
tout_apres_mkv="${nom_paquet} ${tout#*${nom_paquet} }"
tout_apres_mkv="${tout_apres_mkv#*$'\n\n\n'}"
echo "${tout_jusqua_mkv}mkv-extractor-gui blabla
* blbabla
* ...
${tout_apres_mkv}
" > "${changelog}"
pas forcement tres rapide ou des plus simple, mais ca devrait marcher en se passant de python.
En tout cas, pingouinux, je te remercie ENORMEMENT pour le temps passé à me lire et à essayer de m'aider !!!
Vraiment merci !
Hors ligne
nesthib
Re : encore du sed et awk
J'arrive un peu après la bataille mais voici quelques suggestions en awk (parce que awk c'est fun) :
Afficher le numéro de version de la première ligne contenant mkv-extractor-gui :
awk '/^mkv-extractor-gui/{print gensub(/[^ ]* \(([0-9.]+).*/,"\\1", "g") ; exit}' changelog
Récupérer le numéro de version dans la première ligne commençant par mkv-extractor-gui si disponible, sinon dans la première ligne commençant par poupou :
awk '/^mkv-extractor-gui/{if (! v1) {v1=gensub(/[^ ]* \(([0-9.]+).*/,"\\1", "g")}};/^poupou/{if (! v2) {v2=gensub(/[^ ]* \(([^~]+).*/,"\\1", "g")}} END {print (v1?"version1 : "v1:(v2?"version2 : "v2:"Erreur, aucun numéro de version trouvé"))}' changelog
Récupérer le premier bloc commençant par mkv-extractor-gui :
awk '/^mkv-extractor-gui/{start++}; {if (start) {if (newline==2) {exit} ; if (!$0) {newline++} else {newline=0} ; print}}' changelog
ici j'affiche le bloc au fur et à mesure, mais il va de soi que tu peux stocker les lignes dans un tableau et même les modifier. Avec mon exemple tu as 2 lignes vides à la fin mais si tu affiches le contenu de ton tableau dans le bloc « END {…} » tu peux facilement les supprimer.
Pour récupérer un bloc différent (ex. le second) il te suffit de changer le (start) en (start==2).
Pour remplacer les sauts de ligne par « @@ » il suffit également d'ajouter « BEGIN{ORS="@@"} » au début de la commande awk.
Une méthode plus compacte si tu désires juste faire de l'affichage :
awk 'BEGIN{RS="\n\n\n+"} /^mkv-extractor-gui/{print;exit}' changelog
Maintenant si tu veux remplacer spécifiquement ce bloc tout en gardant le reste :
NOUVEAU_BLOC='nouveau bloc\n\n * au milieu\n\n'
awk '/^mkv-extractor-gui/{start++}; {if (start && newline<2) {if (!$0) {newline++} else {newline=0} ; if (newline==2) {print "'"${NOUVEAU_BLOC}"'"; newline++}} else {print}}' changelog
une variante plus courte :
NOUVEAU_BLOC='nouveau bloc\n\n * au milieu'
awk 'BEGIN{RS="\n\n\n+";ORS="\n\n\n"} /^mkv-extractor-gui/{$0=(a++?$0:"'"${NOUVEAU_BLOC}"'")};1' changelog
Et si tu veux insérer ton nouveau bloc avant la première occurrence de ton bloc en mkv-extractor-gui (il y a plus simple si l'on se contentait de trouver ce mot clé, mais ici ça vérifie que ce qui suit est bien un bloc. Voir l'exemple suivant) :
NOUVEAU_BLOC='nouveau bloc\n\n * au milieu\n\n'
awk '/^mkv-extractor-gui/{start++}; {if (start && newline<2) {if (!$0) {newline++} else {newline=0} ; if (newline==2) {print "'"${NOUVEAU_BLOC}"'"; newline++ ; print bloc} ; bloc=bloc$0"\n"} else {print}}' changelog
Même chose sans vérifier que le bloc suit le format attendu :
NOUVEAU_BLOC='nouveau bloc\n\n * au milieu\n\n'
awk '/^mkv-extractor-gui/{start++;if (start==1) { print "'"${NOUVEAU_BLOC}"'"}}; {print}' changelog
une variante :
NOUVEAU_BLOC='nouveau bloc\n\n * au milieu\n\n'
awk 'BEGIN{RS="\n\n\n+";ORS="\n\n\n"} /^mkv-extractor-gui/{$0=(a++?"":"'"${NOUVEAU_BLOC}"'\n")$0};1' changelog
Comme quoi awk c'est vraiment génial non ?
NB. juste pour être plus sérieux je te signale aussi l'existence de la commande debchange (et de son option -a) qui permet d'éditer les fichiers de changelog
Hors ligne
Hizoka
Re : encore du sed et awk
merci beaucoup pour ces commandes
Je n'arrive vraiment pas à saisir awk, ca me semble tellement compliqué...
Oui j'ai testé debchange, mais le soucis c'est que si tu veux ajouter 25 lignes ca te prends 7sec alors qu'avec un awk ou des echos, ca va bcp plus vite et c'est bien dommage !
Hors ligne
|
I think Both Pickup and the Throw are STANDARD ACTIONS. Equip/Stow a Sheild is a Standard. Heaving a 60-200 lb person in the air and having the proper grasp on them doesn't seem Minor. Maybe the small Kobold at 40 lbs would be minor. I would say a brute grasp to toss overhand/overhead would be minor. But to prepare for an Athletic Toss, no. I differentiate between those two tosses below.
So here are my calculations of how far, accuracy, damage and the reasons/logic behind them. Hope they are useful. It was a fun exercise. I think I'm going to have to use these in a trap design. - RoyalEF
if we look to reality:
The Olympic hammer throw reaches 300 feet for 16 pounds.
Scottish Heavy Weight Throw for Distance ranges 36-46 ft for 56 lbs.
2002 British Champion Dwarf toss was only 11'4" for 98 lbs.
So there are some true examples. Smaller weights go dramatically further. All of these are Athletic throws, they wind up and toss. They don't care too much about accuracy side to side, just maximizing distance. Overhead throws are MUCH LESS efficient!
BTW, In 4e Halflings are 4' and 75-85 pounds.
Improvised Weapons under Melee limit it to 1 LB. And range is 5/10, Hit for 1d4.
I think you have to treat the Halfling the same as if the the player wanted to throw a Barrel or a Boulder. Players may want to do that... it should be no different, including the damage potential to the barrel. If the throwee was unwilling it would involve a Standard Action of a Grab, and a second Standard Action of the lift and throw. You would have to add a strong negative if they were struggling/fighting.
My calculations are reasonably simple, AND THEY SCALE TO THE MONSTER MANUAL FOR ROCK THROWING DISTANCE OF MONSTERS!!! Woo-Hoo, we're balanced!
STR 18 (Normal Load:180lbs, Heavy Load and Slowed:360) I don't think a Slowed state is viable for a toss.
So (for me) STR 18 is tossing with a total encumbered load of 180lbs. Trained Athletics, should increase this and compensates in the equations!! I'd have to say some sort of -1 per 10 lbs over that is in order. We'll assume all toss weight examples don't push us over Normal Load.
How far can it be thrown?
It is a factor of the HEIGHT of thrower and STR vs WEIGHT. However, if you shot put or pitch the weight, Athletics should STRONGLY come into play. And let's make sure our level adds to the epicness of our throw.
In "Long Jump" you add 1/3 of your height to your height to represent your arm reach height. For a Monster, I would add 1/3 to their SIZE (Medium=5',Large=10',Huge=15', etc) as a shortcut to researching heights. Alternately, you could add Monster SIZE & MELEE REACH, this would overextend reach on some, but it accounts for when Monster Stats account for TALL sizes.
So...
OVERHEAD THROW check (clumsy, inefficient--only dumb trolls do this)
d20 + STR CHECK Mod + Reach Height(Rounded) - (Weight of object/10,Rounded)
Lvl 1, STR: 10( 0), 8 ft reach, 10lb = d20 + 7 ft (throw a milk gallon, 8lbs)
Lvl 1, STR: 18(+4), 8 ft reach, 10lb = d20 + 11 ft (13-31')
Lvl 10, STR: 18(+9), 8 ft reach, 10lb = d20 + 16 ft (18-36')
Lvl 1, STR: 18(+4), 8 ft reach, 98lb Halfling = d20 + 7 ft (9-20')
Lvl 9, STR: 22(+10), 20 ft reach, 98lb Halfling = D20 + 20 feet. (Troll, 22-40')
Lvl 13, STR: 21(+11), 20 ft reach, 60 lb rock = d20 + 25' (Hill Giant, 27-45')
60 lbs of concrete mix is about a 11.5" sphere.
This Hill Giant has a HURL ROCK range of 8/16 (40'/80') in MM1.
This inefficient method is right in Short Range.
ATHLETIC THROW check (leveraging your STR in an Athletics move)
d20 + STR Ability Score + STR CHECK MOD + ATHLETICS Check MOD + Reach Height (Rounded) - (Weight of object/10,Rounded)
Outside of Combat, the DM might consider letting players TAKE 10, if they know that will succeed at the distance they want. In combat, always roll even if only Natural 1 fails.
If you are targeting something and not going for pure long distance, Targeting below deals with the misses.
Calculations:
Lvl 13, STR: 21(+11), ATH: +16, 13 ft reach height, 60lb rock = d20 + 56' (58-76')
This Hill Giant has a HURL ROCK range of 8/16 (40'/80') in MM1. Near Long Range!
If I use SIZE + MELEE REACH I get d20 + 63'. Right on Target.
Lvl 16, STR: 23(+14), ATH: +19, 20 ft reach, 60lb rock = d20 + 86' (88-106')
This Earth Titan Giant has a HURL ROCK range of 20 (100') in MM1. DONE!!
Distances are scaling well against existing D&D 4E throws.
Targeting
In Ranged Combat, you don't care how far the aerodynamic weapon travels when it misses. Only that it had the range to hit. The above Athletics Check determine the ultimate range for a heavy, awkward non-projectile being unceremoniously tossed.
But what about accuracy, like a basic ball toss. If the mark is comfortably within your range, you have more control. But you can still miss. So here's my take on it.
The above Athletics check determines if you get the range you needed. If it falls short, it falls short. Maybe the DM decides that within 3 feet the hurled Halfling can a Grab for the ledge the same as a Fall During Climbing? House rules apply.
However, Strength doesn't determine Ranged accuracy. For more accuracy in the throw, I think you need a second roll for DEX CHECK. (-1 for every 10 lbs over Normal Load)
For a living target, you're doing DEX vs. AC. If you don't hit, you can randomize in which adjacency the tossed lands in. Perhaps let the target choose. DM rules.
As a guide for hitting inanimate objects (like floors), I use DMG Pg. 65.
AC 5 = Medium Size Target (5'x5'=1 square area)
AC 8 = Small Size Target
AC 10 = Tiny Sized Target (bottle, book)
For every 1 the DEX Check falls short, you missed the target by 5% of the thrown distance.
What direction? Simple d4 it.
1=left
2=right
3=short
4=overshot (or projectile/target decides)
4 gives the Dwarf a chance to pick his fate, as opposed to overshot for a barrel of flammable oil.
Strong but Clumsy Olaf Tosses a Dwarf onto a 5'x5' floating platform 30' away:
OLAF: Lvl 2, STR:20(+6), DEX:8(-1), Athletics:(1) Reach:8', Dwarf(180lbs)
Athletics d20 roll = 18 , distance=35' (good for range)
Dexterity d20 roll = 2 , DC:5 missed by 4 (20% of 30'), 6 feet
d4 roll = 3
Short by 6'
The DM can rule how to measure this. From the center of the square is decent. That would mean that 1-2' off would basically land you on the edge. 3-5' puts most people within reach of catching the edge.
LANDING OF THE HURLED
The tosser has succeeded with both rolls. For the sentient tossed, the landing should be determined. This is a basic ACROBATIC Check by the tossed. Succeed, they land standing. Fail, they are prone. Natural 1, they landed prone and bounced or slid past the target. One square seems fine as a punishment. Again, grabbing for an edge is always there.
DOES BEING TOSSED HURT? DAMAGE?
Of course it does. That's why Hill Giants throw rocks. Earth Elementals can hear the rocks yelling, "Ouch!"
Scaling to hurled rock damages is trickier. D&D doesn't scale falling damage by weight--physics disagrees. Falling damage is a flat 1d10 for every 10 feet of drop, the weight of the faller is ignored. With the angles we're using, I'm thinking a bit less is appropriate. I've come up with something that takes drops into consideration, too.
Roll 1d4 for every 15 feet thrown. Add 1d10 for every 10 feet the landing is below the thrown from surface.
Hill Giant, 80 ft throws = 5d4, 5-20 hp. (MM1, 7-17 hp)
Earth Titan Giant, 100 ft throws = 6d4, 6-24 hp. (MM1, 8-26 hp)
Formula is scaling reasonably.
If you're throwing across a pit where the target floor is the same level then the 1d10 doesn't matter. But when you have to fall down to get to the target, you should get falling damage.
Olaf is throwing the Dwarf across a 30' Chasm to a Ledge 20' below.
Olaf, 160lb Dwarf, 30' across, 20' down = 2d4 + 2d10
Olaf is throwing the Dwarf across a 30' Chasm to a Ledge 60' below.
Olaf, 160lb Dwarf, 30' across, 60' down = 2d4 + 6d10
Damage would be to the Dwarf as well as the target.
UPWARD TOSS
What if you're tossing upward to a target above you. Keep it simple.
Height gain is the distance of ATHLETICS Check divided by 5 plus the reach height of the tosser. ATHLETICS Check was 35 = 7 feet higher than my 8 ft reach height or 15'
If landing on a higher structure the d4 damage should be halved and the d10 ignored. Tossing something on a high shelf requires timing the top of the arc of the throw to just clear the ledge. This should limit the horizontal distance to HALF the maximum determined by the ATHLETICS check.
SOFT LANDING STRIP
The DM will have to rule on soft landing areas. Stone has 2x more HP than Wood and Wood has 10x more HP than cloth. So softer materials could absorb some of the HP damage. You could say for every 1' of soft materials 1d10 is avoided. In the real world, 9" of wood mulch will protect a ten foot fall (Playground Standards). Perhaps every 1' of loose, soft, compressible materials will absorb 1d10. If the materials aren't so soft, maybe it should be 1d8, or 1d6. At least that gives a DM something to chew on.
NOTE: In HotFK pg 285. Someone TRAINED in Acrobatics can reduce falling damage.
"Reduce Falling Damage (Trained Only) If an adventurer who has training in Acrobatics falls, he or she can make an Acrobatics check to reduce the amount of falling damage he or she takes. Your character can make this check whether or not the fall is intentional. It is a free action in response to falling.The amount of falling damage that you take is reduced by one-half the check result (rounded down). If the falling damage is reduced to 0, you land standing.
|
AlexandreP
Re : Generateur de sources.list en Francais
Euh... en même temps, je suis pas totalement sûr que ce soit ça : si on regarde le message d'erreur, Ubuntu tente de rejoindre l'adresse IP 1.0.0.0. Je doute très très fortement que se soit la bonne adresse du serveur
Un connaisseur, siouplease ?
«La capacité d'apprendre est un don; La faculté d'apprendre est un talent; La volonté d'apprendre est un choix.» -Frank Herbert
93,8% des gens sont capables d'inventer des statistiques sans fournir d'études à l'appui.
Hors ligne
Azema
Re : Generateur de sources.list en Francais
A mon avis, tu as un problème de DNS.
Ton serveur DNS supérieur ne résout pas correctement l'adresse http://archive.canonical.com
Je te conseille de vérifier les serveurs DNS indiqué pour ta connection internet que tu peux voir en faisant
cat /etc/resolv.conf
Pour ce qui est des dépôts rapides et peu encombrés, il faut voir du côté de la Suisse ou de la Belgique. Mais chuttttt, il ne faut pas le dire à tout le monde sinon ils vont être grave encombrés. ;-)
Cordialement, Azema.
Pour obtenir un fichier sources.list propre, rendez-vous sur www.sourceslist.org
Si votre problème est résolu, merci de l'indiquer dans l'en-tête de votre topic avec le terme [RESOLU].
Hors ligne
Zillable
Re : Generateur de sources.list en Francais
Un dépôt à rajouter :
#Dépôt du logiciel Miro
deb http://ftp.osuosl.org/pub/pculture.org/miro/linux/repositories/ubuntu gutsy/
"Thanks to Mr. Gates, we now know that an open Internet with protocols anyone can implement is communism; it was set up by that famous communist agent, the US Department of Defense." Richard Stallman
"They who can give up essential liberty to obtain a little temporary safety, deserve neither liberty nor safety." Benjamin Franklin
Hors ligne
superfigaro
Re : Generateur de sources.list en Francais
Bonjour,
Un nouveau souci pour moi
E: /var/cache/apt/archives/libisc32_1%3a9.4.1-P1-3ubuntu1_i386.deb: le sous-processus dpkg-deb --control a retourné une erreur de sortie d'état 2
E: /var/cache/apt/archives/libdns32_1%3a9.4.1-P1-3ubuntu1_i386.deb: le sous-processus dpkg-deb --control a retourné une erreur de sortie d'état 2
E: /var/cache/apt/archives/libisccc30_1%3a9.4.1-P1-3ubuntu1_i386.deb: le sous-processus dpkg-deb --control a retourné une erreur de sortie d'état 2
E: /var/cache/apt/archives/libisccfg30_1%3a9.4.1-P1-3ubuntu1_i386.deb: le sous-processus dpkg-deb --control a retourné une erreur de sortie d'état 2
E: /var/cache/apt/archives/libbind9-30_1%3a9.4.1-P1-3ubuntu1_i386.deb: le sous-processus dpkg-deb --control a retourné une erreur de sortie d'état 2
E: /var/cache/apt/archives/liblwres30_1%3a9.4.1-P1-3ubuntu1_i386.deb: le sous-processus dpkg-deb --control a retourné une erreur de sortie d'état 2
E: /var/cache/apt/archives/bind9-host_1%3a9.4.1-P1-3ubuntu1_i386.deb: le sous-processus dpkg-deb --control a retourné une erreur de sortie d'état 2
E: /var/cache/apt/archives/dnsutils_1%3a9.4.1-P1-3ubuntu1_i386.deb: le sous-processus dpkg-deb --control a retourné une erreur de sortie d'état 2
E: /var/cache/apt/archives/libgs8_8.61.dfsg.1~svn8187-0ubuntu3.3_i386.deb: le sous-processus dpkg-deb --control a retourné une erreur de sortie d'état 2
E: /var/cache/apt/archives/ghostscript_8.61.dfsg.1~svn8187-0ubuntu3.3_i386.deb: le sous-processus dpkg-deb --control a retourné une erreur de sortie d'état 2
E: /var/cache/apt/archives/ghostscrip
euh quézaquo c'est jamais arrivé avant !
merci de m'aider.
Hors ligne
Azema
Re : Generateur de sources.list en Francais
Salut,
Pourrais tu nous dire quel(s) paquet(s) tu as souhaité installer ?
Cordialement, Azema.
Pour obtenir un fichier sources.list propre, rendez-vous sur www.sourceslist.org
Si votre problème est résolu, merci de l'indiquer dans l'en-tête de votre topic avec le terme [RESOLU].
Hors ligne
Peepingtom
Re : Generateur de sources.list en Francais
Salut,
je souhaite me creer un fichier sources.list propre, par le biais de l'adresse www.sourceslist.org, mais pas moyen d'y accéder sous Ubuntu, là je suis sous Xp je peux y acceder mais sous Ubuntu Firefox me met la page d'erreur. Je capte pas trop pourquoi moi ^^
Si quelqu'un a une idée, en espérant que c'est le bon endroit pour poster.
gtomtom
Re : Generateur de sources.list en Francais
Un petit "up" pour savoir quel est le problème avec le générateur de sources.list
Azema
Re : Generateur de sources.list en Francais
Salut à tous,
Désolé de venir si tardivement pour vous donner des nouvelles.
Le générateur de fichier sources.list est en pleine restructuration. Suite à divers problème rencontrés, j'ai préféré refaire le générateur correctement afin qu'il puisse suivre, sans problèmes, l'évolution du Zend Framework.
Je vous prie de bien vouloir m'excuser pour le dérangement et je me presse de terminer le travail afin qu'il soit prêt pour la sortie de la dernière version d'Ubuntu (sans certitudes).
A très bientôt sur le générateur Sourceslist.org
Azema.
Pour obtenir un fichier sources.list propre, rendez-vous sur www.sourceslist.org
Si votre problème est résolu, merci de l'indiquer dans l'en-tête de votre topic avec le terme [RESOLU].
Hors ligne
jajaX
Re : Generateur de sources.list en Francais
merci à toi pour ton travail
c'est clair que j'en ai pris l'habitude et qu'en j'en ai besoin ben....
@+ 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
sylvainvh
Re : Generateur de sources.list en Francais
Tout d'abord, je te souhaite un très bon courage et je te félicite pour ce que tu fais.
J'ai une petite proposition à faire, ne serrait pas une bonne idée que pour l'instant de mettre un petit lien vers une page avec quelques sources.list complète pour chaque version? Même si on peut tjrs les trouver dans le wiki une petite page récapitulatif avec une sources.list ne serrait-il pas une bonne idée?
Je suis près à créer cette page.
Bonne continuation
Hors ligne
Azema
Re : Generateur de sources.list en Francais
Salut à tous,
Merci pour vos encouragements, ça remonte le moral !!!
Pour répondre à sylvainvh, il y a déjà des dépôts qui sont recenser sur le wiki, mais je crois que les admins ne souhaitent pas ajouter de dépôts tiers qui pourraient causés des problèmes de compatibilité (que l'on me corrige si je me trompe).
En attendant que le générateur de fichiers sources.list soit remis en route, je te conseille d'aller sur Google et de chercher "depots ubuntu", si tu cherches bien tu devrais pouvoir trouver plusieurs sources.list avec divers sources, mais je te conseilles vivement d'aller voir le dépôt à l'aide ton navigateur avant de le mettre dans ton fichier sources.list
Cordialement, Azema.
Pour obtenir un fichier sources.list propre, rendez-vous sur www.sourceslist.org
Si votre problème est résolu, merci de l'indiquer dans l'en-tête de votre topic avec le terme [RESOLU].
Hors ligne
Ju.
Re : Generateur de sources.list en Francais
http://doc.ubuntu-fr.org/sources.list devrait faire l'affaire en attendant.
Have Fun !
Conduite à tenir face aux trolls
Hors ligne
lefanfan
Re : Generateur de sources.list en Francais
Bjs vs je voudrai juste savoir aproximativement quand sourceslist.org sera ouvert a nouveau. J' utilise actuelemnt le source list d'un ami depuis mon passage a la 8.04 mais j'aimerai savoir si le site sera dispo bientot... Car si l'ouverture est proche j'ai pas envie de faire une longue recherche qui sera inutile pour repersonaliser mon source list.(source list de mon ami sans commentaire et blinder de depots surement pas tip top et je n'ai pas envie de les verifier un par un.
Merci a vous.
Ps : si l'un de vous aurai un fichier source list bine remplie avec key et commentaire inclu merci de penssez a moi (HARYFRANCOIS@HOTMAIL.fr)
jajaX
Re : Generateur de sources.list en Francais
salut
en attendant tu as cette page de la doc
@+ 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
cocolapin2007
Re : Generateur de sources.list en Francais
Bonjour,
quelqu'un à des infos sur le retour du site http://www.sourceslist.org/
Merci
bon dimanche
Hors ligne
Iluvatar
Re : Generateur de sources.list en Francais
Bonjour à tous
Après migration vers hardy, mon système ne ce m'étais pas à jour. La sources.list étais complètement bugger, alors j'ai tenter de faire la propre sources.list (comme le générateur n'est pas encore remit en fonction, d'ailleurs, bon courage !!) :
### DÉPÔTS OFFICIEL
## Ubuntu Hardy
deb http://fr.archive.ubuntu.com/ubuntu/ hardy main restricted
deb http://fr.archive.ubuntu.com/ubuntu/ hardy universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy restricted main multiverse universe
## Ubuntu Hardy security
deb http://security.ubuntu.com/ubuntu hardy-security main restricted
deb http://security.ubuntu.com/ubuntu hardy-security universe multiverse
# deb-src http://security.ubuntu.com/ubuntu hardy-security restricted main multiverse universe
# deb-src http://security.ubuntu.com/ubuntu hardy-security universe multiverse
## Ubuntu Hardy updates
deb http://fr.archive.ubuntu.com/ubuntu/ hardy-updates main restricted
deb http://fr.archive.ubuntu.com/ubuntu/ hardy-updates universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy-updates restricted main multiverse universe
# deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy-updates universe multiverse
## Ubuntu Hardy backports
deb http://fr.archive.ubuntu.com/ubuntu/ hardy-backports main restricted universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy-backports main restricted universe multiverse #Added by software-properties
## Ubuntu Hardy proposed
# deb http://fr.archive.ubuntu.com/ubuntu/ hardy-proposed main restricted universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy-proposed main restricted universe multiverse
## Ubuntu Hardy Commercial
deb http://archive.canonical.com/ubuntu hardy partner
deb http://archive.canonical.com/ubuntu hardy-backports partner
deb http://archive.canonical.com/ubuntu hardy-security partner
deb http://archive.canonical.com/ubuntu hardy-updates partner
# deb http://archive.canonical.com/ubuntu hardy-proposed partner
### DÉPÔTS MEDIBUNTU
## KEY GPG: wget -q http://packages.medibuntu.org/medibuntu-key.gpg -O- | sudo apt-key add -
deb http://fr.packages.medibuntu.org/ hardy free non-free
### DÉPÔTS WINE
## KEY GPG: wget -q http://wine.budgetdedicated.com/apt/387EE263.gpg -O- | sudo apt-key add
deb http://wine.budgetdedicated.com/apt hardy main
Ôtant un débutant sous linux, j'aimerai avoir votre avis, merci d'avance !!
Packard Bell EseayNote Tj75-JO-140FROrdinateur portable - 15,6 po - Intel Pentium i5 - Disque Dur : 640 Go - RAM : 4 Go
Hors ligne
sylvainvh
Re : Generateur de sources.list en Francais
Bah moi j'ai fais une sources.list complète! Attention, le dernier dépot est à utiliser avec précotion, c'est amarok2 en plein développement ... ou si non, les 3 derniers dépots ne sont pas du tout indispensable.
deb cdrom:[Ubuntu 8.04 _Hardy Heron_ - Release i386 (20080423)]/ hardy main restricted
##############################################
## Dépôts Principales
# Depots Principales
deb http://nl.archive.ubuntu.com/ubuntu/ hardy main restricted
deb http://security.ubuntu.com/ubuntu hardy-security main restricted
deb http://nl.archive.ubuntu.com/ubuntu/ hardy-updates main restricted
# deb-src http://nl.archive.ubuntu.com/ubuntu/ hardy main restricted
# deb-src http://security.ubuntu.com/ubuntu hardy-security main restricted
# deb-src http://nl.archive.ubuntu.com/ubuntu/ hardy-updates main restricted
##############################################
## Dépôts Universe et Multiverse
# Depots Universe et Multiverses
deb http://nl.archive.ubuntu.com/ubuntu/ hardy universe multiverse
deb http://security.ubuntu.com/ubuntu hardy-security universe multiverse
deb http://nl.archive.ubuntu.com/ubuntu/ hardy-updates universe multiverse
# deb-src http://nl.archive.ubuntu.com/ubuntu/ hardy universe multiverse
# deb-src http://security.ubuntu.com/ubuntu hardy-security universe multiverse
# deb-src http://nl.archive.ubuntu.com/ubuntu/ hardy-updates universe multiverse
##############################################
## Backports
# Depot Backports
deb http://nl.archive.ubuntu.com/ubuntu/ hardy-backports main restricted universe multiverse
# deb-src http://be.archive.ubuntu.com/ubuntu/ hardy-backports main restricted universe multiverse
##############################################
## Proposed
# Proposed
# deb http://nl.archive.ubuntu.com/ubuntu/ main restricted universe multiverse
# deb-src http://nl.archive.ubuntu.com/ubuntu/ main restricted universe multiverse
##############################################
## Commercial
# Commercial
deb http://archive.canonical.com/ubuntu hardy partner
# deb-src http://archive.canonical.com/ubuntu hardy partner
##############################################
## MEDIBUNTU
# Depot Medibuntu
deb http://fr.packages.medibuntu.org/ hardy free non-free
# deb-src http://fr.packages.medibuntu.org/ hardy free non-free
# deb http://fr.packages.medibuntu.org/ hardy-staging free non-free
# deb-src http://fr.packages.medibuntu.org/ hardy-staging free non-free
# wget -q http://fr.packages.medibuntu.org/medibuntu-key.gpg -O- | sudo apt-key add -
##############################################
## Elbuntu
# Depot Elbuntu
deb http://e17.dunnewind.net/ubuntu hardy e17
# deb-src http://e17.dunnewind.net/ubuntu hardy e17
# wget -q http://lut1n.ifrance.com/repo_key.asc -O- | sudo apt-key add -
##############################################
## VirtualBox
# Depot VirtualBox
deb http://www.virtualbox.org/debian gutsy non-free
##############################################
## Wine
# Depot Wine
deb http://wine.budgetdedicated.com/apt hardy main
# deb-src http://wine.budgetdedicated.com/apt hardy main
# wget -q http://wine.budgetdedicated.com/apt/387EE263.gpg -O- | sudo apt-key add -
##############################################
## Avant-Window-Navigator
# Depot Avant-Window-Navigator
deb http://ppa.launchpad.net/reacocard-awn/ubuntu hardy main
# deb-src http://ppa.launchpad.net/reacocard-awn/ubuntu hardy main
##############################################
## EnvyNG
# Depot EnvyNG
deb http://ppa.launchpad.net/envyng-hardy/ubuntu hardy main
##############################################
## PyTube
# Depot PyTube
deb http://www.bashterritory.com/pytube/releases /
##############################################
## KDE4
#Depot KDE4
deb http://ppa.launchpad.net/kubuntu-members-kde4/ubuntu gutsy main
##############################################
## Neon
# Depot Amarok2
deb http://ppa.launchpad.net/project-neon/ubuntu hardy main
Hors ligne
quentin_
Re : Generateur de sources.list en Francais
##############################################
## PyTube
# Depot PyTube
deb http://www.bashterritory.com/pytube/releases /
De quel logiciel s'agit-il ?
Hors ligne
compte supprimé
Re : Generateur de sources.list en Francais
De PyTube peut-être?
Elle sert à télécharger des vidéos depuis Youtube et de tout autres sites proposant des contenus vidéos (Metacafé, GoogleVideo, etc.). PyTube permet aussi de convertir ces vidéos dans les formats les plus connus (avi, mpg, ogm) et offre un set d'outils pour extraire la bande son des vidéos aux formats (mp3, ogg ou wav), opérer des rotations ou encore assembler plusieurs vidéos en un seul fichier. Depuis la version 0.0.10 on peut aussi noter la présence d'un outils de recherche intégré de vidéos pour Youtube.
(http://www.cedynamix.fr/dotclear/index.php?post/2008/05/04/PyTube-%3A-Vos-videos-preferees-sur-votre-Ubuntu)
sylvainvh
Re : Generateur de sources.list en Francais
Je vois que je ne suis pas le seul lecteur de la "Planète". Merci d'avoir répondu si vite. Quand est-il du générateur, je l'attend tjrs avec impatience.
Bon, je vous préviens, amarok2 est en plein construction, je l'ai installer et je le trouve très sympa mais pas du tout stable actuellement, mais ça promet. Si ça intéresse quelqu'un je peux mettre quelques Screenshoot d'Amarok Neon
Dernière modification par sylvainvh (Le 09/05/2008, à 17:15)
Hors ligne
sylvainvh
Re : Generateur de sources.list en Francais
Comme vous pouvez voir, c'est encore assez sommaire, j'ai quelques bugs mais ça avance, j'ai des MAJ toutes les 12H pour amarok. Il manque encore la fonction "Aléatoire". Je tiens à dire que Amarok2 fonctionne à part d'Amarok 1.4 et donc, vous pouvez tester Amarok2 tout en gardant Amarok 1.4
Hors ligne
|
I'm new to python and I'm writing a code to upload a file using urllib2 but I can't make it work.
Here's the code:
class Get(object):
handlers = list()
def __init__(self,url):
self.url = url
self.request = urllib2.Request(url)
self.request.add_header('User-Agent',"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13")
def auth(self,username,password):
pass_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
pass_mgr.add_password(None, self.url, username, password)
handler = urllib2.HTTPBasicAuthHandler(pass_mgr)
self._add_handler(handler)
def perform(self):
try:
opener = self._opener()
res = opener.open(self.request)
to_return = {
'code': res.code,
'contents': res.read(),
'url': res.geturl(),
'headers': dict(res.info())
}
except urllib2.URLError as e:
if hasattr(e, 'reason'):
print 'Error accessing the server.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print 'The server couldn\'t fulfill the request.'
print e
else:
return to_return
def _add_handler(self,handler):
self.handlers.append(handler)
def _opener(self):
return urllib2.build_opener(*self.handlers)
class Multipart(object):
def __init__(self,url):
super(Multipart,self).__init__(url)
self.data = list()
def perform(self):
b = choose_boundary()
tmp = "".join(map(lambda x: "--%s \r\n %s" % (b,x), self.data ))
tmp += "--%s--\r\n" % b
self.request.add_data(tmp)
content_type = 'multipart/form-data; boundary=%s' % b
self.request.add_unredirected_header('Content-Type', content_type)
#self.request.add_header("Content-Type","multipart/form-data, boundary=%s" % b)
return super(HTTP.Multipart,self).perform()
def set_data(self,data,file = None):
for i in data:
if file:
self.data.append(self._encode_file(i,**data[i]))
else:
self.data.append(self._encode_text(i,data[i]))
def _encode_text(self,key,value):
return "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n" % (key, value)
def _encode_file(self,key,path,filename=None,mime_type=None):
if not exists(path):
raise RuntimeError('%s not found' % path)
fname = filename or basename(path)
mime = mime_type or guess_type(path)[0] or 'application/octet-stream'
size = getsize(path)
content = ""
with open(path,'rb') as fobj:
content = fobj.read(size)
converted_text = "Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\n" % (key,fname)
converted_text += "Content-Transfer-Encoding: binary\r\n"
converted_text += "Content-Type: %s \r\n" % mime
converted_text += "Content-Length: %s \r\n" % size
converted_text += "\r\n %s \r\n" % content
return converted_text
|
Web Client Programming in Python
by Dave Warner
06/21/2000
Web client programming is a powerful technique for querying the Web. A web client is any program that retrieves data from a web server using the Hyper Text Transfer Protocol (the http in your URLs). A web browser is a client; so are web crawlers, programs that traverse the Web automatically to gather information. You can also use web clients to take advantage of services offered by others on the Web and add dynamic features to your own web site.
Web client programming belongs in any developer's toolbox. Perl aficionados have employed it for years. In Python, the process reaches even higher levels of convenience and flexibility. Three modules provide most of the functionality you will need: HTTPLIB, URLLIB, and a newer addition, XMLRPCLIB. In true Pythonesque fashion, each module builds upon its predecessor, providing a solid, well-designed base for your applications. We will cover the first two modules in this article, saving XMLRPCLIB for a later time.
For our examples, we will use Meerkat. If you are like me, you invest time tracking trends and developments in the open source community to give you a competitive edge. Meerkat is a tool that makes that task much easier. It is an open wire service that collects and collates an enormous amount of information on open source computing. Although its browser interface is flexible and customizable, using web client programming we can scan, extract, and even store this information off-line for later use. We will first access Meerkat using HTTPLIB interactively, and then move on to accessing Meerkat's Open API via URLLIB to create a customizable information-collecting tool.
HTTPLIB
HTTPLIB is a lightweight wrapper around the socket module. Of the three libraries I have mentioned, HTTPLIB provides the most control when accessing a web site. That control, however, comes at the cost of requiring more work to accomplish your task. The http protocol is "stateless," so it doesn't remember anything about your previous requests. You must construct a new HTTPLIB object to connect to the web site for each request. The requests form a conversation with the web server, mimicking a web browser. Let's connect to Meerkat using Rael Dornfest's Open API interactively and see what results we get. The conversation begins by building up a series of statements that first state what action you want to take, and then identify you to the web server:
>>> import httplib
>>> host = 'www.oreillynet.com'
>>> h = httplib.HTTP(host)
>>> h.putrequest('GET', '/meerkat/?_fl=minimal')
>>> h.putheader('Host', host)
>>> h.putheader('User-agent', 'python-httplib')
>>> h.endheaders()
>>>
The GET request tells the server which page you want to receive. The Host header tells it the domain name you are querying. Modern servers using HTTP 1.1 can host several domains at the same address. If you don't tell it which domain name you want, you will get a '302' redirection response as your return code. The User-agent header tells the server what kind of client you are so it knows what it can and cannot send you. This is all the information you need for the web server to process your request. Next you ask for the response:
>>> returncode, returnmsg, headers = h.getreply()
>>> if returncode == 200: #OK
... f = h.getfile()
... print f.read()
...
This will print out the current Meerkat page in the minimal flavor. The response header and content are returned separately, which aids in both troubleshooting and parsing any returned data. If you want to see the response headers use print headers.
HTTPLIB hides the mechanics of socket programming, and its use of a file object for buffering lets you use a familiar approach to manipulating the data. It is, however, best suited as a building block for more powerful web client applications, or for interactive conversations with a troubled web site. To aid in both areas, HTTPLIB has a useful debug capability. You access it by calling the method h.set_debuglevel(1) at any point after object initialization (the line h = httplib.HTTP(host) in our example). With the debug level set to 1, the module will echo requests and the results of any calls to getreply() to the screen.
The interactive nature of Python makes analyzing websites using HTTPLIB a joy. Familiarize yourself with this module and you will have a powerful, flexible tool for diagnosing web site problems. Take time to look at the source for HTTPLIB as well. With less than 200 lines of code, HTTPLIB is a quick and easy introduction to socket programming using Python.
Pages:
|
I want to implement hash table in python. Since the hashing basic idea is to store the value in the index i where i = hash_function(key), I need to be able to index a list/array to store the value. But since the size of lists in python expands with .append(), the hashList[i] statement will cause "List assignment index out of range".
Is there a twist to use lists with fixed size and indexing it normally? or shall I use a ctype array ?
Here's how the code might look like:
class Hash():
length = 1000
array = []
def __setitem__(self, key, value):
sum = 0
if key != None:
for letter in key:
sum = sum + ord(letter)
self.array[sum % self.length] = self.length
|
oliver2004
problème wifi avec portable HP nx6125...
Salut à tous, je viens d'installer sans trop de mal Kubuntu 7.10 sur mon portable HP Compaq nx6125 (j'ai de la chance il n'est pas tatoué...). Aparemment tout marche sur la machine... sauf le wifi... j'en ai pas besoin là maintenant mais j'en aurai sûrement besoin et de toutes façons, c'est agréable que tout fonctionne. La carte est fonctionnelle puisqu'aucun problème sous windows, mais rien à faire pour la faire marcher sous Kubuntu. J'ai suivi le tuto http://doc.ubuntu-fr.org/materiel/liste … paq_nx6125 mais rien n'y fait. Voici ce que j'obtiens avec les commandes indiquées sur le sujet épinglé.
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=7.10
DISTRIB_CODENAME=gutsy
DISTRIB_DESCRIPTION="Ubuntu 7.10"
olivier@kubuntu:~$ lsusb
Bus 003 Device 001: ID 0000:0000
Bus 002 Device 005: ID 05a4:9862 Ortek Technology, Inc.
Bus 002 Device 004: ID 05e3:1205 Genesys Logic, Inc. Afilias Optical Mouse H3003
Bus 002 Device 003: ID 05a4:9837 Ortek Technology, Inc.
Bus 002 Device 002: ID 08ff:2580 AuthenTec, Inc.
Bus 002 Device 001: ID 0000:0000
Bus 001 Device 001: ID 0000:0000
olivier@kubuntu:~$ lspci
00:00.0 Host bridge: ATI Technologies Inc RS480 Host Bridge (rev 01)
00:01.0 PCI bridge: ATI Technologies Inc RS480 PCI Bridge
00:04.0 PCI bridge: ATI Technologies Inc RS480 PCI Bridge
00:05.0 PCI bridge: ATI Technologies Inc RS480 PCI Bridge
00:13.0 USB Controller: ATI Technologies Inc IXP SB400 USB Host Controller
00:13.1 USB Controller: ATI Technologies Inc IXP SB400 USB Host Controller
00:13.2 USB Controller: ATI Technologies Inc IXP SB400 USB2 Host Controller
00:14.0 SMBus: ATI Technologies Inc IXP SB400 SMBus Controller (rev 11)
00:14.1 IDE interface: ATI Technologies Inc Standard Dual Channel PCI IDE Controller
00:14.3 ISA bridge: ATI Technologies Inc IXP SB400 PCI-ISA Bridge
00:14.4 PCI bridge: ATI Technologies Inc IXP SB400 PCI-PCI Bridge
00:14.5 Multimedia audio controller: ATI Technologies Inc IXP SB400 AC'97 Audio Controller (rev 02)
00:14.6 Modem: ATI Technologies Inc SB400 AC'97 Modem Controller (rev 02)
00:18.0 Host bridge: Advanced Micro Devices [AMD] K8 [Athlon64/Opteron] HyperTransport Technology Configuration
00:18.1 Host bridge: Advanced Micro Devices [AMD] K8 [Athlon64/Opteron] Address Map
00:18.2 Host bridge: Advanced Micro Devices [AMD] K8 [Athlon64/Opteron] DRAM Controller
00:18.3 Host bridge: Advanced Micro Devices [AMD] K8 [Athlon64/Opteron] Miscellaneous Control
01:05.0 VGA compatible controller: ATI Technologies Inc Radeon XPRESS 200M 5955 (PCIE)
02:01.0 Ethernet controller: Broadcom Corporation NetXtreme BCM5788 Gigabit Ethernet (rev 03)
02:02.0 Network controller: Broadcom Corporation BCM4318 [AirForce One 54g] 802.11g Wireless LAN Controller (rev 02)
02:04.0 CardBus bridge: Texas Instruments PCIxx21/x515 Cardbus Controller
02:04.2 FireWire (IEEE 1394): Texas Instruments OHCI Compliant IEEE 1394 Host Controller
02:04.3 Mass storage controller: Texas Instruments PCIxx21 Integrated FlashMedia Controller
02:04.4 Generic system peripheral [0805]: Texas Instruments PCI6411/6421/6611/6621/7411/7421/7611/7621 Secure Digital Controller
olivier@kubuntu:~$ sudo lshw -C network
[sudo] password for olivier:
*-network:0
description: Ethernet interface
product: NetXtreme BCM5788 Gigabit Ethernet
vendor: Broadcom Corporation
physical id: 1
bus info: pci@0000:02:01.0
logical name: eth0
version: 03
serial: 00:0f:b0:b9:7c:f6
size: 100MB/s
capacity: 1GB/s
width: 32 bits
clock: 66MHz
capabilities: pm vpd msi bus_master cap_list ethernet physical mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
configuration: autonegotiation=on broadcast=yes driver=tg3 driverversion=3.77 duplex=full firmware=5788-v3.26 ip=192.168.1.21 latency=64 link=yes mingnt=64 module=tg3 multicast=yes port=twisted pair speed=100MB/s
*-network:1 UNCLAIMED
description: Network controller
product: BCM4318 [AirForce One 54g] 802.11g Wireless LAN Controller
vendor: Broadcom Corporation
physical id: 2
bus info: pci@0000:02:02.0
version: 02
width: 32 bits
clock: 33MHz
capabilities: bus_master
configuration: latency=64
olivier@kubuntu:~$ lsmod
Module Size Used by
sg 41384 0
ipv6 317192 8
af_packet 28172 2
rfcomm 47656 2
l2cap 28672 11 rfcomm
bluetooth 63876 4 rfcomm,l2cap
radeon 129824 2
drm 106408 3 radeon
ppdev 11272 0
powernow_k8 16608 0
cpufreq_stats 8160 0
cpufreq_ondemand 10896 0
cpufreq_powersave 3072 0
cpufreq_userspace 6048 0
freq_table 6464 3 powernow_k8,cpufreq_stats,cpufreq_ondemand
cpufreq_conservative 9608 0
video 21140 0
battery 12424 0
sbs 21520 0
container 6400 0
button 10400 0
dock 12264 0
ac 7304 0
ndiswrapper 233632 0
sbp2 27144 0
lp 15048 0
joydev 13440 0
pcmcia 46232 0
snd_atiixp 24084 2
snd_seq_dummy 5380 0
tifm_7xx1 10112 0
tifm_core 13832 1 tifm_7xx1
sdhci 21004 0
mmc_core 33416 1 sdhci
pcspkr 4608 0
xpad 11400 0
parport_pc 41896 1
parport 44172 3 ppdev,lp,parport_pc
serio_raw 9092 0
psmouse 45596 0
k8temp 7680 0
snd_seq_oss 36864 0
yenta_socket 30220 1
rsrc_nonstatic 14208 1 yenta_socket
pcmcia_core 46628 3 pcmcia,yenta_socket,rsrc_nonstatic
snd_seq_midi 11008 0
snd_rawmidi 29824 1 snd_seq_midi
snd_atiixp_modem 19468 1
snd_ac97_codec 122200 2 snd_atiixp,snd_atiixp_modem
ac97_bus 4096 1 snd_ac97_codec
snd_seq_midi_event 9984 2 snd_seq_oss,snd_seq_midi
snd_pcm_oss 50048 0
snd_mixer_oss 20096 1 snd_pcm_oss
snd_seq 62496 6 snd_seq_dummy,snd_seq_oss,snd_seq_midi,snd_seq_midi_event
snd_seq_device 10260 5 snd_seq_dummy,snd_seq_oss,snd_seq_midi,snd_rawmidi,snd_seq
snd_pcm 94344 4 snd_atiixp,snd_atiixp_modem,snd_ac97_codec,snd_pcm_oss
snd_timer 27272 2 snd_seq,snd_pcm
snd 69288 17 snd_atiixp,snd_seq_oss,snd_rawmidi,snd_atiixp_modem,snd_ac97_codec,snd_pcm_oss,snd_mixer_oss,snd_seq,snd_seq_device,snd_pcm,snd_timer
soundcore 10272 1 snd
snd_page_alloc 12560 3 snd_atiixp,snd_atiixp_modem,snd_pcm
i2c_piix4 11020 0
i2c_core 30208 1 i2c_piix4
shpchp 38300 0
pci_hotplug 36612 1 shpchp
evdev 13056 7
ext3 146576 2
jbd 69360 1 ext3
mbcache 11272 1 ext3
ide_cd 35488 0
cdrom 41768 1 ide_cd
ide_disk 20352 6
ata_generic 9988 0
libata 138928 1 ata_generic
scsi_mod 172856 3 sg,sbp2,libata
usbhid 32576 0
hid 33408 1 usbhid
ohci1394 38984 0
ieee1394 109528 2 sbp2,ohci1394
tg3 118788 0
atiixp 7824 0 [permanent]
ide_core 141200 3 ide_cd,ide_disk,atiixp
ehci_hcd 40076 0
ohci_hcd 25092 0
usbcore 161584 6 ndiswrapper,xpad,usbhid,ehci_hcd,ohci_hcd
thermal 16528 0
processor 36232 2 powernow_k8,thermal
fan 6920 0
fuse 52528 5
apparmor 47008 0
commoncap 9472 1 apparmor
olivier@kubuntu:~$ iwconfig
lo no wireless extensions.
eth0 no wireless extensions.
olivier@kubuntu:~$ ifconfig
eth0 Lien encap:Ethernet HWaddr 00:0F:B0:B9:7C:F6
inet adr:192.168.1.21 Bcast:192.168.1.255 Masque:255.255.255.0
adr inet6: fe80::20f:b0ff:feb9:7cf6/64 Scope:Lien
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
Packets reçus:252387 erreurs:0 :0 overruns:0 frame:0
TX packets:177429 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 lg file transmission:1000
Octets reçus:275552682 (262.7 MB) Octets transmis:18439639 (17.5 MB)
Interruption:10
lo Lien encap:Boucle locale
inet adr:127.0.0.1 Masque:255.0.0.0
adr inet6: ::1/128 Scope:Hà´te
UP LOOPBACK RUNNING MTU:16436 Metric:1
Packets reçus:20 erreurs:0 :0 overruns:0 frame:0
TX packets:20 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 lg file transmission:0
Octets reçus:1620 (1.5 KB) Octets transmis:1620 (1.5 KB)
olivier@kubuntu:~$ iwlist scan
lo Interface doesn't support scanning.
eth0 Interface doesn't support scanning.
olivier@kubuntu:~$ uname -r -m
2.6.22-14-generic x86_64
olivier@kubuntu:~$ cat /etc/network/interfaces
auto lo
iface lo inet loopback
Donc apparemment, si j'ai bien compris, le driver est bien installé mais la carte pas reconnue?
Si quelqu'un pouvais me donner une piste??
Merci d'avance :)
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
willy78
Re : problème wifi avec portable HP nx6125...
lspci:
00:0b.0 Network controller: Broadcom Corporation BCM4318 [AirForce One 54g] 802.11g Wireless LAN Controller (rev 02)
Tous ça avec une connection active
On télecharge le driver adequat (bcmwl5):
cd
wget http://dlsvr03.asus.com/pub/ASUS/wireless/WL-100g-03/Driverv3100640.zip
unzip Driverv3100640.zip
Ensuite on installe ndiswrapper:
sudo apt-get install ndiswrapper-utils-1.9
on charge le driver dans ndiswrapper
sudo ndiswrapper -i ~/Driver/WinXP/bcmwl5.inf
et on verifie s'il est bien chargé (avant de faire quoi que ce soi d'autres)
ndiswrapper -l #C'est un petit L
si il affiche un truc qui ressemble à ça:
bcmwl5 : driver installed
device (14E4:4318) present (alternate driver: bcm43xx)
Tu peux continuer!
pour décharger le module chargé automatiquement par Gutsy
sudo rmmod bcm43xx
pour charger ndiswrapper
sudo ndiswrapper -m
sudo modprobe ndiswrapper
Blacklister le module chargé automatiquement par gutsy
echo 'blacklist bcm43xx' | sudo tee -a /etc/modprobe.d/blacklist
Mettre ndiswrapper dans la liste des modules chargés au démarrage:
echo 'ndiswrapper' | sudo tee -a /etc/modules
modif du fichier interfaces
echo -e 'auto lo\niface lo inet loopback\n' | sudo tee /etc/network/interfaces
et connecte toi avec network-manager (2 tv en haut a droite à coté de l'heure)!
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
Salut, merci pour la réponse.:)
Voici où j'en suis, ça bloque quelque part:
olivier@kubuntu:~$ wget http://dlsvr03.asus.com/pub/ASUS/wireless/WL-100g-03/Driverv3100640.zip
--10:49:00-- http://dlsvr03.asus.com/pub/ASUS/wireless/WL-100g-03/Driverv3100640.zip
=> `Driverv3100640.zip'
Résolution de dlsvr03.asus.com... 122.213.112.90
Connexion vers dlsvr03.asus.com|122.213.112.90|:80... connecté.
requête HTTP transmise, en attente de la réponse... 200 OK
Longueur: 926 968 (905K) [application/x-zip-compressed]
100%[====================================>] 926 968 141.47K/s ETA 00:00
10:49:07 (141.27 KB/s) - « Driverv3100640.zip » sauvegardé [926968/926968]
--> Téléchargement du fichier, ok
olivier@kubuntu:~$ unzip Driverv3100640.zip
Archive: Driverv3100640.zip
creating: Driver/
creating: Driver/WinXP/
inflating: Driver/WinXP/bcm43xx.cat
inflating: Driver/WinXP/bcmwl5.inf
inflating: Driver/WinXP/bcmwl5.sys
creating: Driver/WinME/
extracting: Driver/WinME/bcm43xxa.cat
inflating: Driver/WinME/bcmwl5.sys
inflating: Driver/WinME/bcmwl5a.inf
creating: Driver/Win98/
extracting: Driver/Win98/bcm43xxa.cat
inflating: Driver/Win98/bcmwl5.sys
inflating: Driver/Win98/bcmwl5a.inf
creating: Driver/Win2K/
inflating: Driver/Win2K/bcm43xx.cat
inflating: Driver/Win2K/bcmwl5.inf
inflating: Driver/Win2K/bcmwl5.sys
--> Dezipage du fichier ok.
olivier@kubuntu:~$ sudo apt-get install ndiswrapper-utils-1.9
[sudo] password for olivier:
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
ndiswrapper-utils-1.9 est déjà la plus récente version disponible.
Les paquets suivants ont été installés automatiquement et ne sont plus nécessaires :
python-cairo python-gtk2 python-numeric
Veuillez utiliser « apt-get autoremove » pour les supprimer.
0 mis à jour, 0 nouvellement installés, 0 à enlever et 0 non mis à jour.
--> Installation de ndiswrapper-utils-1.9 , ok.
olivier@kubuntu:~$ sudo ndiswrapper -i ~/Driver/WinXP/bcmwl5.inf
installing bcmwl5 ...
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
olivier@kubuntu:~$ ndiswrapper -l
bcmwl5 : driver installed
device (14E4:4318) present (alternate driver: bcm43xx)
bcmwl5a : driver installed
device (14E4:4318) present (alternate driver: bcm43xx)
--> Chargement du driver et vérification ok.
olivier@kubuntu:~$ sudo rmmod bcm43xx
ERROR: Module bcm43xx does not exist in /proc/modules #### ERREUR
En fait j'ai éditer le fichier /proc/modules avec kate et il est vide, il n'y a rien dedans.
olivier@kubuntu:~$ sudo ndiswrapper -m
module configuration already contains alias directive ### Il y a déjà une directive de configuration
olivier@kubuntu:~$ sudo modprobe ndiswrapper
olivier@kubuntu:~$ echo 'blacklist bcm43xx' | sudo tee -a /etc/modprobe.d/blacklist
blacklist bcm43xx
--> Ok, le bcm43xx est bien blacklisté....
Le fichier /proc/modules reste vide, rien dessus. C'est normal?
J'ai donc essayé de me connecter à travers KNetworkManager mais l'onglet Network reste inactif.:/
Dernière modification par oliver2004 (Le 03/02/2008, à 13:02)
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
willy78
Re : problème wifi avec portable HP nx6125...
il y a un driver de trop d'o๠problème!
sudo ndiswrapper -e bcmwl5a
reboot et donnes ces retour
sudo lshw -C network
iwlist scanning
Pour proc/module aucune importance! si bcm43xx est déjà blacklister suite a ton essaie avec le driver bcmwl5a normal qu'il ne soit pas charger et c'est tant mieux!
Dernière modification par willy78 (Le 03/02/2008, à 13:43)
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
Voici les retours
[sudo] password for olivier:
*-network:0
description: Ethernet interface
product: NetXtreme BCM5788 Gigabit Ethernet
vendor: Broadcom Corporation
physical id: 1
bus info: pci@0000:02:01.0
logical name: eth0
version: 03
serial: 00:0f:b0:b9:7c:f6
size: 100MB/s
capacity: 1GB/s
width: 32 bits
clock: 66MHz
capabilities: pm vpd msi bus_master cap_list ethernet physical mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
configuration: autonegotiation=on broadcast=yes driver=tg3 driverversion=3.77 duplex=full firmware=5788-v3.26 ip=192.168.1.21 latency=64 link=yes mingnt=64 module=tg3 multicast=yes port=twisted pair speed=100MB/s
*-network:1 UNCLAIMED
description: Network controller
product: BCM4318 [AirForce One 54g] 802.11g Wireless LAN Controller
vendor: Broadcom Corporation
physical id: 2
bus info: pci@0000:02:02.0
version: 02
width: 32 bits
clock: 33MHz
capabilities: bus_master
configuration: latency=64
olivier@kubuntu:~$ iwlist scanning
lo Interface doesn't support scanning.
eth0 Interface doesn't support scanning.
Apparemment ça ne va toujours pas
Uhm, je vois ceci: width: 32 bits, je suis en 64 bits, ne serait-ce pas ça l'erreur?
Dernière modification par oliver2004 (Le 03/02/2008, à 13:53)
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
willy78
Re : problème wifi avec portable HP nx6125...
sudo modprobe -r ndiswrapper
sudo modprobe ndiswrapper
et retour de
sudo lshw -C network
iwlist scanning
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
olivier@kubuntu:~$ sudo modprobe -r ndiswrapper
olivier@kubuntu:~$ sudo modprobe ndiswrapper
olivier@kubuntu:~$ sudo lshw -C network
*-network:0
description: Ethernet interface
product: NetXtreme BCM5788 Gigabit Ethernet
vendor: Broadcom Corporation
physical id: 1
bus info: pci@0000:02:01.0
logical name: eth0
version: 03
serial: 00:0f:b0:b9:7c:f6
size: 100MB/s
capacity: 1GB/s
width: 32 bits
clock: 66MHz
capabilities: pm vpd msi bus_master cap_list ethernet physical mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
configuration: autonegotiation=on broadcast=yes driver=tg3 driverversion=3.77 duplex=full firmware=5788-v3.26 ip=192.168.1.21 latency=64 link=yes mingnt=64 module=tg3 multicast=yes port=twisted pair speed=100MB/s
*-network:1 UNCLAIMED
description: Network controller
product: BCM4318 [AirForce One 54g] 802.11g Wireless LAN Controller
vendor: Broadcom Corporation
physical id: 2
bus info: pci@0000:02:02.0
version: 02
width: 32 bits
clock: 33MHz
capabilities: bus_master
configuration: latency=64
olivier@kubuntu:~$ iwlist scanning
lo Interface doesn't support scanning.
eth0 Interface doesn't support scanning.
Au mème point je pense.
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
willy78
Re : problème wifi avec portable HP nx6125...
§Mince j'avais pas vu tu es en 64 bits donc c'est mort pour ndiswrapper, dommage c'est la meilleur soluce!
il faut passer par les driver proprio et donc virer bcm43xx du fichier blacklist:
sudo gedit /etc/modprobe.d/blacklist
et vire toutes les lignes avec
blacklist bcm43xx
ensuite va dans le menu
Système > Administration > Gestionnaire de pilotes propriétaires
et tu coches le pilotes de ta carte (il faut quand même un connection ethernet!)
si ça marche pas passe en 32 bits (le 64 bits c'est pas du tout au point et pas que sous linux il faut attendre quelque années avant de prendre cette solution!)
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
Ah zut... bon, donc il va sans doute que je refasse une install en 32 bits? bon, c'est con mais tant pis, moi qui avait réussi à configurer mon système... 32 bits est sans doute plus stable de toutes façons. En attendant, j'ai essayé d'activer le pilote du modem mais le message est le suivant: "les sources logicielles pour le paquet sl-modem-daemon ne sont pas activées"
O๠puis-je trouver ces sources pour les activer?
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
willy78
Re : problème wifi avec portable HP nx6125...
je sais pas de quelle modem tu parles
mais fais ça pour voir on ne sais jamais
sudo apt-get install sl-modem-daemon
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
Ben c'est le seul truc qui reste à installer dans les pilotes propriétaires. Donc j'ai supposé que c'était ça mais après quelques recherches, je vois que c'est le modem fax... donc rien à voir avec le wifi...
Je pense donc passer à 32 bits... le téléchargement est d'ailleurs déjà terminé, mais pas de cd vierge à portée de main...
Je pensais que c'était mieux de passer à 64 bits pour tirer parti de toutes les ressources du système, mais si c'est pas encore au point autant rester à 32 bits... :)
Je recommencerai l'install du wifi après, je tiens au courant merci en tout cas pour ton aide.
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
willy78
Re : problème wifi avec portable HP nx6125...
ok salut et a plus sur ce topic au cas ou
Pour le 64 bits il faut avoir du bol avec le matériel sinon c'est la croix et la bannière.
En plus les logiciel ne sont pas encore vraiment porter en 64 bits juste du code 32 bits compiler en 64 bits donc coté optimisation ça sert a rien au mieux 4 a 10 % de mieux!
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
Vu, oui, effectivement, ça ne sert pas encore à grand chose donc, en plus si ça bloque sur certains trucs... je passe donc à 32 bits, on attendra pour me 64 bits... Merci willy78
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
Salut à nouveau,:)
Je suis donc passé à la distribution en 32bits et j'ai refait les manip pour le carte wifi. Aucune erreur n'apparait, je peux maintenant allumer et éteindre le bouton du wifi sur le portable... auparavant, celui-ci restait allumé ou éteint sans changement...
Par contre le wifi ne marche pas mieux... l'onglet Network dans KNetwork Manager n'est toujours pas activé.
Ai-je raté quelque chose?
olivier@kubuntu:~$ sudo lshw -C network
*-network:0
description: Ethernet interface
product: NetXtreme BCM5788 Gigabit Ethernet
vendor: Broadcom Corporation
physical id: 1
bus info: pci@0000:02:01.0
logical name: eth0
version: 03
serial: 00:0f:b0:b9:7c:f6
size: 100MB/s
capacity: 1GB/s
width: 32 bits
clock: 66MHz
capabilities: pm vpd msi bus_master cap_list ethernet physical mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
configuration: autonegotiation=on broadcast=yes driver=tg3 driverversion=3.77 duplex=full firmware=5788-v3.26 ip=192.168.1.21 latency=64 link=yes mingnt=64 module=tg3 multicast=yes port=twisted pair speed=100MB/s
*-network:1
description: Wireless interface
product: BCM4318 [AirForce One 54g] 802.11g Wireless LAN Controller
vendor: Broadcom Corporation
physical id: 2
bus info: pci@0000:02:02.0
logical name: eth1
version: 02
serial: 00:14:a5:2a:02:4d
width: 32 bits
clock: 33MHz
capabilities: bus_master ethernet physical wireless
configuration: broadcast=yes driver=ndiswrapper+bcmwl5 driverversion=1.45+ASUS,02/11/2005, 3.100.64.0 latency=64 link=no module=ndiswrapper multicast=yes wireless=IEEE 802.11g
olivier@kubuntu:~$ iwlist scanning
lo Interface doesn't support scanning.
eth0 Interface doesn't support scanning.
eth1 Scan completed :
Cell 01 - Address: 00:1A:6B:C1:51:D1
ESSID:"Livebox-6547"
Protocol:IEEE 802.11g
Mode:Managed
Frequency:2.457 GHz (Channel 10)
Quality:78/100 Signal level:-46 dBm Noise level:-96 dBm
Encryption key:on
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
9 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s; 36 Mb/s
48 Mb/s; 54 Mb/s
Extra:bcn_int=100
Extra:atim=0
Cell 02 - Address: 00:14:A4:6C:AD:EE
ESSID:"WANADOO-B330"
Protocol:IEEE 802.11g
Mode:Managed
Frequency:2.412 GHz (Channel 1)
Quality:40/100 Signal level:-70 dBm Noise level:-96 dBm
Encryption key:on
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 18 Mb/s
24 Mb/s; 36 Mb/s; 54 Mb/s; 6 Mb/s; 9 Mb/s
12 Mb/s; 48 Mb/s
Extra:bcn_int=100
Extra:atim=0
Cell 03 - Address: 00:11:24:62:10:1D
ESSID:"Cabinet Bonnel"
Protocol:IEEE 802.11g
Mode:Managed
Frequency:2.437 GHz (Channel 6)
Quality:60/100 Signal level:-57 dBm Noise level:-96 dBm
Encryption key:on
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
9 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s; 36 Mb/s
48 Mb/s; 54 Mb/s
Extra:bcn_int=100
Extra:atim=0
IE: WPA Version 1
Group Cipher : WEP-40
Pairwise Ciphers (1) : WEP-40
Authentication Suites (1) : PSK
Il y a donc du progrès mais ça manque encore... Auriez vous une piste?:P
Dernière modification par oliver2004 (Le 06/02/2008, à 13:56)
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
willy78
Re : problème wifi avec portable HP nx6125...
Ah si là ça marche il scan les reseaux!
Cela a-t-il été fait?
Blacklister le module chargé automatiquement par gutsy
echo 'blacklist bcm43xx' | sudo tee -a /etc/modprobe.d/blacklist
Mettre ndiswrapper dans la liste des modules chargés au démarrage:
echo 'ndiswrapper' | sudo tee -a /etc/modules
modif du fichier interfaces
echo -e 'auto lo\niface lo inet loopback\n' | sudo tee /etc/network/interfaces
et connecte toi avec network-manager (2 tv en haut a droite à coté de l'heure)!
Dernière modification par willy78 (Le 06/02/2008, à 13:59)
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
Salut, oui, tout a été fait.
En fait je crois avoir fait une bourde... j'ai installé bêtement wilan, ce qui apparemment a désinstallé knetwormanager... j'ai desintallé à nouveau wilan et réinstallé knetworkmanager... il est donc installé, j'ai activé eth1, qui correspond à la wifi... donc quand j'ouvre maintenant knetworkmanager ben plus aucun onglet est actif à par le premier... alors qu'avant tous étaient actifs sauf celui de la wifi... Dans Device il me met: No active device... uhmmm, pas facile.
Re testage:
*-network:0
description: Ethernet interface
product: NetXtreme BCM5788 Gigabit Ethernet
vendor: Broadcom Corporation
physical id: 1
bus info: pci@0000:02:01.0
logical name: eth0
version: 03
serial: 00:0f:b0:b9:7c:f6
size: 100MB/s
capacity: 1GB/s
width: 32 bits
clock: 66MHz
capabilities: pm vpd msi bus_master cap_list ethernet physical mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
configuration: autonegotiation=on broadcast=yes driver=tg3 driverversion=3.77 duplex=full firmware=5788-v3.26 ip=192.168.1.21 latency=64 link=yes mingnt=64 module=tg3 multicast=yes port=twisted pair speed=100MB/s
*-network:1
description: Wireless interface
product: BCM4318 [AirForce One 54g] 802.11g Wireless LAN Controller
vendor: Broadcom Corporation
physical id: 2
bus info: pci@0000:02:02.0
logical name: eth1
version: 02
serial: 00:14:a5:2a:02:4d
width: 32 bits
clock: 33MHz
capabilities: bus_master ethernet physical wireless
configuration: broadcast=yes driver=ndiswrapper+bcmwl5 driverversion=1.45+ASUS,02/11/2005, 3.100.64.0 latency=64 link=no module=ndiswrapper multicast=yes wireless=IEEE 802.11g
olivier@kubuntu:~$ iwlist scanning
lo Interface doesn't support scanning.
eth0 Interface doesn't support scanning.
eth1 Scan completed :
Cell 01 - Address: 00:1A:6B:C1:51:D1
ESSID:"Livebox-6547"
Protocol:IEEE 802.11g
Mode:Managed
Frequency:2.457 GHz (Channel 10)
Quality:81/100 Signal level:-44 dBm Noise level:-96 dBm
Encryption key:on
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
9 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s; 36 Mb/s
48 Mb/s; 54 Mb/s
Extra:bcn_int=100
Extra:atim=0
Cell 02 - Address: 00:14:A4:6C:AD:EE
ESSID:"WANADOO-B330"
Protocol:IEEE 802.11g
Mode:Managed
Frequency:2.412 GHz (Channel 1)
Quality:37/100 Signal level:-72 dBm Noise level:-96 dBm
Encryption key:on
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 18 Mb/s
24 Mb/s; 36 Mb/s; 54 Mb/s; 6 Mb/s; 9 Mb/s
12 Mb/s; 48 Mb/s
Extra:bcn_int=100
Extra:atim=0
Cell 03 - Address: 00:11:24:62:10:1D
ESSID:"Cabinet Bonnel"
Protocol:IEEE 802.11g
Mode:Managed
Frequency:2.437 GHz (Channel 6)
Quality:64/100 Signal level:-55 dBm Noise level:-96 dBm
Encryption key:on
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
9 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s; 36 Mb/s
48 Mb/s; 54 Mb/s
Extra:bcn_int=100
Extra:atim=0
IE: WPA Version 1
Group Cipher : WEP-40
Pairwise Ciphers (1) : WEP-40
Authentication Suites (1) : PSK
Cell 04 - Address: 00:13:46:6F:C7:84
ESSID:"FPH"
Protocol:IEEE 802.11g
Mode:Managed
Frequency:2.457 GHz (Channel 10)
Quality:6/100 Signal level:-92 dBm Noise level:-96 dBm
Encryption key:on
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
12 Mb/s; 24 Mb/s; 36 Mb/s; 9 Mb/s; 18 Mb/s
48 Mb/s; 54 Mb/s
Extra:bcn_int=100
Extra:atim=0
En fait si je comprends bien, les différentes "Cell", c'est les différents réseaux wifi qu'il y a dans le coin?? ma live box en tout cas est bien détectée.
Ou bien alors il faut faire une manip avec la livebox?
Dernière modification par oliver2004 (Le 06/02/2008, à 15:09)
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
Up?
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
willy78
Re : problème wifi avec portable HP nx6125...
Tu dit j'ai activé eth1, c'est a dire?
bon sinon enligne de commande fais ça:
sudo iwconfig eth1 essid Livebox-6547
sudo iwconfig eth1 key Ta_clé_secrete
sudo dhclient eth1
donnes le retour de la dernière commande!
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
Salut willy78
Par "activer eth1" c'est dans knetwork manager, configuration manuelle, interfaces réseaux. eth1 était desactivé, donc je me suis imaginé que ça pouvait pas marcher comme ça... j'ai donc activé l'interface mais sans plus de résultats.
Voila le retour de la dernière commande:
olivier@kubuntu:~$ sudo dhclient eth1
Internet Systems Consortium DHCP Client V3.0.5
Copyright 2004-2006 Internet Systems Consortium.
All rights reserved.
For info, please visit http://www.isc.org/sw/dhcp/
Listening on LPF/eth1/00:14:a5:2a:02:4d
Sending on LPF/eth1/00:14:a5:2a:02:4d
Sending on Socket/fallback
DHCPDISCOVER on eth1 to 255.255.255.255 port 67 interval 5
DHCPOFFER from 192.168.1.1
DHCPREQUEST on eth1 to 255.255.255.255 port 67
DHCPACK from 192.168.1.1
bound to 192.168.1.10 -- renewal in 249034 seconds.
Il a l'air d'y y avoir une réponse par contre... je n'ai toujours pas internet en wifi...
Dernière modification par oliver2004 (Le 07/02/2008, à 10:33)
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
willy78
Re : problème wifi avec portable HP nx6125...
c'est exactement ce qu'il ne faut pas faire (ne pas utiliser configuration manuel)
C'est incompatible avec knetworkmanager le fichier /etc/network/interfaces ne doit comporter que ça:
auto lo
iface lo inet loopback
La configuration manuel écrit des données dans ce fichier et donc knetworkmanager ne peux plus gérer la connection!
bound to 192.168.1.10 -- renewal in 249034 seconds.
Ceci veut dire que tu es connecter! mais en manuel donc ça marche
cette commande:
echo -e 'auto lo\niface lo inet loopback\n' | sudo tee /etc/network/interfaces
rétabli ce qu'il faut dans le fichier interfaces
après cette commande, attends 1 mn, ensuite tu cliques gauche sur knetworkmanager (sous kde, je crois qu'il est en bas a droite a coté de l'heure) et tu cliques sur ton reseau qui devrais apparaitre!
Hors ligne
|
I just updated Python to 2.6.4 on my Mac. I installed from the dmg package.
The binary did not seem to correctly set my Python path, so I added '/usr/local/lib/python2.6/site-packages' in .bash_profile
>>> pprint.pprint(sys.path)
['',
'/Users/Bryan/work/django-trunk',
'/usr/local/lib/python2.6/site-packages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages']
Apparently that is not all the required paths because I can't run iPython.
$ ipython
Traceback (most recent call last):
File "/usr/local/bin/ipython", line 5, in <module>
from pkg_resources import load_entry_point
ImportError: No module named `pkg_resources`
I've done Google searches and I can't really figure out how to install pkg_resources or make sure it's on the path.
What do I need to do to fix this?
|
Having briefly looked at Haskell recently I wondered whether anybody could give a brief, succinct, practical explanation as to what a monad essentially is? I have found most explanations I've come across to be fairly inaccessible and lacking in practical detail, so could somebody here help me?
Having briefly looked at Haskell recently I wondered whether anybody could give a
First: The term
You ask for practical examples:
[x*2 | x<-[1..10], odd x]
This expression returns the doubles of all odd numbers in the range from 1 to 10. Very useful!
It turns out this is really just syntactic sugar for some operations within the List monad. The same list comprehension can be written as:
do
x <- [1..10]
if odd x
then [x * 2]
else []
Or even:
[1..10] >>= (\x -> if odd x then [x*2] else [])
do
putStrLn "What is your name?"
name <- getLine
putStrLn ("Welcome, " ++ name ++ "!")
Both examples uses monads, aka computation builders. The common theme is that the monad
It turns out the pattern of
Another example is exceptions: Using the
Both the list-comprehension syntax and the do-notation are syntactic sugar for chaining operations using the
This is a very simple parser which parses either a quoted string or a number:
parseExpr = parseString <|> parseNumber
parseString = do
char '"'
x <- many (noneOf "\"")
char '"'
return (StringValue x)
parseNumber = do
num <- many1 digit
return (NumberValue (read num))
The operations
The above examples are in Haskell, but it turns out F# also supports monads. This example is stolen from Don Syme:
let AsyncHttp(url:string) =
async { let req = WebRequest.Create(url)
let! rsp = req.GetResponseAsync()
use stream = rsp.GetResponseStream()
use reader = new System.IO.StreamReader(stream)
return reader.ReadToEnd() }
This method fetches a web page. The punch line is the use of
In most other languages you would have to explicitly create a separate function for the lines that handle the response. The
So how can a monad do all these fancy control-flow thing? What actually happens in a do-block (or a
As an example, this is the expanded version of the IO-code from example 2:
putStrLn "What is your name?"
>>= (\_ -> getLine)
>>= (\name -> putStrLn ("Welcome, " ++ name ++ "!"))
This is uglier, but it's also more obvious what is actually going on. The
Note that
The simplest possible implementation of
There is some additional cleverness in how the values are passed from one operation to the next, but this requires a deeper explanation of the Haskell type system.
In Haskell-terms a monad is a parameterized type which is an instance of the Monad type class, which defines >>= along with a few other operators. In layman's terms, a monad is just a type for which the
In itself
For many Haskell-learners, monads are an obstacle they hit like a brick wall. It's not that monads themselves are complex, but that the implementation relies on many other advanced Haskell features like parameterized types, type classes, and so on. The problem is that Haskell IO is based on monads, and IO is probably one of the first things you want to understand when learning a new language - after all, its not much fun to create programs which don't produce any output. I have no immediate solution for this chicken-and-egg problem, except treating IO like "magic happens here" until you have enough experience with other parts of language. Sorry.
I doubt anybody will ever scroll this far down, but I'm going to give it a go anyway...
OK, explaining "what is a monad" is a bit like saying "what is a number?" We use numbers all the time. But imagine you met someone who didn't know anything about numbers. How the
What is a monad? The short answer: It's a specific way of chaining operations together.
In essence, you're writing execution steps and linking them together with the "bind function". (In Haskell, it's named
So the bind function is like a semicolon; it separates the steps in a process. The bind function's job is to take the output from the previous step, and feed it into the next step.
That doesn't sound too hard, right? But there is
Well, the bind function
(A monad that does
Basically, each monad has its own implementation of the bind function. And you can write a bind function such that it does hoopy things between execution steps. For example:
All of this and more is possible with monads. Of course, all of this is also perfectly possible
Actually, contrary to common understanding of Monads, they have nothing to do with state. Monads are simply a way to wrapping things and provide methods to do operations on the wrapped stuff without unwrapping it.
For example, you can create a type to wrap another one, in Haskell:
data Wrapped a = Wrap a
To wrap stuff we define
return :: a -> Wrapped a
return x = Wrap x
To perform operations without unwrapping, say you have a function
fmap :: (a -> b) -> (Wrapped a -> Wrapped b)
fmap f (Wrap x) = Wrap (f x)
That's about it there is to understand. However, it turns out that there is a more general function to do this
bind :: (a -> Wrapped b) -> (Wrapped a -> Wrapped b)
bind f (Wrap x) = f x
The cool thing is that this turns out to be such a general pattern that it pops up all over the place, encapsulating state in a pure way is only one of them.
For a good article on how monads can be used to introduce functional dependencies and thus control order of evaluation, like it is used in Haskell's IO monad, check out IO Inside.
As for understanding monads, don't worry too much about it. Read about them what you find interesting and don't worry if you don't understand right away. Then just diving in a language like Haskell is the way to go. Monads are one of these things where understanding trickles into your brain by practice, one day you just suddenly realize you understand them.
A monad is a datatype that has two operations:
In Haskell notation, the monad interface is written
class Monad m where
return :: a -> m a
(>>=) :: forall a b . m a -> (a -> m b) -> m b
These operations are supposed to obey certain "laws", but that's not terrifically important: the "laws" just codify the way sensible implementations of the operations ought to behave (basically, that
Monads are not just about state and IO: they abstract a common pattern of computation that includes working with state, IO, exceptions, and non-determinism. Probably the simplest monads to understand are lists and option types:
instance Monad [ ] where
[] >>= k = []
(x:xs) >>= k = k x ++ (xs >>= k)
return x = [x]
instance Monad Maybe where
Just x >>= k = k x
Nothing >>= k = Nothing
return x = Just x
where
You really have to play around writing some non-trivial Haskell code to appreciate what monads are about and why they are useful.
You should first understand what a functor is. Before that, understand higher-order functions.
A
A
map (\x -> x) x == x
map (p . q) x == map p (map q x)
For example, a type constructor called
A
T (T a) -> T a, and unit (sometimes called return, fork, or pure) of type a -> T a. For lists in Haskell:
Why is that useful? Because you could, for example,
You can write a function that does
A monad has to satisfy certain laws, namely that
This video is one of the clearest and most concise explanation of monads that I have come across:
A good motivation to Monads is sigfpe(Dan Piponi)'s You Could Have Invented Monads! (And Maybe You Already Have). There are a LOT of other monad tutorials, many of which misguidedly try to explain monads in "simple terms" using various analogies: this is the monad tutorial fallacy; avoid them.
As DR MacIver says in Tell us why your language sucks:
You say you understand the Maybe monad? Good, you're on your way. Just start using other monads and sooner or later you'll understand what monads are in general.
[If you are mathematically oriented, you might want to ignore the dozens of tutorials and learn the definition, or follow lectures in category theory :) The main part of the definition is that a Monad M involves a "type constructor" that defines for each existing type "T" a new type "M T", and some ways for going back and forth between "regular" types and "M" types.]
Also, surprisingly enough, one of the best introductions to monads is actually one of the early academic papers introducing monads, Philip Wadler's Monads for functional programming. It actually has practical,
[Disclaimer: I am still trying to fully grok monads. The following is just what I have understood so far. If itâs wrong, hopefully someone knowledgeable will call me on the carpet.]
Arnar wrote:
Thatâs precisely it. The idea goes like this:
But the example is just what happens for
Basically,
And that is why people find monads so confusing: because they are such a generic concept. To ask what makes something a monad is similarly vague as to ask what makes something a pattern.
But think of the implications of having syntactic support in the language for the idea of a pattern: instead of having to read the
So that is why people who
A monad is, effectively, a form of "type operator". It will do three things. First it will "wrap" ( or otherwise convert) a value of one type into another type (typically called a "monadic type"). Secondly it will make all the operations ( or functions ) available on the underlying type available on the monadic type. Finally it will provide support for combining its self with another monad to produce a composite monad.
The "maybe monad" is essentially the equivalent of "nullable types" in VB / C#. It takes a non nullable type "T" and converts it into a "Nullable<T>", and then defines what all the binary operators mean on a Nullable<T>.
Side effects are represented simillarly. A structure is created that holds descriptions of side effects along side a function's return value. The "lifted" operations then copy around side effects as values are passed between functions.
The are called "monads" rather than the easier to grasp name of "type operators" for several reasons:
As soon as you understand Monads, you will understand that this is a Monad, too.
xkcd:248
{{alt:
After much striving, I think I finally understand the monad. After rereading my own lengthy critique of the overwhelmingly top voted answer, I will offer this explanation.
There are three questions that need to be answered to understand monads:
Why do you need a monad? What is a monad? How is a monad implemented?
As I noted in my original comments, too many monad explanations get caught up in question number 3, without, and before really adequately covering question 2, or question 1.
Why do you need a monad?
Pure functional languages like Haskell are different from imperative languages like C, or Java in that, a pure functional program is not necessarily executed in a specific order, one step at a time. A Haskell program is more akin to a mathematical function, in which you may solve the "equation" in any number of potential orders. This confers a number of benefits, among which is that it eliminates the possibility of certain kinds of bugs, particularly those relating to things like "state".
However, there are certain problems that are not so straightforward to solve with this style of programming. Some things, like console programming, and file i/o, need things to happen in a particular order, or need to maintain state. One way to deal with this problem is to create a kind of object that represents the state of a computation, and a series of functions that take a state object as input, and return a new modified state object.
so let's create a hypothetical "state" value, that represents the state of a console screen. exactly how this value is constructed is not important, but let's say it's an array of byte length ascii characters that represents what is currently visible on the screen, and an array that represents the last line of input entered by the user, in pseudocode. We've defined some functions that take console state, modify it, and return a new console state.
consolestate MyConsole = new consolestate;
so to do console programming, but in a pure functional manner, you would need to nest a lot of function calls inside eachother.
consolestate FinalConsole = print(input(print(myconsole, "Hello, what's your name?")),"hello, %inputbuffer%!");
Programming in this way keeps the "pure" functional style, while forcing changes to the console to happen in a particular order. But, we'll probably want to do more than just a few operations at a time like in the above example. Nesting functions in that way will start to become ungainly. What we want, is code that does essentially the same thing as above, but is written a bit more like this:
consolestate FinalConsole = myconsole:
print("Hello, what's your name?"):
input():
print("hello, %inputbuffer%!");
this would indeed be a more convenient way to write it. How do we do that though?
What is a monad?
once you have a type (such as
How is a monad implemented?
See other answers, that seem quite free to jump into the details of that.
This excellent video with Brian Beckman explains monads 'in terms you already know' and Brian assures you don't have to be scared by monads because of the way they look, because they are easy. I found his approach very educating and a good introduction to monads. Check it out.
My favorite Monad tutorial:
(out of 170,000 hits on a Google search for "monad tutorial"!)
@Stu: The point of monads is to allow you to add (usually) sequential semantics to otherwise pure code; you can even compose monads (using Monad Transformers) and get more interesting and complicated combined semantics, like parsing with error handling, shared state, and logging, for example. All of this is possible in pure code, monads just allow you to abstract it away and reuse it in modular libraries (always good in programming), as well as providing convenient syntax to make it look imperative.
Haskell already has operator overloading[1]: it uses type classes much the way one might use interfaces in Java or C# but Haskell just happens to also allow non-alphanumeric tokens like + && and > as infix identifiers. It's only operator overloading in your way of looking at it if you mean "overloading the semicolon" [2]. It sounds like black magic and asking for trouble to "overload the semicolon" (picture enterprising Perl hackers getting wind of this idea) but the point is that without monads
This all sounds much more complicated than it needs to. sigfpe's article is pretty cool but uses Haskell to explain it, which sort of fails to break the chicken and egg problem of understanding Haskell to grok Monads and understanding Monads to grok Haskell.
[1] This is a separate issue from monads but monads use Haskell's operator overloading feature.
[2] This is also an oversimplification since the operator for chaining monadic actions is >>= (pronounced "bind") but there is syntactic sugar ("do") that lets you use braces and semicolons and/or indentation and newlines.
In addition to the excellent answers above, let me offer you a link to the following article (by Patrick Thomson) which explains monads by relating the concept to the JavaScript library
The jQuery documentation itself doesn't refer to the term "monad" but talks about the "builder pattern" which is probably more familiar. This doesn't change the fact that you have a proper monad there maybe without even realizing it.
Monads Are Not Metaphors, but a practically useful abstraction emerging from a common pattern, as Daniel Spiewak explains.
I've been thinking of Monads in a different way, lately. I've been thinking of them as abstracting out
If you're using an imperative language, and you write some expressions in order, the code ALWAYS runs exactly in that order.
And in the simple case, when you use a monad, it feels the same -- you define a list of expressions that happen in order. Except that, depending on which monad you use, your code might run in order (like in IO monad), in parallel over several items at once (like in the List monad), it might halt partway through (like in the Maybe monad), it might pause partway through to be resumed later (like in a Resumption monad), it might rewind and start from the beginning (like in a Transaction monad), or it might rewind partway to try other options (like in a Logic monad).
And because monads are polymorphic, it's possible to run the same code in different monads, depending on your needs.
Plus, in some cases, it's possible to combine monads together (with monad transformers) to get multiple features at the same time.
Monads are to control flow what abstract data types are to data.
In other words, many developers are comfortable with the idea of Sets, Lists, Dictionaries (or Hashes, or Maps), and Trees. Within those data types there are many special cases (for instance InsertionOrderPreservingIdentityHashMap).
However, when confronted with program "flow" many developers haven't been exposed to many more constructs than if, switch/case, do, while, goto (grr), and (maybe) closures.
So, a monad is simply a control flow construct. A better phrase to replace monad would be 'control type'.
As such, a monad has slots for control logic, or statements, or functions - the equivalent in data structures would be to say that some data structures allow you to add data, and remove it.
For example, the "if" monad:
if( clause ) then block
at it's simplest has two slots - a clause, and a block. The if monad is usually built to evaluate the result of the clause, and if not false, evaluate the block. Many developers are not introduced to monads when they learn 'if', and it just isn't necessary to understand monads to write effective logic.
Monads can become more complicated, in the same way that data structures can become more complicated, but there are many broad categories of monad that may have similar semantics, but differing implementations and syntax.
Of course, in the same way that data structures may be iterated over, or traversed, monads may be evaluated.
Compilers may or may not have support for user defined monads. Haskell certainly does. Ioke has some similar capabilities, athough the term monad is not used in the language.
The two things that helped me best when learning about there were:
Chapter 8, "Functional Parsers," from Graham Hutton's book Programming in Haskell. This doesn't mention monads at all, actually, but if you can work through chapter and really understand everything in it, particularly how a sequence of bind operations is evaluated, you'll understand the internals of monads. Expect this to take several tries.
The tutorial All About Monads. This gives several good examples of their use, and I have to say that the analogy in Appendex I worked for me.
http://code.google.com/p/monad-tutorial/ is a Work In Progress to address exactly this question.
In the context of Scala you will find the following to be the simplest definition. Basically flatMap (or bind) is 'associative' and there exists an identity.
trait M[+A] {
def flatMap[B](f: A => M[B]): M[B] // AKA bind
// Pseudo Meta Code
def isValidMonad: Boolean = {
// for every parameter the following holds
def isAssociativeOn[X, Y, Z](x: M[X], f: X => M[Y], g: Y => M[Z]): Boolean =
x.flatMap(f).flatMap(g) == x.flatMap(f(_).flatMap(g))
// for every parameter X and x, there exists an id
// such that the following holds
def isAnIdentity[X](x: M[X], id: X => M[X]): Boolean =
x.flatMap(id) == x
}
}
E.g.
// These could be any functions
val f: Int => Option[String] = number => if (number == 7) Some("hello") else None
val g: String => Option[Double] = string => Some(3.14)
// Observe these are identical. Since Option is a Monad
// they will always be identical no matter what the functions are
scala> Some(7).flatMap(f).flatMap(g)
res211: Option[Double] = Some(3.14)
scala> Some(7).flatMap(f(_).flatMap(g))
res212: Option[Double] = Some(3.14)
// As Option is a Monad, there exists an identity:
val id: Int => Option[Int] = x => Some(x)
// Observe these are identical
scala> Some(7).flatMap(id)
res213: Option[Int] = Some(7)
scala> Some(7)
res214: Some[Int] = Some(7)
A monad is a thing used to encapsulate objects that have changing state. It is most often encountered in languages that otherwise do not allow you to have modifiable state (e.g., Haskell).
An example would be for file IO.
You would be able to use a monad for file IO to isolate the changing state nature to just the code that used the Monad. The code inside the Monad can effectively ignore the changing state of the world outside the Monad - this makes it a lot easier to reason about the overall effect of your program.
If I've understood correctly, IEnumerable is derived from monads. I wonder if that might be an interesting angle of approach for those of us from the C# world?
For what it's worth, here are some links to tutorials that helped me (and no, I still haven't understood what monads are).
A monad is a way of combining computations together that share a common context. It is like building a network of pipes. When constructing the network, there is no data flowing through it. But when I have finished piecing all the bits together with 'bind' and 'return' then I invoke something like
Monoid appears to be something that ensures that all operations defined on a Monoid and a supported type will always return a supported type inside the Monoid. Eg, Any number + Any number = A number, no errors.
Whereas division accepts two fractionals, and returns a fractional, which defined division by zero as Infinity in haskell somewhy(which happens to be a fractional somewhy)...
In any case, it appears Monads are just a way to ensure that your chain of operations behaves in a predictable way, and a function that claims to be Num -> Num, composed with another function of Num->Num called with x does not say, fire the missiles.
On the other hand, if we have a function which does fire the missiles, we can compose it with other functions which also fire the missiles, because our intent is clear -- we want to fire the missiles -- but it won't try printing "Hello World" for some odd reason.
In Haskell, main is of type IO (), or IO [()], the distiction is strange and I will not discuss it but here's what I think happens:
If I have main, I want it to do a chain of actions, the reason I run the program is to produce an effect -- usually though IO. Thus I can chain IO operations together in main in order to -- do IO, nothing else.
If I try to do something which does not "return IO", the program will complain that the chain does not flow, or basically "How does this relate to what we are trying to do -- an IO action", it appears to force the programmer to keep their train of thought, without straying off and thinking about firing the missiles, while creating algorithms for sorting -- which does not flow.
Basically, Monads appear to be a tip to the compiler that "hey, you know this function that returns a number here, it doesn't actually always work, it can sometimes produce a Number, and sometimes Nothing at all, just keep this in mind". Knowing this, if you try to assert a monadic action, the monadic action may act as a compile time exception saying "hey, this isn't actually a number, this CAN be a number, but you can't assume this, do something to ensure that the flow is acceptable." which prevents unpredictable program behavior -- to a fair extent.
It appears monads are not about purity, nor control, but about maintaining an identity of a category on which all behavior is predictable and defined, or does not compile. You cannot do nothing when you are expected to do something, and you cannot do something if you are expected to do nothing (visible).
The biggest reason I could think of for Monads is -- go look at Procedural/OOP code, and you will notice that you do not know where the program starts, nor ends, all you see is a lot of jumping and a lot of math,magic,and missiles. You will not be able to maintain it, and if you can, you will spend quite a lot of time wrapping your mind around the whole program before you can understand any part of it, because modularity in this context is based on interdependant "sections" of code, where code is optimized to be as related as possible for promise of efficiency/inter-relation. Monads are very concrete, and well defined by definition, and ensure that the flow of program is possible to analyze, and isolate parts which are hard to analyze -- as they themselves are monads. A monad appears to be a "comprehensible unit which is predictable upon its full understanding" -- If you understand "Maybe" monad, there's no possible way it will do anything except be "Maybe", which appears trivial, but in most non monadic code, a simple function "helloworld" can fire the missiles, do nothing, or destroy the universe or even distort time -- we have no idea nor have any guarantees that IT IS WHAT IT IS. A monad GUARANTEES that IT IS WHAT IT IS. which is very powerful.
All things in "real world" appear to be monads, in the sense that it is bound by definite observable laws preventing confusion. This does not mean we have to mimic all the operations of this object to create classes, instead we can simply say "a square is a square", nothing but a square, not even a rectangle nor a circle, and "a square has area of the length of one of it's existing dimensions multiplied by itself. No matter what square you have, if it's a square in 2D space, it's area absolutely cannot be anything but its length squared, it's almost trivial to prove. This is very powerful because we do not need to make assertions to make sure that our world is the way it is, we just use implications of reality to prevent our programs from falling off track.
Im pretty much guaranteed to be wrong but I think this could help somebody out there, so hopefully it helps somebody.
I wrote this mostly for me but I hope otherwise find it useful :)
It turns out that instead of merely smoothing out the handling of DivByZero (or Infinity if you will) in calculations, the Monad treatment is broadly applicable to situations that can benefit from type expansion to simplify their coding. In fact this seems to be everything. In particular, the IO monad is a type that represents the universe, literally. Input to the program is "lifted" into this IO universe type which incidentally implies your computer hardware, etc as part of it's property values. A new instance of this universe IO is subsequently returned, duly indicative of all worldly modifications that are to be performed such as requesting additional input and updating your screen or database or whatever else.
Why?
Monads allow Stateless algorithms to be devised. State-full machines are complex. A machine with 10 bits may be in 2^10 possible states. Eliminating this complexity is the ideal of functional languages.
Variables hold state. Eliminate variables should simply stuff. Purely functional programs don't have variables only values (despite usage of the term 'variable' in the Haskell documentation) and labels or symbols or names for for them. The closest thing to a variable in a purely functional language is the parameters received by a function on each invocation.
So what?
Without the presence of state, the program becomes a declaration or a definition, as oppose to an interrogation and manipulation of some underlying state. Essentially,
x, unlike y, cannot be modified elsewhere concurrently, since it cannot be modified at all.
Why call it a Monad?
A monad is characterized by a mathematical structure called a Monoid from Algebraic group theory. With that said, all it means in that the structure has the following three properties:
Note how property two (2) describes a single element "lift" by requiring an ineffectual secondary element to the binary operation. In arithmetic addition this would be 0 and in multiplication it would be 1. Property three (3) allows arbitrary expression lengths to be evaluated without concern for segmentation as in,
The easiest way to grok them (at least for me) is as "decorators", adding behavior while preserving the underlying semantics. Or, an even dirtier definition: it's functional programming's operator overloading.
Two little tutorials from the wikibooks to explain the idea (one is F# but provides a nice short definition):
If you can read ML syntax, a short, accessible explanation with practical, simple code is here.
Explaining monads seems to be like explaining control-flow statements. Imagine that a non-programmer asks you to explain them?
You can give them an explanation involving the theory - Boolean Logic, register values, pointers, stacks, and frames. But that would be crazy.
You could explain them in terms of the syntax. Basically all control-flow statements in C have curly brackets, and you can distinguish the condition and the conditional code by where they are relative to the brackets. That may be even crazier.
Or you could also explain loops, if statements, routines, subroutines, and possibly co-routines.
Monads can replace a fairly large number of programming techniques. There's a specific syntax in languages that support them, and some theories about them.
They are also a way for functional programmers to use imperative code without actually admitting it, but that's not their only use.
protected by Tats_innit May 29 at 2:17
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?
|
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).
|
While I don't believe in putting numbers on source code quality, SonarQube (formerly known as Sonar) can be a really useful tool during development. It enforces a consistent style across your team, has discovered several possible bugs for me and is a great tool to learn: You can browse the violations and see why a certain expression or code block can be a problem.
To make sure that your code base stays in a consistent state you can also go as far as mandating that there should be no violations in the code developers check in. One of the problems with this is that a lot of projects are not green field projects and you have a lot of existing code. If your violation number already is high it is difficult to judge if no new violations were introduced.
In this post I will show you how you can start with zero violations for existing code without touching the sources, something I got inspired to do by Jens Schauder in his great talk Working with Legacy Teams. We will ignore all violations based on the line in the file so if anybody touches the file the violations will show again and the developer is responsible for fixing the legacy violations.
The Switch Off Violations Plugin
We are using the Switch Off Violations Plugin for SonarQube. It can be configured with different exclusion patterns for the issues. You can define regular expressions for code blocks that should be ignored or deactivate violations at all or on a file or line basis.
For existing code you want to ignore all violations for certain files and lines. This can be done by inserting something like this in the text area Exclusion patterns:
de.fhopf.akka.actor.IndexingActor;pmd:SignatureDeclareThrowsException;[23]
This will exclude the violation for throwing raw Exceptions in line 23 of the IndexingActor class. When analyzing the code again this violation will be ignored.
Retrieving violations via the API
Besides the nice dashboard SonarQube also offers an API that can be used to retrieve all the violations for a project. If you are not keen to look up all existing violations in your code base and insert those by hand you can use it to generate the exclusion patterns automatically. All of the violations can be found at /api/violations, e.g. http://localhost:9000/api/violations.
I am sure there are other ways to do it but I used jsawk to parse the JSON response (On Ubuntu you have to install Spidermonkey instead of the default js interpreter.. And you have to compile it yourself. And I had to use a specific version. Sigh.).
Once you have set up all the components you can now use jsawk to create the exclusion patterns for all existing violations:
curl -XGET 'http://localhost:9000/api/violations?depth=-1' | ./jsawk -a 'return this.join("\n")' 'return this.resource.key.split(":")[1] + ";*;[" + this.line + "]"' | sort | uniq
This will present a list that can just be pasted in the text area of the Switch Off Violations plugin or checked in to the repository as a file. With the next analysis process you will then hopefully see zero violations. When somebody changes a file by inserting a line the violations will be shown again and should be fixed. Unfortunately some violations are not line based and will yield a line number 'undefined'. Currently I just removed those manually so you still might see some violations.
Conclusion
I presented one way to reset your legacy code base to zero violations. With SonarQube 4.0 the functionality of the Switch Violations Off plugin will be available in the core so it will be easier to use. I am still looking for the best way to keep the exclusion patterns up to date. Once somebody had to fix the violations for an existing file the pattern should be removed.
Update 09.01.2014
Starting with SonarQube 4 this approach doesn't work anymore. Some features of the SwitchOffViolations plugin have been moved to the core but excluding violations by line is not possible anymore and also will not be implemented. The developers recommend to only look at the trends of the project and not the overall violation count. This can be done nicely using the differentials.
About Florian Hopf
I am working as a freelance software developer and consultant in Karlsruhe, Germany. If you liked this post you can follow me on Twitter or subscribe to my feed to get notified of new posts. If you think I could help you and your company and you'd like to work with me please contact me directly.
|
gtk.ListStore — a list model to use with a gtk.TreeView
class gtk.ListStore(gobject.GObject, gtk.TreeModel, gtk.TreeDragSource, gtk.TreeDragDest, gtk.TreeSortable):
gtk.ListStore(column_type, ...)
def set_column_types(type, ...)
def set_value(iter, column, value)
def set(iter, column_num, value, ...)
def remove(iter)
def insert(position, row=None)
def insert_before(sibling, row=None)
def insert_after(sibling, row=None)
def prepend(row=None)
def append(row=None)
def clear()
def iter_is_valid(iter)
def reorder(new_order)
def swap(a, b)
def move_after(iter, position)
def move_before(iter, position)
+--gobject.GObject+-- gtk.ListStore
gtk.ListStore(column_type, ...)
the column type of the first column
optional types for succeeding columns
a new gtk.ListStore
Creates a new list store as with one or more columns with the typespecified by the arguments passed to the constructor. For example,gtk.ListStore(gobject.TYPE_INT, gobject.TYPE_STRING,gtk.gdk.Pixbuf); will create a new gtk.ListStorewith three columns, of type int, string and gtk.gdk.Pixbufrespectively. The built-in GObject
gobject.TYPE_BOOLEANgobject.TYPE_BOXEDgobject.TYPE_CHARgobject.TYPE_DOUBLEgobject.TYPE_ENUMgobject.TYPE_FLAGSgobject.TYPE_FLOATgobject.TYPE_INTgobject.TYPE_INT64gobject.TYPE_INTERFACEgobject.TYPE_INVALIDgobject.TYPE_LONGgobject.TYPE_NONEgobject.TYPE_OBJECTgobject.TYPE_PARAMgobject.TYPE_POINTERgobject.TYPE_PYOBJECTgobject.TYPE_STRINGgobject.TYPE_UCHARgobject.TYPE_UINTgobject.TYPE_UINT64gobject.TYPE_ULONG
The column types can be any GObjectGObject
def set_column_types(type, ...)
the type of the first column
zero or more type specifications
This method is available in PyGTK 2.2 and above.
The set_column_types() method sets theliststore columns to the types specified by type andany additional type parameters. This method is meant primarily for classesthat inherit from
gtk.ListStore,and should only be used when constructing a new gtk.ListStore.It will not function after a row has been added, or a method on the gtk.TreeModelinterface is called.
def set_value(iter, column, value)
a valid gtk.TreeIter forthe row being modified
the column number to modify
the new value for the cell
The set_value() method sets the data inthe cell specified by iter and
columnvalue
def set(iter, column_num, value, ...)
A valid gtk.TreeIter forthe row being modified
the number of the column to modify
the new cell value
additional optional sets of column number - value pairs
The set() method sets the value of oneor more cells in the row referenced by iter. Theargument list should contain integer column numbers, each followed by thevalue to be set (the value must be convertible to the type of the cellcolumn). For example, to set column 0 with type
gobject.TYPE_STRING to "Foo", you would write:
liststore.set(iter, 0, "Foo")
def remove(iter)
A valid gtk.TreeIter forthe row
True if is still valid.iter
The remove() method removes the rowspecified by iter from the list store and returnsTrue if
iteriter
Prior to PyGTK 2.4 this method returned a new gtk.TreeIter thatis a copy of iter.
def insert(position, row=None)
the integer position to insert the new row
an optional list or tuple containing orderedcolumn values to set on the row orNone
A gtk.TreeIterpointing at the new row
The insert() method creates a new rowat the location specified by position. If
positionrowNone. If rowgobject.TYPE_STRING,gobject.TYPE_INT]) that are used to set the values in thecells of the new row. Alternatively, the application can fill in row cellvalues using the set() orset_value() methods.
def insert_before(sibling, row=None)
A valid gtk.TreeIteror None
an optional list or tuple containing orderedcolumn values to set on the row orNone
A gtk.TreeIterpointing at the new row
The insert_before() method inserts anew row before the row specified by the gtk.TreeIter sibling. The row will be empty if
rowNone.If rowgobject.TYPE_STRING,gobject.TYPE_INT]) that are used to set the values in thecells of the new row. Alternatively, the application can fill in row cellvalues using the set() orset_value()methods.
In PyGTK 2.4, if sibling is
None the row will be appended to the liststore.
def insert_after(sibling, row=None)
A valid gtk.TreeIteror None
an optional list or tuple containing orderedcolumn values to set on the row orNone
A gtk.TreeIterpointing at the new row
The insert_after() method inserts a newrow after the row specified by the gtk.TreeIter sibling. The row will be empty if
rowNone.If rowgobject.TYPE_STRING,gobject.TYPE_INT]) that are used to set the values in thecells of the new row. Alternatively, the application can fill in row cellvalues using the set() orset_value() methods.
In PyGTK 2.4, if sibling is
None the row will be prepended to the liststore.
def prepend(row=None)
an optional list or tuple containing orderedcolumn values to set on the row orNone
A gtk.TreeIterpointing at the new row
The prepend() method prepends a new rowto the liststore. The row will be empty if row is notspecified or is
None. If rowgobject.TYPE_STRING,gobject.TYPE_INT]) that are used to set the values in thecells of the new row. Alternatively, the application can fill in row cellvalues using the set() orset_value() methods.
def append(row=None)
an optional list or tuple containing orderedcolumn values to set on the row orNone
A gtk.TreeIterpointing at the new row
The append() method appends a new rowto the liststore. The row will be empty if row is notspecified or is
None. If rowgobject.TYPE_STRING,gobject.TYPE_INT]) that are used to set the values in thecells of the new row. Alternatively, the application can fill in row cellvalues using the set() orset_value() methods.
def clear()
The clear() method removes all rowsfrom the liststore.
def iter_is_valid(iter)
A gtk.TreeIter.
True if the iter is valid, False if the iter is invalid.
This method is available in PyGTK 2.2 and above.
This method is slow. Only use it for debugging and/or testing purposes.
def reorder(new_order)
a list of integers. The gtk.ListStore nodes will be rearranged so that the gtk.ListStore node that is at position index new_order[i] will be located at position index i.
This method is available in PyGTK 2.2 and above.
The reorder() method reorders the gtk.ListStore items to follow the order indicated by new_order. The
gtk.ListStore nodes will be rearranged so that the gtk.ListStore node that is at position index new_order[i] will be located at position index i. Note that this method only works with unsorted stores.
def swap(a, b)
A gtk.TreeIter.
Another gtk.TreeIter.
This method is available in PyGTK 2.2 and above.
The swap() method swaps the liststorerows specified by the gtk.TreeIters a and
b
def move_after(iter, position)
A gtk.TreeIter.
A gtk.TreeIter or None.
This method is available in PyGTK 2.2 and above.
The move_after() method moves theliststore row referenced by iter to the positionafter the row referenced by
positionpositionNone, the row referenced byiter
def move_before(iter, position)
A gtk.TreeIter.
A gtk.TreeIter, or None.
This method is available in PyGTK 2.2 and above.
The move_before() method moves theliststore row referenced by iter to the positionbefore the row referenced by
positionpositionNone, the row referenced byiter
|
I'm using epoll reactor and sample HTTP Proxy realization.
From another process a execute ~30 HTTP requests per second and twisted process is consuming 10% cpu
The profiler output is:
937706 function calls (934675 primitive calls) in 59.988 CPU seconds
Ordered by: cumulative time
List reduced from 312 to 15 due to restriction <15>
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 59.988 59.988 base.py:1167(run)
1 0.076 0.076 59.988 59.988 base.py:1172(mainLoop)
12697 55.456 0.004 59.253 0.005 epollreactor.py:169(doPoll)
13553 0.086 0.000 3.797 0.000 log.py:71(callWithLogger)
13553 0.096 0.000 3.691 0.000 log.py:66(callWithContext)
13553 0.047 0.000 3.481 0.000 context.py:117(callWithContext)
13553 0.067 0.000 3.426 0.000 context.py:61(callWithContext)
13552 0.095 0.000 3.359 0.000 posixbase.py:544(_doReadOrWrite)
5454 0.097 0.000 1.736 0.000 tcp.py:182(doRead)
5453 0.167 0.000 1.639 0.000 basic.py:543(dataReceived)
12697 0.095 0.000 0.587 0.000 base.py:762(runUntilCurrent)
4453 0.025 0.000 0.574 0.000 http.py:495(rawDataReceived)
6000 0.036 0.000 0.547 0.000 http.py:1515(lineReceived)
2000 0.029 0.000 0.454 0.000 tcp.py:371(doConnect)
5098 0.104 0.000 0.428 0.000 abstract.py:212(doWrite)
937706 function calls (934675 primitive calls) in 59.988 CPU seconds
Ordered by: internal time
List reduced from 312 to 15 due to restriction <15>
ncalls tottime percall cumtime percall filename:lineno(function)
12697 55.456 0.004 59.253 0.005 epollreactor.py:169(doPoll)
59101 0.277 0.000 0.277 0.000 <string>:1(fileno)
5098 0.252 0.000 0.252 0.000 tcp.py:212(writeSomeData)
24453 0.198 0.000 0.198 0.000 __init__.py:1230(getEffectiveLevel)
5453 0.167 0.000 1.639 0.000 basic.py:543(dataReceived)
5098 0.104 0.000 0.428 0.000 abstract.py:212(doWrite)
5454 0.097 0.000 1.736 0.000 tcp.py:182(doRead)
13553 0.096 0.000 3.691 0.000 log.py:66(callWithContext)
12697 0.095 0.000 0.587 0.000 base.py:762(runUntilCurrent)
13552 0.095 0.000 3.359 0.000 posixbase.py:544(_doReadOrWrite)
13553 0.086 0.000 3.797 0.000 log.py:71(callWithLogger)
1 0.076 0.076 59.988 59.988 base.py:1172(mainLoop)
16556 0.074 0.000 0.074 0.000 context.py:86(getContext)
17451 0.073 0.000 0.094 0.000 epollreactor.py:71(_add)
17098 0.068 0.000 0.085 0.000 epollreactor.py:112(_remove)
What is wrong? Why twisted perfomance is so poor here?
Source code being tested applied
import hotshot, hotshot.stats
from twisted.internet import epollreactor
epollreactor.install()
from twisted.internet import reactor
from twisted.web import http
from twisted.web.proxy import Proxy
factory = http.HTTPFactory()
factory.protocol = Proxy
reactor.listenTCP(18001, factory)
reactor.callLater(60, reactor.stop)
prof = hotshot.Profile("stones.prof")
prof.start()
reactor.run()
prof.close()
|
I was trying to do the exact same thing today, and ended up writing a helper function to render template tags:
def render_templatetag(request, tag_string, tag_file, dictionary=None):
dictionary = dictionary or {}
context_instance = RequestContext(request)
context_instance.update(dictionary)
t = Template("{%% load %s %%}{%% %s %%}" % (tag_file, tag_string))
return t.render(context_instance)
tag_string is the call to the template tag as it'd appear in a normal template, and tag_file is the file you need to load for the template tag.
|
Short description: I want to run an instance of gedit, provided by my Ubuntu 13.10 "Server" on another Computer. It works via ssh -X, but some plugins cannot be installed (in my case it is 'Snippets').
After installing gedit and gedit-plugins none of the plugins worked. I installed dbus-x11 and most of them worked - "Snippets", unfortunately, still doesn't. Bash says:
Traceback (most recent call last):
File "/usr/lib/x86_64-linux-gnu/gedit/plugins/snippets/__init__.py", line 18, in <module>
from .appactivatable import AppActivatable
File "/usr/lib/x86_64-linux-gnu/gedit/plugins/snippets/appactivatable.py", line 26, in <module>
from .manager import Manager
File "/usr/lib/x86_64-linux-gnu/gedit/plugins/snippets/manager.py", line 29, in <module>
from .document import Document
File "/usr/lib/x86_64-linux-gnu/gedit/plugins/snippets/document.py", line 21, in <module>
import cairo
ImportError: No module named 'cairo'
(gedit:954): libpeas-WARNING **: Error loading plugin 'snippets'
when I try to select "Snippets" in the plugins preferences. Any idea what I am doing wrong?
Long description: I'm using a MacBook Air for daily work. Unfortunately there seems to be no way, to get gedit running on OS X Mavericks (or any other OS X capable of running on the MacBook). So, if anyone knows a workaround for that, it would be a possible solution to. (I've tried an older version of gedit - 2.x.x I guess - it didn't crash, but it was rather buggy.)
So I installed a "hardware friendly" Ubuntu Server via Parallels Desktop 9. I guess there are distros which are far more lightweight, but Ubuntu works really seamlessly with PD9, so I chose it.
Via XQuarts linux applications like gedit can easily be streamed over ssh. So I'm able to run gedit. But I "need" the snippets. There are of course many other text editors for Mac OS, but they cost a lot of money or are incapable of almost anything.
Best regards and thanks in advance, Markus
|
k3c
Re : TVDownloader: télécharger les médias du net ! [2]
Merci Julien
J'ai testé avec succès pour plusieurs vidéos comme
par contre le --resume devrait être optionnel
python d8_julien.py http://www.d8.tv/d8-art-de-vivre/pid5205-d8-a-vos-regions.html
rtmpdump -r "rtmp://geo2-vod-fms.canalplus.fr/ondemand/geo2/1304/A_VOS_REGIONS_BA_130402_CAN_328928_video_HD.mp4" -o "A_vos_régions.mp4" --resume
RTMPDump v2.4
(c) 2010 Andrej Stepanchuk, Howard Chu, The Flvstreamer Team; license: GPL
ERROR: Last tag size must be greater/equal zero (prevTagSize=-629966759) and smaller then filesize, corrupt file!
gg@gg-SATELLITE-L755:~$ rtmpdump -r "rtmp://geo2-vod-fms.canalplus.fr/ondemand/geo2/1304/A_VOS_REGIONS_BA_130402_CAN_328928_video_HD.mp4" -o "A_vos_régions.mp4"
RTMPDump v2.4
(c) 2010 Andrej Stepanchuk, Howard Chu, The Flvstreamer Team; license: GPL
Connecting ...
INFO: Connected...
Starting download at: 0.000 kB
INFO: Metadata:
INFO: duration 401.54
INFO: moovPosition 81208653.00
INFO: audiocodecid mp4a
INFO: width 640.00
INFO: height 360.00
INFO: videocodecid avc1
INFO: avcprofile 66.00
INFO: avclevel 30.00
INFO: aacaot 2.00
INFO: audiosamplerate 44100.00
INFO: audiochannels 2.00
INFO: videoframerate 25.00
INFO: trackinfo:
INFO: length 17708032.00
INFO: timescale 44100.00
INFO: language eng
INFO: sampledescription:
INFO: sampletype mp4a
INFO: length 10036000.00
INFO: timescale 25000.00
INFO: language eng
INFO: sampledescription:
INFO: sampletype avc1
79789.031 kB / 401.52 sec (99.9%)
Download complete
gg@gg-SATELLITE-L755:~$
et je ne trouve pas l'id de la vidéo pour le match PSG Barcelone, je vais regarder
http://www.d8.tv/d8-sport/pid5653-d8-fc … e-psg.html
Edit: le ! dans le titre
Touche pas à mon poste !
plante la vidéo, donc
titre = titre.replace('/','_').replace('!','')
Dernière modification par k3c (Le 04/04/2013, à 13:24)
Hors ligne
k3c
Re : TVDownloader: télécharger les médias du net ! [2]
Bon la page sur PSG Barcelone ne contient pas de video...
Après quelques modifs mineures (passage de l'id dans la fonction, nom vid et pas id qui est un mot réservé...)
voici une version qui a l'air pas mal
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# D8 version 0.3 par k3c et Julien974
from urllib2 import urlopen
from lxml import objectify
import bs4 as BeautifulSoup
import sys, subprocess, re
a = urlopen(sys.argv[1]).read()
s = BeautifulSoup.BeautifulSoup(a)
url = ''
def get_HD(d8_cplus,vid):
zz = urlopen('http://service.canal-plus.com/video/rest/getVideosLiees/'+d8_cplus+'/'+vid).read()
root = objectify.fromstring(zz)
isGoodId = False
for element in root.iter():
if element.tag == 'ID':
if element.text == str(vid) :
isGoodId = True
if element.tag == 'HD' and isGoodId :
url = element.text
arguments = 'rtmpdump -r "%s" -o "%s.mp4" --resume' % (url, titre)
print arguments
process = subprocess.Popen(arguments, stdout=subprocess.PIPE, shell=True).communicate()[0]
isGoodId = False
sys.exit()
m = re.search('pid\d{6}',sys.argv[1])
if m is None:
try:
vid = s.findAll('div',attrs={"class":u"block-common block-player-programme"})[0]('canal:player')[0]['videoid']
except:
print 'impossible de trouver l\'id de la video'
sys.exit()
else:
vid = m.group(0)
titre = s.findAll('meta',attrs={"property":u"og:title"})[0]['content'].replace(' ','_')
titre = titre.replace('/','_').replace('!','')
for x in ['d8','cplus']:
get_HD(x,vid)
Hors ligne
JUL1EN094
Re : TVDownloader: télécharger les médias du net ! [2]
Merci Julien
J'ai testé ave...
Salut k3c,
Merci pour ton retour.
- Tu veux bien nous faire le --resume optionnel ? Je n'ai pas touché à cette partie, pas sur de savoir comment faire. J'ai repris le code sur le fil de discussion précédent et ai juste ajouté la condition isGoodId, qui est sensé valider le fait que nous sommes dans les infos correspondant au bon ID (le fichier récupéré contients les infos pour plusieurs emissions).
- Pour le match moi je ne vois pas video de disponible sur le site,... donc pas d'id. Normal à mon sens.
- Pour les '!', tu risques/peux avoir le cas sur d'autres caractères, pas seulement le '!'. Perso je repasse sur le string avec la fonction suivante, qui t'assurera d'avoir un nom de fichier compatible avec n'importe quel système de fichier (= pas de caractères incorrects) :
#for RemoveDisallowedFilenameChars()
import unicodedata
import string
validFilenameChars = "-_.() %s%s" % (string.ascii_letters, string.digits)
def RemoveDisallowedFilenameChars(filename):
cleanedFilename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore')
return ''.join(c for c in cleanedFilename if c in validFilenameChars)
Encore merci pour ton excellent travail et a bientôt.
Hors ligne
JUL1EN094
Re : TVDownloader: télécharger les médias du net ! [2]
on s'est croisé hihi.
Hors ligne
k3c
Re : TVDownloader: télécharger les médias du net ! [2]
@ julien
Pour le --resume finalement la vidéo récalcitrante marche, donc je ne sais pas
Merci pour ta fonction, je l'ai utilisée, et j'ai fait des petites modifs, histoire que pylint me donne la moyenne :-)
j'ai ajouté d8 ou cplus dans le nom du fichier avant .mp4 pour savoir d'où on vient.
dernière version
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# D8 version 0.5 par k3c et Jul1en094
from urllib2 import urlopen
from lxml import objectify
import bs4 as BeautifulSoup
import sys, subprocess, re
import unicodedata
import string
validFilenameChars = "-_.() %s%s" % (string.ascii_letters, string.digits)
def removeDisallowedFilenameChars(filename):
"Remove invalid filename characters"
cleanedFilename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore')
cleanedFilename = cleanedFilename.replace(' ', '_')
return ''.join(c for c in cleanedFilename if c in validFilenameChars)
def getHD(d8_cplus, titre, vid):
"Get video url and download"
titre = removeDisallowedFilenameChars(titre)
zz = urlopen('http://service.canal-plus.com/video/rest/getVideosLiees/'+d8_cplus+'/' + vid).read()
root = objectify.fromstring(zz)
isGoodId = False
for element in root.iter():
if element.tag == 'ID':
if element.text == str(vid) :
isGoodId = True
if element.tag == 'HD' and isGoodId:
url = element.text
arguments = 'rtmpdump -r "%s" -o "%s_%s.mp4" --resume' % (url, titre, d8_cplus)
print arguments
subprocess.Popen(arguments, stdout=subprocess.PIPE, shell=True).communicate()[0]
isGoodId = False
sys.exit()
def main():
"main function"
a = urlopen(sys.argv[1]).read()
s = BeautifulSoup.BeautifulSoup(a)
m = re.search('pid\d{6}', sys.argv[1])
if m is None:
try:
vid = s.findAll('div', attrs={"class":u"block-common block-player-programme"})[0]('canal:player')[0]['videoid']
except:
print 'impossible de trouver l\'id de la video'
sys.exit()
else:
vid = m.group(0)
titre = s.findAll('meta', attrs={"property":u"og:title"})[0]['content']
for x in ['d8','cplus']:
getHD(x, titre, vid)
if __name__ == '__main__':
main()
Dernière modification par k3c (Le 05/04/2013, à 07:40)
Hors ligne
ynad
Re : TVDownloader: télécharger les médias du net ! [2]
@ 11gjm
merci pour l’explication...
Hors ligne
k3c
Re : TVDownloader: télécharger les médias du net ! [2]
La version précédente faisait une erreur pour télécharger la série H, donc voilà un fix
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# D8 version 0.5.1 par k3c et Jul1en094
from urllib2 import urlopen
from lxml import objectify
import bs4 as BeautifulSoup
import sys, subprocess, re
import unicodedata
import string
validFilenameChars = "-_.() %s%s" % (string.ascii_letters, string.digits)
def removeDisallowedFilenameChars(filename):
"Remove invalid filename characters"
filename = filename.decode('ASCII', 'ignore')
cleanedFilename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore')
cleanedFilename = cleanedFilename.replace(' ', '_')
return ''.join(c for c in cleanedFilename if c in validFilenameChars)
def getHD(d8_cplus, titre, vid):
"Get video url and download"
titre = removeDisallowedFilenameChars(titre)
zz = urlopen('http://service.canal-plus.com/video/rest/getVideosLiees/'+d8_cplus+'/' + vid).read()
root = objectify.fromstring(zz)
isGoodId = False
for element in root.iter():
if element.tag == 'ID':
if element.text == str(vid) :
isGoodId = True
if element.tag == 'HD' and isGoodId:
url = element.text
arguments = 'rtmpdump -r "%s" -o "%s_%s.mp4" --resume' % (url, titre, d8_cplus)
print arguments
subprocess.Popen(arguments, stdout=subprocess.PIPE, shell=True).communicate()[0]
isGoodId = False
sys.exit()
def main():
"main function"
a = urlopen(sys.argv[1]).read()
s = BeautifulSoup.BeautifulSoup(a)
m = re.search('pid\d{6}', sys.argv[1])
if m is None:
try:
vid = s.findAll('div', attrs={"class":u"block-common block-player-programme"})[0]('canal:player')[0]['videoid']
except:
print 'impossible de trouver l\'id de la video'
sys.exit()
else:
vid = m.group(0)
titre = s.findAll('meta', attrs={"property":u"og:title"})[0]['content']
for x in ['d8','cplus']:
getHD(x, titre, vid)
if __name__ == '__main__':
main()
Dernière modification par k3c (Le 05/04/2013, à 07:41)
Hors ligne
k3c
Re : TVDownloader: télécharger les médias du net ! [2]
Au fait le script de KSV (pour télécharger les sites qui font du Adobe Http Dynamic Streaming) a visiblement été porté en Python
Hors ligne
k3c
Re : TVDownloader: télécharger les médias du net ! [2]
J'ai fait un script pour télécharger les vidéos de NRJ, basé sur le plugin XBMC.
Je ne vais pas dire que les vidéos sont géniales, mais ça utilise pyamf, une première pour moi.
:-)
# -*- coding: utf-8 -*-
# os and lib modules
import subprocess
import sys
import urllib2
import shlex
# pyamf
from pyamf.remoting.client import RemotingService
# parseDOM
import bs4 as BeautifulSoup
import unicodedata
import string
__addonID__ = "plugin.video.NRJ12Replay"
__author__ = "k3c,JUL1EN094 ,vilain_mamuth"
__date__ = "05-04-2013"
__version__ = "1.0"
__credits__ = "Merci aux auteurs des autres addons replay du dépôt Passion-XBMC et de la communauté open-source"
# Web variable
INFOSITE = "http://prod-kernnrj12v5.integra.fr/videoinfo"
validFilenameChars = "-_.() %s%s" % (string.ascii_letters, string.digits)
def removeDisallowedFilenameChars(filename):
"Remove invalid filename characters"
filename = filename.decode('ASCII', 'ignore')
cleanedFilename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore')
cleanedFilename = cleanedFilename.replace(' ', '_')
return ''.join(c for c in cleanedFilename if c in validFilenameChars)
def get_soup(url):
"analyse de la page par BeautifulSoup"
req = urllib2.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0.1')
sou = urllib2.urlopen(req).read()
soup = BeautifulSoup.BeautifulSoup(sou)
try:
mediaId = soup.findAll('div', attrs={"class":u"img-une"})[0]('img')[0]['id']
# on enlève mediaId_
mediaId = mediaId[8:]
except:
print 'impossible de trouver l\'id de la video'
sys.exit()
return mediaId
def get_url(url, mediaId):
"appel à pyamf pour l'adresse de la vidéo"
client = RemotingService(url)
vi = client.getService('Nrj_VideoInfos')
mi = vi.mediaInfo(mediaId)
url_episode = mi["url"]
titre = mi["title"].replace(' ','_')
return url_episode, titre
#######################################################################################################################
# BEGIN !
#######################################################################################################################
def main():
"main function"
mediaId = get_soup(sys.argv[1])
url_episode, titre = get_url(INFOSITE, mediaId)
cmds = 'msdl -c --no-proxy %s -s 5 -o %s.mp4' % (url_episode, titre)
arguments = shlex.split( cmds )
print arguments
p = subprocess.Popen( arguments, stdout = subprocess.PIPE).communicate()[0]
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) + ")"
if __name__ == '__main__':
main()
Hors ligne
ynad
Re : TVDownloader: télécharger les médias du net ! [2]
Bonjour,
pas de retour sur le script nrj(12) de k3c... j'ai installé pyafm, mais des mess d'erreurs
Hors ligne
k3c
Re : TVDownloader: télécharger les médias du net ! [2]
@ ynad
Tu peux poster les messages d'erreur ?
Hors ligne
thom83
Re : TVDownloader: télécharger les médias du net ! [2]
Bonjour,
J'ai fait un essai qui montre des erreurs, mais qui télécharge avec un débit d'environ 100 ko/s :
~$ python Bureau/Scripts-TV-Replay/NRJ.py http://www.nrj12.fr/replay-4203/toutes-les-emissions-en-replay-4204/media/video/671332-crimes-a-bordeaux.html
['msdl', '-c', '--no-proxy', 'http://r.nrj.fr/mogador/web/00193232_h264_12.mp4', '-s', '5', '-o', 'CRIMES.mp4']
download [ CRIMES.mp4 ]
Host: [ 95.81.165.1:80 ] connected!
get_filesize CRIMES.mp4: stat() error
No such file or directory
http resume: no such file "CRIMES.mp4", not resuming
redirect to http://95.81.147.19/1UWRWhAEJgo07hftIzFBeC-4iE-vZJsyuTUA=/mogador/web/00193232_h264_12.mp4
Host: [ 95.81.147.19:80 ] connected!
get_filesize CRIMES.mp4: stat() error
No such file or directory
http resume: no such file "CRIMES.mp4", not resuming
Après avoir stoppé le programme à 3 %, le fichier de 30Mo est tout à fait lisible avec VLC.
J'ai cherché à utiliser ce script pour les flux de cherie25 (Les Tudors). Sans succès.
~$ python Bureau/Scripts-TV-Replay/NRJ.py http://www.cherie25.fr/replay-4272/media/video/668987-le-pardon-royal.html
impossible de trouver l'id de la video
J'ai voulu utiliser rtmpsrv pour trouver la commande à lancer. Là, c'est une erreur sur iptables qui me bloque
~$ sudo iptables -t nat -A OUTPUT -p tcp –dport 1935 -j REDIRECT
[sudo] password for thom:
Bad argument `–dport'
Try `iptables -h' or 'iptables --help' for more information.
Finalement, pour cherie25, Adblock Plus donne l'adresse de la video qui peut être obtenue grâce à wget.
Dernière modification par thom83 (Le 09/04/2013, à 16:51)
Hors ligne
k3c
Re : TVDownloader: télécharger les médias du net ! [2]
@ thom83
Pour iptables, c'est des commandes du type
sudo iptables -t nat -A OUTPUT -p tcp --dport 1935 -j REDIRECT
sudo iptables -t nat -D OUTPUT -p tcp --dport 1935 -j REDIRECT
mais rtmpsrv ne va rien trouver, vu que ce n'est pas une commande rtmpdump
Edit
Le script qui suit télécharge les Tudors, je n'ai rien testé d'autre, et il serait mieux d'avoir un script unique
# -*- coding: utf-8 -*-
# os and lib modules
import subprocess
import sys
import urllib2
import shlex
# pyamf
from pyamf.remoting.client import RemotingService
# parseDOM
import bs4 as BeautifulSoup
import unicodedata
import string
__addonID__ = "plugin.video.NRJ12Replay"
__author__ = "k3c,JUL1EN094 ,vilain_mamuth"
__date__ = "05-04-2013"
__version__ = "1.0"
__credits__ = "Merci aux auteurs des autres addons replay du dépôt Passion-XBMC et de la communauté open-source"
# Web variable
#WEBROOT = "http://www.nrj12.fr"
#WEBSITE = WEBROOT + "/replay-4203/collectionvideo/"
INFOSITE = "http://prod-kernnrj12v5.integra.fr/videoinfo"
validFilenameChars = "-_.() %s%s" % (string.ascii_letters, string.digits)
def removeDisallowedFilenameChars(filename):
"Remove invalid filename characters"
filename = filename.decode('ASCII', 'ignore')
cleanedFilename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore')
cleanedFilename = cleanedFilename.replace(' ', '_')
return ''.join(c for c in cleanedFilename if c in validFilenameChars)
def get_soup(url):
"analyse de la page par BeautifulSoup"
req = urllib2.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0.1')
sou = urllib2.urlopen(req).read()
soup = BeautifulSoup.BeautifulSoup(sou)
print "le findAll "
try:
mediaId = soup.findAll('div', attrs={"class":u"page_video"})[0]('img')[0]['id']
# on enlève mediaId_
mediaId = mediaId[8:]
except:
print 'impossible de trouver l\'id de la video'
sys.exit()
return mediaId
def get_url(url, mediaId):
"appel à pyamf pour l'adresse de la vidéo"
client = RemotingService(url)
vi = client.getService('Nrj_VideoInfos')
mi = vi.mediaInfo(mediaId)
url_episode = mi["url"]
titre = mi["title"].replace(' ','_')
return url_episode, titre
#######################################################################################################################
# BEGIN !
#######################################################################################################################
def main():
"main function"
mediaId = get_soup(sys.argv[1])
url_episode, titre = get_url(INFOSITE, mediaId)
cmds = 'msdl -c --no-proxy %s -s 5 -o %s.mp4' % (url_episode, titre)
arguments = shlex.split( cmds )
print arguments
p = subprocess.Popen( arguments, stdout = subprocess.PIPE).communicate()[0]
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) + ")"
if __name__ == '__main__':
main()
Dernière modification par k3c (Le 09/04/2013, à 17:59)
Hors ligne
k3c
Re : TVDownloader: télécharger les médias du net ! [2]
Un script unique pour cherie25 et nrj
# -*- coding: utf-8 -*-
# os and lib modules
# cherie25 et nrj v 0.1 k3c
import subprocess
import sys
import urllib2
import shlex
from urlparse import urlparse
# pyamf
from pyamf.remoting.client import RemotingService
# parseDOM
import bs4 as BeautifulSoup
import unicodedata
import string
__addonID__ = "plugin.video.NRJ12_cherie25"
__author__ = "k3c"
__date__ = "05-04-2013"
__version__ = "0.1"
__credits__ = "Merci aux auteurs des autres addons replay du dépôt Passion-XBMC et de la communauté open-source"
INFOSITE = "http://prod-kernnrj12v5.integra.fr/videoinfo"
mediaId = ''
validFilenameChars = "-_.() %s%s" % (string.ascii_letters, string.digits)
def removeDisallowedFilenameChars(filename):
"Remove invalid filename characters"
filename = filename.decode('ASCII', 'ignore')
cleanedFilename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore')
cleanedFilename = cleanedFilename.replace(' ', '_')
return ''.join(c for c in cleanedFilename if c in validFilenameChars)
def get_soup(url):
"analyse de la page par BeautifulSoup"
req = urllib2.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0.1')
sou = urllib2.urlopen(req).read()
soup = BeautifulSoup.BeautifulSoup(sou)
print "le findAll "
zz = urlparse(sys.argv[1])
try:
if 'cherie25' in zz.netloc:
mediaId = soup.findAll('div', attrs={"class":u"page_video"})[0]('img')[0]['id']
elif 'nrj' in zz.netloc:
mediaId = soup.findAll('div', attrs={"class":u"img-une"})[0]('img')[0]['id']
else:
print "cette video ne vient ni de nrj12 ni de cherie25"
sys.exit()
# on enlève mediaId_
mediaId = mediaId[8:]
# print mediaId
except:
print 'impossible de trouver l\'id de la video'
sys.exit()
return mediaId
def get_url(url, mediaId):
"appel à pyamf pour l'adresse de la vidéo"
client = RemotingService(url)
vi = client.getService('Nrj_VideoInfos')
mi = vi.mediaInfo(mediaId)
url_episode = mi["url"]
titre = mi["title"].replace(' ','_')
return url_episode, titre
#######################################################################################################################
# BEGIN !
#######################################################################################################################
def main():
"main function"
mediaId = get_soup(sys.argv[1])
url_episode, titre = get_url(INFOSITE, mediaId)
cmds = 'msdl -c --no-proxy %s -s 5 -o %s.mp4' % (url_episode, titre)
arguments = shlex.split( cmds )
print arguments
p = subprocess.Popen( arguments, stdout = subprocess.PIPE).communicate()[0]
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) + ")"
if __name__ == '__main__':
main()
Hors ligne
thom83
Re : TVDownloader: télécharger les médias du net ! [2]
Ce dernier script semble bien fonctionner pour cherie25, avec les même mentions d'erreur que pour NRJ mais beaucoup plus vite, entre 500 et 600 ko/s.
Merci
Hors ligne
k3c
Re : TVDownloader: télécharger les médias du net ! [2]
@ thom83
Les "messages d'erreur" sont liés à msdl, tu les auras toujours.
Je peux remplacer msdl par curl, éventuellement.
Hors ligne
thom83
Re : TVDownloader: télécharger les médias du net ! [2]
Non, je pense que msdl est plus efficace en débit que curl.
Hors ligne
thom83
Re : TVDownloader: télécharger les médias du net ! [2]
Il y a tout de même un détail qui ne va pas, c'est le choix du nom de fichier.
En l'occurrence, il y a plusieurs épisodes et le fichier initial est pollué par le deuxième (ce dernier étant plus long : 401313203 contre 390687908 octets)
J'ai noté également que wget permet de charger l'adresse contenue dans la liste commençant par 'msdl', et ce, avec le nom de fichier commençant par un n° qui est unique.
Hors ligne
k3c
Re : TVDownloader: télécharger les médias du net ! [2]
@ thom83
J'ai ajouté à la fin du nom _ suivi de l'identifiant de la vidéo (6 chiffres)
Ca te convient ?
Hors ligne
thom83
Re : TVDownloader: télécharger les médias du net ! [2]
Bonjour,
L'identifiant devrait éviter de modifier une video déjà complète. 9a me paraît donc parfait.
Hors ligne
k3c
Re : TVDownloader: télécharger les médias du net ! [2]
version avec l'identifiant
# -*- coding: utf-8 -*-
# os and lib modules
# cherie25 et nrj v 0.3 k3c
import subprocess
import sys
import urllib2
import shlex
from urlparse import urlparse
# pyamf
from pyamf.remoting.client import RemotingService
# parseDOM
import bs4 as BeautifulSoup
import unicodedata
import string
__addonID__ = "plugin.video.NRJ12Replay"
__author__ = "k3c,JUL1EN094 ,vilain_mamuth"
__date__ = "05-04-2013"
__version__ = "0.3"
__credits__ = "Merci aux auteurs des autres addons replay du dépôt Passion-XBMC et de la communauté open-source"
# Web variable
#WEBROOT = "http://www.nrj12.fr"
#WEBSITE = WEBROOT + "/replay-4203/collectionvideo/"
INFOSITE = "http://prod-kernnrj12v5.integra.fr/videoinfo"
validFilenameChars = "-_.() %s%s" % (string.ascii_letters, string.digits)
def removeDisallowedFilenameChars(filename):
"Remove invalid filename characters"
filename = filename.decode('ASCII', 'ignore')
cleanedFilename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore')
cleanedFilename = cleanedFilename.replace(' ', '_')
return ''.join(c for c in cleanedFilename if c in validFilenameChars)
def get_soup(url):
"analyse de la page par BeautifulSoup"
req = urllib2.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0.1')
sou = urllib2.urlopen(req).read()
soup = BeautifulSoup.BeautifulSoup(sou)
print "le findAll "
zz = urlparse(sys.argv[1])
mediaiId = ''
try:
if 'cherie25' in zz.netloc:
mediaId = soup.findAll('div', attrs={"class":u"page_video"})[0]('img')[0]['id']
elif 'nrj' in zz.netloc:
mediaId = soup.findAll('div', attrs={"class":u"img-une"})[0]('img')[0]['id']
else:
print "cette video ne vient ni de nrj12 ni de cherie25"
sys.exit()
# on enlève mediaId_
mediaId = mediaId[8:]
# print mediaId
except:
print 'impossible de trouver l\'id de la video'
sys.exit()
return mediaId
def get_url(url, mediaId):
"appel à pyamf pour l'adresse de la vidéo"
client = RemotingService(url)
vi = client.getService('Nrj_VideoInfos')
mi = vi.mediaInfo(mediaId)
url_episode = mi["url"]
titre = mi["title"].replace(' ','_')
return url_episode, titre
#######################################################################################################################
# BEGIN !
#######################################################################################################################
def main():
"main function"
mediaId = get_soup(sys.argv[1])
url_episode, titre = get_url(INFOSITE, mediaId)
cmds = 'msdl -c --no-proxy %s -s 5 -o \"%s_%s.mp4\"' % (url_episode, titre, mediaId)
print cmds
arguments = shlex.split( cmds )
print arguments
subprocess.Popen( arguments, stdout = subprocess.PIPE).communicate()[0]
# 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) + ")"
if __name__ == '__main__':
main()
Hors ligne
ynad
Re : TVDownloader: télécharger les médias du net ! [2]
@ k3c
Bonjour,
messages d'erreurs par ex:
python nrj12-0.3.py http://www.nrj12.fr/replay-4203/media/video/668850-choc-en-retour.html
le findAll
msdl -c --no-proxy http://r.nrj.fr/mogador/web/00121585_h264_12.mp4 -s 5 -o "LES_CORDIER,_JUGE_ET_FLIC_668850.mp4"
['m\x00s\x00d\x00l\x00', '\x00-\x00c\x00', '\x00-\x00-\x00n\x00o\x00-\x00p\x00r\x00o\x00x\x00y\x00', '\x00h\x00t\x00t\x00p\x00:\x00/\x00/\x00r\x00.\x00n\x00r\x00j\x00.\x00f\x00r\x00/\x00m\x00o\x00g\x00a\x00d\x00o\x00r\x00/\x00w\x00e\x00b\x00/\x000\x000\x001\x002\x001\x005\x008\x005\x00_\x00h\x002\x006\x004\x00_\x001\x002\x00.\x00m\x00p\x004\x00', '\x00-\x00s\x00', '\x005\x00', '\x00-\x00o\x00', '\x00\x00L\x00E\x00S\x00_\x00C\x00O\x00R\x00D\x00I\x00E\x00R\x00,\x00_\x00J\x00U\x00G\x00E\x00_\x00E\x00T\x00_\x00F\x00L\x00I\x00C\x00_\x006\x006\x008\x008\x005\x000\x00.\x00m\x00p\x004\x00\x00']
Traceback (most recent call last):
File "nrj12-0.3.py", line 86, in <module>
main()
File "nrj12-0.3.py", line 80, in main
subprocess.Popen( arguments, stdout = subprocess.PIPE).communicate()[0]
File "/usr/lib/python2.6/subprocess.py", line 623, in __init__
errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1141, in _execute_child
raise child_exception
TypeError: execv() argument 1 must be encoded string without NULL bytes, not str
Hors ligne
k3c
Re : TVDownloader: télécharger les médias du net ! [2]
@ ynad
Je ne reproduis pas ton problème
gg@gg-SATELLITE-L755:~$ python !$ http://www.nrj12.fr/replay-4203/media/video/668850-choc-en-retour.html
python nrj/plugin.video.NRJ12Replay/cherie_1.py http://www.nrj12.fr/replay-4203/media/video/668850-choc-en-retour.html
le findAll
msdl -c --no-proxy http://r.nrj.fr/mogador/web/00121585_h264_12.mp4 -s 5 -o "LES_CORDIER,_JUGE_ET_FLIC_668850.mp4"
['msdl', '-c', '--no-proxy', 'http://r.nrj.fr/mogador/web/00121585_h264_12.mp4', '-s', '5', '-o', 'LES_CORDIER,_JUGE_ET_FLIC_668850.mp4']
download [ LES_CORDIER,_JUGE_ET_FLIC_668850.mp4 ]
Host: [ 95.81.165.1:80 ] connected!
get_filesize LES_CORDIER,_JUGE_ET_FLIC_668850.mp4: stat() error
No such file or directory
http resume: no such file "LES_CORDIER,_JUGE_ET_FLIC_668850.mp4", not resuming
redirect to http://95.81.146.19/1UWasxAEJoc86jX_7_jXn_QS0jSirvn8VNXc=/mogador/web/00121585_h264_12.mp4
Host: [ 95.81.146.19:80 ] connected!
get_filesize LES_CORDIER,_JUGE_ET_FLIC_668850.mp4: stat() error
No such file or directory
http resume: no such file "LES_CORDIER,_JUGE_ET_FLIC_668850.mp4", not resuming
DL: 8413249/797617651 B -- 1% 106.5K/s ETA 03:17:4 ^CTraceback (most recent call last):
File "nrj/plugin.video.NRJ12Replay/cherie_1.py", line 86, in <module>
main()
File "nrj/plugin.video.NRJ12Replay/cherie_1.py", line 80, in main
subprocess.Popen( arguments, stdout = subprocess.PIPE).communicate()[0]
File "/usr/lib/python2.7/subprocess.py", line 746, in communicate
stdout = _eintr_retry_call(self.stdout.read)
File "/usr/lib/python2.7/subprocess.py", line 478, in _eintr_retry_call
return func(*args)
KeyboardInterrupt
gg@gg-SATELLITE-L755:~$
Je l'ai arrêté, mais il avait commencé à télécharger.
Hors ligne
ynad
Re : TVDownloader: télécharger les médias du net ! [2]
@ k3c
alors je ne comprends pas tous tes autres scripts que j'ai essayé ont fonctionnés...? je vais réessayer
mon python peut-être ?
Dernière modification par ynad (Le 11/04/2013, à 11:25)
Hors ligne
ynad
Re : TVDownloader: télécharger les médias du net ! [2]
@ k3c
j'ai réinstallé msdl
et jai toujours des erreurs mais la ligne:
msdl -c --no-proxy http://r.nrj.fr/mogador/web/00121585_h264_12.mp4 -s 5 -o "LES_CORDIER,_JUGE_ET_FLIC_668850.mp4"
apparait et si je l’exécute dans un terminal, ça charge la vidéo, il y a déjà du mieux !
Hors ligne
|
Gaara
barre de progression sur notification en root [finalisé]
Bonjour,
J'essaie de me faire un petit script qui me prévient avec une notification quand mes mises à jours sont effectuées, en utilisant unattended-upgrades.
J'ai réussi à le faire fonctionner avec yad, mais c'est pas très joli. Je voudrais donc utiliser notify-send mais ça a l'air d'être une autre histoire.
J'ai trouvé ce fil qui en parle, mais rien ne marche chez moi:
Par exemple, quand je tape ceci dans mon terminal,
sudo -s
export DISPLAY=:0
unset XAUTHORITY
sudo -u user notify-send "Essai"
ne me renvoie rien.
J'ai essayé beaucoup de choses, testé avec who pour voir quel était le display et c'est bien le 0.
Je précise que le <notify-send "mon message"> fonctionne en mode normal !
A l'heure actuelle, mon script ressemble à ça, mais ça ne fonctionne pas.
#!bin/bash
export DISPLAY=:0
export XAUTHORITY=/home/user/.Xauthority
su - user -c notify-send "mon message"
Quelqu'un aurait une idée? Merci
Dernière modification par gaara92 (Le 22/02/2014, à 22:31)
Hors ligne
Gaara
Re : barre de progression sur notification en root [finalisé]
J'ai trouvé une astuce sur cette page, mais ça ne marche pas non plus. Je pense que c'est la version de libnotify-bin de la 13.10 qui fonctionne différemment.
Hors ligne
Zakhar
Re : barre de progression sur notification en root [finalisé]
Le principe est d'envoyer le message avec le user présumé connecté.
Celui-ci aura donc le message.
Cependant, si un autre user est connecté sur :0, eh bien personne n'a de message !
"A computer is like air conditioning: it becomes useless when you open windows." (Linus Torvald)
Hors ligne
Gaara
Re : barre de progression sur notification en root [finalisé]
Merci de ta réponse,
Est-ce que en root ça correspond à un autre user?
Si oui, comment déconnecter le user root?
Et la commande
su - user -c commande
ne permet-elle pas d'exécuter la commande en user normal ?
Dernière modification par gaara92 (Le 01/02/2014, à 16:41)
Hors ligne
Zakhar
Re : barre de progression sur notification en root [finalisé]
sudo -u user commande
Oui... si l'utilisateur en session s'appelle "user" !
"A computer is like air conditioning: it becomes useless when you open windows." (Linus Torvald)
Hors ligne
Gaara
Re : barre de progression sur notification en root [finalisé]
si je comprend, pour revenir à l'utilisateur normal:sudo -u user commande -> dans le terminalsu - user -c commande -> dans un script
Sauf que aucune de ces deux commandes ne font marcher notify-send quand je suis en root !
Hors ligne
Zakhar
Re : barre de progression sur notification en root [finalisé]
Et tu as bien sûr remplacé "user" par le nom de ton user, comme ça :
sudo su -u zakhar notify-send "Test" "test"
"A computer is like air conditioning: it becomes useless when you open windows." (Linus Torvald)
Hors ligne
Gaara
Re : barre de progression sur notification en root [finalisé]
Oui, bien sûr.
Mais j'ai peut-être trouvé une solution de contournement, en installant notify-osd
Les notification s'affichent, mais sur mon deuxième écran...
Hors ligne
Zakhar
Re : barre de progression sur notification en root [finalisé]
Ah... tu avais juste omis de dire que tu avais 2 écrans.
Jamais fait de notify-send avec 2 écrans, désolé je ne peux guère aider pour ça.
"A computer is like air conditioning: it becomes useless when you open windows." (Linus Torvald)
Hors ligne
Gaara
Re : barre de progression sur notification en root [finalisé]
Bon... ça été difficile mais c'est résolu, petit bug de notify-osd en dual screen. (pour plus d'info voir ici)
Merci quand même!
Hors ligne
metalux
Re : barre de progression sur notification en root [finalisé]
Salut gaara92,
Tu pourrais partager ton script final S.T.P, il m'intéresse.
Xubuntu 14.04 LTS sur HP Pavilion t728.fr
Precise Pangolin 64 bits sur Acer aspire 5738ZG
Voyager 13.04 mise à niveau en 14.04 sur TOSHIBA Satellite C870-196.
Faîtes la mise à jour de vos P.P.A. automatiquement
Hors ligne
Gaara
Re : barre de progression sur notification en root [finalisé]
Salut metalux,
Mon script est en fait super simple. Avec notify-osd installé, les notifications s'affichent en root, mais c'est la commande notify-send que j'ai utilisé. (qui doit désormais passer par notify-osd je suppose)
export DISPLAY=:0.0
notify-send --expire-time=50000 -i /home/guillaume/.icons/NITRUX/apps/48/ubuntu-tweak.png " " "Mises a jour effectuées"
mplayer /usr/share/sounds/KDE-K3B-Insert-Medium.ogg
Hors ligne
metalux
Re : barre de progression sur notification en root [finalisé]
Oui, pour ça j'avais compris, c'est juste comment tu fais pour le relier à unattended-upgrades. Ou est-ce que tu le mets ce script?
Xubuntu 14.04 LTS sur HP Pavilion t728.fr
Precise Pangolin 64 bits sur Acer aspire 5738ZG
Voyager 13.04 mise à niveau en 14.04 sur TOSHIBA Satellite C870-196.
Faîtes la mise à jour de vos P.P.A. automatiquement
Hors ligne
Gaara
Re : barre de progression sur notification en root [finalisé]
C'est un script à part, dans mon répertoire majauto. J'ai modifié unattended-upgrade pointant vers ce fichier, (en fait deux script: un pour me dire que la maj démarre, l'autre pour me dire que c'est installé)
sudo kate /usr/bin/unattended-upgrade
1-) entre les lignes 50 et 60
import gettext
from gettext import gettext as _
# SCRIPT MAISON
# MISE A JOUR EN COURS...
import subprocess
subprocess.call('su - guillaume -c "DISPLAY=:0 /home/guillaume/majauto/message_ech"', shell=True)
# FIN DU SCRIPT MAISON
# the reboot required flag file used by packages
REBOOT_REQUIRED_FILE = "/var/run/reboot-required"
2-) entre les lignes 646 et 654. Edit: l'inconvénient de cette méthode, c'est que le script n'est plus appelé quand on désactive la notification par mail. Il faut donc faire autrement.
logging.debug("Sending mail with '%s' to '%s'" % (logfile_dpkg, to_email))
# SCRIPT MAISON SUCCES DES MAJ
import subprocess
subprocess.call('su - guillaume -c "DISPLAY=:0 /home/guillaume/majauto/message_eff"', shell=True)
# FIN DU SCRIPT MAISON
if os.path.isfile(REBOOT_REQUIRED_FILE):
C'est mon bricolage, je ne sais pas si c'est optimal, mais ça marche !
PS: Au départ je voulais un message pour me prévenir d'un échec éventuel, mais j'ai pas réussi. J'ai donc changé en "Mise à jour en cours"
Dernière modification par gaara92 (Le 25/02/2014, à 00:37)
Hors ligne
metalux
Re : barre de progression sur notification en root [finalisé]
Merci.
Je rajouterai un lien vers la discussion sur l'aide de la prochaine version de maj_auto.
Xubuntu 14.04 LTS sur HP Pavilion t728.fr
Precise Pangolin 64 bits sur Acer aspire 5738ZG
Voyager 13.04 mise à niveau en 14.04 sur TOSHIBA Satellite C870-196.
Faîtes la mise à jour de vos P.P.A. automatiquement
Hors ligne
Gaara
Re : barre de progression sur notification en root [finalisé]
D'accord, et si quelqu'un trouve une amélioration (notify + barre de progression par exemple), je suis preneur !
Hors ligne
Gaara
Re : barre de progression sur notification en root [finalisé]
J'ai un peu avancé pour la barre de progression. Je n'utilise plus notify-send, du moins pas pour la barre.
Le script suivant (en GtkPython) affiche une notification, et une barre de progression.
#!/usr/bin/env python
# -*- Encoding: Latin-1 -*-
import pygtk
pygtk.require('2.0')
import gtk, gobject
import subprocess
# Update the value of the progress bar so that we get some movement
def progress_timeout(tempslimite):
if tempslimite.activity_check.get_active():
tempslimite.pbar.pulse()
else:
# Calculate the value of the progress bar using the value range set in the adjustment object
new_val = tempslimite.pbar.get_fraction() + 0.02
if new_val > 1.0:
# Appel d'un script bash et fermeture de la fenêtre quand la barre est terminée
subprocess.call('su - <user> -c "DISPLAY=:0 /chemin/script/bash/"', shell=True)
gtk.main_quit()
exit()
# new_val = 0.0
# On fixe la nouvelle valeur
tempslimite.pbar.set_fraction(new_val)
# Cette fonction etant une fonction de temporisation, on
# renvoie TRUE afin qu'elle puisse encore etre appelee
return True
class ProgressBar:
# Fonction de rappel qui active ou desactive l'affichage du texte
# dans la coulisse de la barre de progression
# def modif_affich_texte(self, widget, data=None):
# if widget.get_active():
# self.barreprogression.set_text("Installation")
# else:
# self.barreprogression.set_text(""
# Fonction de rappel qui active ou desactive le mode "activite" de la barre de progression
def toggle_activity_mode(self, widget, data=None):
if widget.get_active():
self.pbar.pulse()
else:
self.pbar.set_fraction(0.0)
# Liberation de la memoire reservee et retrait de la temporisation
def destroy_progress(self, widget, data=None):
# gobject.source_remove(self.timer)
self.timer = 0
gtk.main_quit()
def __init__(self):
# Création fenetre principale
self.window = gtk.Window(gtk.WINDOW_POPUP)
self.window.set_resizable(True)
self.window.connect("destroy", self.destroy_progress)
# Taille et position de la fenetre principale
self.window.move(1550,38)
# Creation de la fenetre secondaire, qui enferme l'image et la barre de progression
vbox = gtk.VBox(False, 5)
vbox.set_border_width(10)
self.window.add(vbox)
# Couleur de la fenetre
fenetre=self.window
map = fenetre.get_colormap()
colour = map.alloc_color("#F3F3F3") # gris clair
style = fenetre.get_style().copy()
style.bg[gtk.STATE_NORMAL] = colour
fenetre.set_style(style)
# Chargement de l'image
image = gtk.Image()
image.set_from_file("/home/guillaume/majauto/maj.png")
image.show()
# Ajout de l'image dans la fenetre et affichage
vbox.add(image)
vbox.show_all()
# Centrage et taille de la barre
align = gtk.Alignment(0, 1, 1, 0)
vbox.pack_start(align, False, False, 5)
align.show()
# Creation de la barre
self.pbar = gtk.ProgressBar()
align.add(self.pbar)
self.pbar.show()
# Texte dans la barre
self.pbar.set_text("Installation...")
# Fonction de rappel temporisee qui actualisera la valeur de la barre de progression
self.timer = gobject.timeout_add (100, progress_timeout, self)
# Ligne de separation
# separator = gtk.HSeparator()
# vbox.pack_start(separator, False, False, 0)
# separator.show()
# Bouton pour afficher la barre bleue de gauche à droite
table = gtk.Table(2, 2, False)
vbox.pack_start(table, False, True, 0)
# affichage de la colonne
table.show()
# Barre d'avancement bleue
self.activity_check = check = gtk.CheckButton("Mode Activité")
table.attach(check, 0, 1, 1, 2, gtk.EXPAND | gtk.FILL, gtk.EXPAND | gtk.FILL, 5, 5)
check.connect("clicked", self.toggle_activity_mode)
check.show()
# Affichage de la fenetre principale
self.window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
ProgressBar()
main()
J'utilise cette image (un simple screen de notity-osd en png), qui colle à mon theme.
La position de la fenêtre est aussi à modifier, en fonction de la taille de l'écran.
Quand la barre est au bout, le script renvoie à un script shell qui utilise notify-osd, prévenant que la mise à jour est terminée. Puis le script s'arrête.
J'ai volontairement laissé quelques fonctions en commentaire, libre de les activer ou non.
Je pense appeler ce script avec unattended-upgrade vers la ligne 51, pour qu'il puisse démarrer en même temps.
Le prochain challenge est de lier ce script à unattended-upgrade, pour avoir une progression réelle. Est-il possible de jouer avec le .pid ou le .progress que génère unattended-upgrade?
# progress information is written here
PROGRESS_LOG = "/var/run/unattended-upgrades.progress"
PID_FILE = "/var/run/unattended-upgrades.pid"
Sinon, comment faire ?
N'étant pas développeur, il y a sans doute des améliorations a faire, car je n'ai fait que prendre des morceaux de tutos ça et là. Et ce n'est que la partie graphique.
Dernière modification par gaara92 (Le 13/02/2014, à 15:11)
Hors ligne
Gaara
Re : barre de progression sur notification en root [finalisé]
Alors voilà, le script est prêt pour afficher la barre de progression d'unattended-upgrade. (paquet présent dans les dépôts, qui permet de faire les mises à jour de sécurité automatiquement).
J'en profite pour vous donner le lien de metalux, qui a préparé un script (bash) qui permet d'utiliser unattended-upgrade pour les ppa. Le code initial d'unattended est prévu pour envoyer un mail lorsque les maj sont faites, mais comme je préfère une notification en local, j'ai mis les mains dans le cambouis
Le scrit de la notification: Avant toute chose, il faut savoir qu'il interagit avec le fichier .progress ( /run/unattended-upgrades.progress ) que génère unattended.
Donc pour essayer le script, il faut changer la valeur du texte en root (sans changer les mots). Ex: Progression : 0.0 % (menu) => Progression : 10.0 % (menu)
Quand la valeur de 92% est atteinte, le script renvoie à un petit bash (celui ci utilise notify-osd) qui indique que c'est terminé.
Pour l'image, voir le post précédent, il devrait y avoir un lien. Mais bon c'est à reconfigurer selon vos goûts et couleur !
#!/usr/bin/env python
# -*- Encoding: Latin-1 -*-
import pygtk
pygtk.require('2.0')
import gtk
import gobject
import subprocess
import time
# Barre de progression
def progress_timeout(barreProgression):
# initialisation des variables
perc = 0 # pourcentage réel du log d'unattended
pourcent = 0 # pourcentage affiché sur la barre
# création initialisation du fichier .progress, car il n'est pas présent lors de l'allumage
fichierini = open("/run/unattended-upgrades.progress", "w")
fichierini.write("Progression : 0.0 % (menu)")
fichierini.close()
# animation de la barre
if barreProgression.activity_check.get_active():
barreProgression.pbar.pulse()
else:
############## Récupérer pourcentage d'unattended sous forme d'une variable ##################
time.sleep (2)
while pourcent < 1:
# ouvrir fichier .progress généré par unattended-upgrade (ex: Progression : 92.3077 % (menu))
fichier = open("/run/unattended-upgrades.progress", "r")
# lecture du texte en ignorant les 14 premiers caracteres
t = fichier.read(14)
# lecture du pourcentage (chaine de caractere)
t= fichier.read(5)
# fermeture du .progress
fichier.close()
# convertion de la chaine en nombre
unom = float(t)
# calcul du pourcentage
perc = float(unom/100)
################ Boucles d'affichage de la barre de progression #############################
# forcer le rafraichissement de l'affichage
while gtk.events_pending():
gtk.main_iteration()
# augmentation fluide de la barre
while perc > pourcent:
time.sleep(0.01)
pourcent = pourcent+0.002
if pourcent > 0.92:
pourcent = 1
print "pourcent milieu =",pourcent
while gtk.events_pending():
gtk.main_iteration()
barreProgression.pbar.set_fraction(pourcent)
# finir la boucle quand le log d'unattended atteint 92% au moins
if perc >= 0.92:
while gtk.events_pending():
gtk.main_iteration()
time.sleep(2)
gtk.main_quit()
subprocess.call('su - guillaume -c "DISPLAY=:0 /home/guillaume/majauto/message_eff"', shell=True)
exit()
if perc < 1:
#print "perc=",perc
#print "pourcent=",pourcent
#print "------------Nouvelle Boucle Principale--------------"
time.sleep(0.1)
else:
barreProgression.pbar.pulse()
return True
##################################FIN DE LA BOUCLE DE LA BARRE DE PROGRESSION##############################
# class est incluse dans l'objet: ces sont des boîtes qui servent à regrouper des éléments communs
class ProgressBar:
# Fonction de rappel qui active ou desactive le mode "activite" de la barre de progression
def toggle_activity_mode(self, widget, data=None):
self.pbar.set_fraction(0.0)
print "remise à 0 du %"
def __init__(self):
# Création fenetre principale
self.window = gtk.Window(gtk.WINDOW_POPUP)
# Position de la fenetre principale
self.window.move(1561,32)
# Creation de la fenetre secondaire, qui enferme l'image et la barre de progression
vbox = gtk.VBox(False, 5)
vbox.set_border_width(10)
self.window.add(vbox)
# Couleur de la fenetre
fenetre=self.window
map = fenetre.get_colormap()
colour = map.alloc_color("#F3F3F3") # gris-clair/blanc
style = fenetre.get_style().copy()
style.bg[gtk.STATE_NORMAL] = colour
fenetre.set_style(style)
# Chargement de l'image
image = gtk.Image()
image.set_from_file("/home/guillaume/majauto/maj.png")
image.show()
# Ajout de l'image dans la fenetre et affichage
vbox.add(image)
vbox.show_all()
# Ligne de separation
separator = gtk.HSeparator()
vbox.pack_start(separator, False, False, 0)
separator.show()
# Centrage et taille de la barre
align = gtk.Alignment(0, 1, 1, 0)
vbox.pack_start(align, False, False, 5)
align.show()
# Creation de la barre
self.pbar = gtk.ProgressBar()
align.add(self.pbar)
self.pbar.show()
# Texte dans la barre
self.pbar.set_text("Installation... ")
# Fonction de rappel temporisee qui actualisera la valeur de la barre de progression
self.timer = gobject.timeout_add (100, progress_timeout, self)
# Pour afficher la barre bleue de gauche à droite
table = gtk.Table(2, 2, False)
vbox.pack_start(table, False, True, 0)
# print "est passé par là 5"
# affichage de la colonne
table.show()
# Bouton du Mode activité
self.activity_check = check = gtk.CheckButton("Mode Activité")
# table.attach(check, 0, 1, 1, 2, gtk.EXPAND | gtk.FILL, gtk.EXPAND | gtk.FILL, 5, 5)
# check.connect("clicked", self.toggle_activity_mode)
# check.show()
# Affichage de la fenetre principale
self.window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
ProgressBar()
main()
La chose qui est en cours: intégrer ce script à unattended (écrit lui aussi en python) , car pour l'instant la commande que j'ai trouvé bloque le script unattended, car il attend que le second se termine. Donc .progress n'est pas mis à jour.
Il faudrait une commande qui permet de lancer deux scripts python en parallèle, je suis sur quelques pistes.
Dernière modification par gaara92 (Le 16/02/2014, à 16:24)
Hors ligne
Gaara
Re : barre de progression sur notification en root [finalisé]
Ca semble être sur le point d'être résolu !
Pour lancer le "notif_prog_bar.py" il faut ajouter les lignes suivantes dans le script /usr/bin/unattended-upgrade, au début, après les imports des modules.
p = subprocess.Popen(['python', '/home/guillaume/majauto/notif_prog_bar.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.flush()
Il y a une autre chose à faire, car unattended ne doit pas quitter avant que la barre ne quitte: IOError: [Errno 32] Relais brisé (pipe)
1) ajouter "import time" dans les imports, tout au début
2) vers la ligne 1050, après > logging.info(_("Packages that will be upgraded: %s" % pkgs))
ajouter > time.sleep(5)
Je teste en dur demain pendant la maj.
Dernière modification par gaara92 (Le 16/02/2014, à 19:37)
Hors ligne
Gaara
Re : barre de progression sur notification en root [finalisé]
Suite du test en dur: rien ne s'est affiché, problème de display. (j'aurais du m'en douter)
Le log de cron.daily reçu par mail est le suivant:
/etc/cron.daily/apt:
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:57: GtkWarning: could not open display
warnings.warn(str(e), _gtk.Warning)
/home/guillaume/majauto/progressbarV3.py:106: Warning: invalid (NULL) pointer instance
self.window = gtk.Window(gtk.WINDOW_POPUP)
/home/guillaume/majauto/progressbarV3.py:106: Warning: g_signal_connect_data: assertion 'G_TYPE_CHECK_INSTANCE (instance)' failed
self.window = gtk.Window(gtk.WINDOW_POPUP)
/home/guillaume/majauto/progressbarV3.py:118: GtkWarning: IA__gdk_screen_get_default_colormap: assertion 'GDK_IS_SCREEN (screen)' failed
map = fenetre.get_colormap()
Traceback (most recent call last):
File "/home/guillaume/majauto/progressbarV3.py", line 177, in <module>
ProgressBar()
File "/home/guillaume/majauto/progressbarV3.py", line 119, in __init__
colour = map.alloc_color("#F3F3F3") # gris-clair/blanc
AttributeError: 'NoneType' object has no attribute 'alloc_color'
Sinon pas de soucis, la maj est bien installée.
Dernière modification par gaara92 (Le 18/02/2014, à 11:23)
Hors ligne
Gaara
Hors ligne
Totor
Re : barre de progression sur notification en root [finalisé]
D'accord, et si quelqu'un trouve une amélioration (notify + barre de progression par exemple), je suis preneur !
je pense que ceci peut répondre à ta demande ...
-- Lucid Lynx --
Hors ligne
Gaara
Re : barre de progression sur notification en root [finalisé]
oui, j'avais vu ton script, mais trop tard, je m'étais mis à écrire le miens...
Hors ligne
|
I am working on a project to take screenshots of desktop and upload images to a server I want to develop a python app, when user starts that app it will start taking screenshots in random interval like between 2-5 min of interval I have the code that will take screenshot and I have tested it on ubuntu it is working properly. Code to capture screenshot
import gtk.gdk
import time
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
print "The size of the window is %d x %d" % sz
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
ts = time.time()
filename = "screenshot"
filename += str(ts)
filename += ".png"
if (pb != None):
pb.save(filename,"png")
print "Screenshot saved to "+filename
else:
print "Unable to get the screenshot."
I want to run this code in random interval of 2-5 min how can I develop a script that will run this code in thread.
|
malbo
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
Ou alors je n'ai pas trouvé comment faire...
Il fallait aller dans le Bios au démarrage et sélectionner le démarrage sur le support d'installation de Ubuntu "sans" UEFI. Comme tu n'y connaissais rien en UEFI, tu as laissé démarrer le PC sur le support sans intervenir, il s'est placé par défaut en mode UEFI et tu t'es retrouvé avec cette installation bancale. J'indique dans ce tuto comment savoir si on est bien en mode Bios ou en mode UEFI : http://forum.ubuntu-fr.org/viewtopic.ph … 1#p7282231
Utilise ce tuto la prochaine fois avant d'installer Ubuntu.
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
YannUbuntu
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
Bonjour
une idée de ce que je "risque" en laissant tout comme ça ?
à priori pas grand-chose, j'ai déjà vu un autre cas fonctionnel comme vous (grub-efi sans disque GPT). Faites seulement attention à ne pas effacer malencontreusement votre partition EFI (sda2).
Dernière modification par YannUbuntu (Le 12/07/2012, à 17:13)
Hors ligne
Coolmic29
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
Le lien est à corriger -
B) redémarrer le PC sur le liveCD de Ubuntu
Il faut télécharger l'ISO officiel 64 bits ubuntu-12.04-desktop-i386.iso.
Très bon Tuto merci
Ubuntu 12.04_64 bits XPC Shuttle SG45H7 Core 2 Duo E8400 3GHz
Ubuntu 13.10_64 bits Portable VAIO core I5 carte vidéo ATI
Hors ligne
malbo
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
Coolmic29,
J'ai corrigé : ubuntu-12.04.1-desktop-amd64.iso (au lieu de ubuntu-12.04-desktop-i386.iso). Merci pour ta remarque.
J'espère que ce tuto "prudent" va devenir obsolète un jour parce que Ubuntu saura s'installer automatiquement sans écraser les glaouis de Windows.
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
YannUbuntu
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
Bonjour
J'espère que ce tuto "prudent" va devenir obsolète un jour parce que Ubuntu saura s'installer automatiquement sans écraser les glaouis de Windows.
Ca devrait être déjà le cas pour 12.04 (le bug #769669 a été corrigé avant la sortie de Precise).
EDIT: ceci dit, le tuto reste intéressant pour apprendre à ne pas mélanger plusieurs partitions EFI
Dernière modification par YannUbuntu (Le 27/08/2012, à 10:01)
Hors ligne
malbo
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
YannUbuntu,
J'avais vu que ce bug est sensé être corrigé mais je reste sceptique. J'ai pu voir dans quelques fils que certains avaient pu installer de façon "normale" (sans créer une partition EFI spéciale pour Ubuntu) mais j'ai l'impression qu'on manque de preuves que le bug est effectivement corrigé et que la cohabitation dans la partition EFI préinstallée ne pose plus de problème. Tu as des liens vers des discussions probantes sur le sujet (sur ce forum ou d'autres forum Ubuntu) ? Je veux dire des discussions avec des Boot-Info où on voit clairement que tout s'est bien passé...
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
malbo
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
@YannUbuntu,
Il apparaît que l'installation avec une partition EFI dédiée à Ubuntu qui est trop loin du début du disque pose problème d'après ce cas de Mateoz (j'en ai vu d'autres) : http://forum.ubuntu-fr.org/viewtopic.ph … #p10548501
On peut constater que Boot-Repair est efficace pour installer Ubuntu dans la même partition EFI que Windows puisqu'on voit ça dans le Boot-Info de Mateoz après réparation par Boot-Repair :
sda3: __________________________________________________________________________
File system: vfat
Boot sector type: Windows 7: FAT32
Boot sector info: No errors found in the Boot Parameter Block.
Operating System:
Boot files: /efi/Boot/bootx64.efi /efi/ubuntu/grubx64.efi
C'est à dire, dans la partition EFI : le chargeur d'amorçage pour Win7 (/efi/Boot/bootx64.efi) et le chargeur d'amorçage pour ubuntu (/efi/ubuntu/grubx64.efi)
Cela ne répond pas à ma question du post #31 (je m'intéresse aux installations réussies du premier coup) mais ça montre que Boot-Repair fait une réparation correcte.
Dernière modification par malbo (Le 28/08/2012, à 14:19)
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
YannUbuntu
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
Je confirme.
D'ailleurs:
- tu devrais ajouter dans le post#1 A)2) de ce tuto qu'il faut, par précaution, placer la partition EFI en début de disque (de façon à ce qu'elle soit entièrement contenue dans les 100 premiers Go du disque)
- ce problème survient aussi pour un /boot séparé.
- je pense qu'il s'agit d'une régression de GRUB 12.04: https://bugs.launchpad.net/bugs/1030887
EDIT: dans le post#1 tu indique de créer l'ESP en FAT16, mais il est aussi possible de la créer en FAT32. D'ailleurs il me semble que le format préconisé par le standard UEFI est FAT32.
Dernière modification par YannUbuntu (Le 28/08/2012, à 14:43)
Hors ligne
malbo
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
- tu devrais ajouter dans le post#1 A)2) de ce tuto qu'il faut, par précaution, placer la partition EFI en début de disque (de façon à ce qu'elle soit entièrement contenue dans les 100 premiers Go du disque)
J'allais te répondre que le bug en question n’apparaît pas dans le cas de joeypa13 : http://forum.ubuntu-fr.org/viewtopic.ph … 1#p8282351
dont l'installation l'installation de Ubuntu a été faite entièrement au delà de 250 Go par rapport au début du disque dur, mais je viens de me rendre compte que joeypa13 avait installé Ubuntu 11.10 alors que tu as bien noté que ce bug #1030887 est une régression de Ubuntu 12.04...
Edit : j'ai trouvé le cas de Xord3 : http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9547651
Tu noteras que toute son install de Ubuntu, partition EFI pour Ubuntu comprise, se situe en fin de son disque dur de 1000 Go
Dans son cas, le bug #1030887 ne se produit pas, bien qu'il s'agisse de Ubuntu 12.04.
Dernière modification par malbo (Le 28/08/2012, à 16:13)
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
YannUbuntu
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
Pour le FAT16, je viens de retrouver pourquoi tu le conseilles http://forum.ubuntu-fr.org/viewtopic.ph … 1#p8791031
Edit : j'ai trouvé le cas de Xord3 : http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9547651
Tu noteras que toute son install de Ubuntu, partition EFI pour Ubuntu comprise, se situe en fin de son disque dur de 1000 Go
Dans son cas, le bug #1030887 ne se produit pas, bien qu'il s'agisse de Ubuntu 12.04.
Bien vu, c'est un cas où /boot et /boot/efi sont à >900Go du début du disque.
Le blocage avec /boot/efi trop loin n'est donc pas systématique pour tous les PCs (c'est d'ailleurs la même chose pour le blocage avec /boot trop loin ).
Mais comme certains PCs sont affectés, il vaut mieux par précaution conseiller de mettre /boot et /boot/efi en début de disque.
Dernière modification par YannUbuntu (Le 28/08/2012, à 17:43)
Hors ligne
YannUbuntu
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
Ces blocages (pour /boot éloigné, comme pour /boot/efi éloigné) sont à mon avis soit dûs soit au BIOS (dans ce cas on ne peut rien faire, à part mettre la partition en début de disque), soit à une régression de GRUB (dans ce cas on peut aider à améliorer GRUB en soumettant un rapport de bug).
Dans l'éventualité où ça serait une régression, il faut qu'on surveille les cas où ça bloque sur 12.04 après migration depuis 11.10 (ou 10.04). N'hésite pas à me prévenir si tu en vois un!
Dernière modification par YannUbuntu (Le 28/08/2012, à 17:45)
Hors ligne
marco1492
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
Merci beaucoup pour ce tutorial qui m'a grandement aidé.
J'ai regardé les différents forums. C'est le seul tutorial qui donne la quasi totalité de la solution pour installer Ubuntu sur un PC avec la nouvelle génération de BIOS-UEFI.
Je suis resté longtemps (plus d'une journée à chercher et réfléchir) à l'étape démarrer sur le CDlive Ubuntu 12.04.1 et vérifier que vous avez booté en UEFI.
J'ai trouvé la combinaison lors du boot de l'ordinateur. Il s'agit de :
1) Placer le CDlive Ubuntu 12.04.1 dans le lecteur DVD-CD de l'ordinateur
2) Rebooter l'ordinateur en maintenant appuyer la touche "Echap".
Ce qui fait apparaître un menu UEFI de boot avec les options suivantes :
- P0 : Windows Boot Manager (il s'agit de la partition UEFI de boot, créée par le fabricant du PC),
- P2 : <le lecteur DVD/CD>
- UEFI : <le lecteur DVD/CD>.
3) Choisir UEFI : <le lecteur DVD/CD>.
Je précise :
- que j'ai acheté l'ordinateur portable récemment (fin août 2012). C'est un ASUS Série Premium R500VD-SX086V (Core i5), avec UEFI AMI BIOS American Megatrends;
- que ni ASUS, ni AMI -American Megatrends mettent à disposition ni un manuel utilisateur du BIOS/UEFI, ni une FAQ sur comment utiliser ce BIOS/UEFI ou comment démarrer un PC avec BIOS/UEFI.
Encore merci.
Très cordialement.
Marc
Hors ligne
malbo
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
@marco1492
Merci pour ce retour.
Aurais-tu l'amabilité de répondre à cette demande : http://doc.ubuntu-fr.org/tutoriel/boot-info
Cela permettrait d'enrichir notre expérience dans le domaine. En particulier sur le problème évoqué dans les posts qui précèdent le tien.
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
malbo
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
YannUbuntu ,
Un cas d'installation avec des fichiers de Boot pour Ubuntu éloignés du début du disque dur qui ne présente pas le bug (Boot-Info en bas du post #1 du lien) : http://forum.ubuntu-fr.org/viewtopic.ph … #p10580891
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
YannUbuntu
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
Merci pour le lien. Ca confirme donc que ce bug n'est pas systématique. Tout comme le bug du /boot éloigné.
Ce que je cherche surtout ce sont des régressions (ça marche avec une ancienne version de GRUB, mais ça plante après une MAJ de GRUB).
Dernière modification par YannUbuntu (Le 03/09/2012, à 19:19)
Hors ligne
marco1492
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
Voici le rapport BootInfo sur mon PC portable Asus i5 64 bits avec BIOS/EFI :
http://paste.ubuntu.com/1181051/
que je poste avec plaisir en accord avec les bons principes de la communauté Gnu-Linux et celle d'Ubuntu en particulier, que je partage et j'apprécie depuis 1998. Ce rapport BootInfo généré est à la fois très riche en information et très intéressant.
Par contre, j'ai exécuté Boot-Repair en mode 'mise à jour du menu Grub EFI' et depuis je n'arrive plus à booter sur Windows 7.
En effet, lors du reboot de mon PC, par défaut, j'ai bien le menu grub-efi. Or, si les options Linux, du menu grub-efi, fonctionnent correctement, par contre, la première (et non les dernières comme nous l'explique YannUbuntu) option de 'Boot sur Windows 7' (générée lors de l'installation d'Ubuntu 12.04.1, et par la suite Boot-repair) me renvoie le message d'erreur "error : invalid EFI file path" et l'exécution du boot BIOS/EFI s'arrête là.
Idem lors du reboot du PC quand je maintiens appuyée la touche "Echap", le menu UEFI de boot apparaît :
- P1 : Ubuntu (avec BIOS/UEFI)
- P0 : Windows Boot Manager (il s'agit de la partition UEFI de boot, créée par le fabricant du PC),
- P2 : <le lecteur DVD/CD>
- etc ...
Quand je choisis l'option "P0 : Windows Boot Manager" (qui est l'option d'origine avant l'installation de Ubuntu 12.04.1 sur le disque), il me renvoit aussi le message d'erreur "error : invalid EFI file path" et l'exécution du boot BIOS/EFI s'arrête là.
Concernant l'exécution de Boot-Repair sur ma configuration PC portable Asus i5 64 bits et en particulier BIOS/EFI, je précise :
- que lors de la génération du rapport BootInfo, j'ai vu qu'il était produit par Boot-Repair que j'ai utilisé fréquemment et sans souci sur un Ubuntu 10.04.3 et un netbook eeePC Asus avec Bios ancienne génération. Boot-Repair me permettait de nettoyer le menu Grub (Bios) et réduire les options de ce menu;
- que j'ai lu au préalable et attentivement les pages Web publiées par YannUbuntu le principal contributeur à BootRepair et vérifié sur ces pages Web que Boot-Repair est compatible avec ma configuration PC i5 64 bits avec BIOS/EFI.
Autrement dit, tout va bien sur Ubuntu12.04.1, par contre, je n'arrive plus à booter Windows 7. Je continue à chercher sur les forums. Pour le moment, je n'ai rien cassé sur la 2è partition 'unknow type' (dédiée UEFI), même si çà me démange ! J'ai vu hier après-midi votre tutorial "malbo" de 2011 où vous expliquez la suppression de la fameuse 2ème partition 'unknow type' (dédiée UEFI), puis la reconstruction très complexe de recréation de cette 'unknow type' (dédiée UEFI). Je ne me sens pas capable de procéder à une telle reconstruction. C'est pourquoi, j'avance prudemment (cf. le titre de votre tutorial 'Installation prudente de Ubuntu dans un PC UEFI') en recherchant sur les forums et surtout en m'interdisant de supprimer :
- la 2ème partition 'unknow type' (dédiée UEFI),
- la 1ère partition 'partition de boot d'origine dont le drapeau n'est plus sur "boot",
- ainsi que la 3è partition 'Windows 7 OS'.
A noter que je n'ai trouvé aucune documentation officielle et utile concernant EFI sur les sites Web Asus, AMI, Microsoft, etc ...; c'est navrant !!! Seuls les contributions précieuses sur les forums permettent d'avancer pas à pas.
Encore merci pour votre tutorial 'Installation prudente de Ubuntu dans un PC UEFI'.
Très cordialement
Marc
Hors ligne
YannUbuntu
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
Bonjour Marco,
- avant d'installer Ubuntu, aviez-vous accès à Seven et XP? si oui, comment se faisait le choix? (deviez-vous modifier quelquechose dans le BIOS?)
- après avoir installé Ubuntu, qu'observiez-vous au redémarrage du pc? à quels systèmes aviez-vous accès, et comment ?
- maintenant (après avoir utilisé la Réparation Recommandée de Boot-Repair):
quand vous choisissez l'entrée "P1 : Ubuntu (avec BIOS/UEFI)" , le menu GRUB affiche plusieurs entrées, dont:
Ubuntu, avec Linux 3.2.0-30-generic
"Windows 7 (loader) (on /dev/sda3)"
"Windows Recovery Environment (loader) (on /dev/sda4)"
"Windows NT/2000/XP (on /dev/sdb7)"
"Windows bootmgfw.efi.bkp, generated by Boot-Repair"
"Windows memtest.efi, generated by Boot-Repair"
"Boot bootx64.efi.bkp, generated by Boot-Repair"
Parmi celles-ci, lesquelles fonctionnent? lesquelles ne fonctionnent pas?
Dernière modification par YannUbuntu (Le 03/09/2012, à 21:18)
Hors ligne
raptor2003
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
@malbo Petit up vers un topic: http://forum.ubuntu-fr.org/viewtopic.php?id=1032691
Hors ligne
chel
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
bonsoir malbo,
j'avais déjà posté le 3 septembre à ce sujet et mis en résolu, voir http://forum.ubuntu-fr.org/viewtopic.php?pid=10632411 , mais tout en précisant que cela ne me satisfaisait pas. J'ai depuis trouvé cette discussion qui est à mon avis la plus pointue sur le sujet. J'ai donc reformaté tout mon disque dur (en fait supprimé toutes mes partitions), réinstallé windows7 en uefi (ça marche). Et j'ai suivi à la lettre la procédure d'installation de ubuntu décrite dans ce topic. Il y a juste un hic:
la création d'une partition sda4 fat16 après d'autres partitions (windows) de plus de 100Go entraîne un adressage trop élévé pour être lu dans le boot sector de la partition. idem sda7 fat32 que j'avais crée en vue de partager avec windows un répertoire www pour xampp. voir mon paste bin 1197593. On peut le vérifier ainsi: j'ai reformaté puis remonté mon sda7 en ntfs et celà ne pose plus de problème (pastebin 1197661).
Maintenant que faire pour que mon sda4 apparaisse en file system: bios boot partition, puisque apparemment c'est la config type qui semble marcher.
Je précise quand même je peux accéder sans problème aux deux systèmes en faisant F12 (carte mère gigabyte B75M dual bios efi) juste au démarrage ce qui m'offre un multi boot système de remplacement.
Merci de ton attention
Hors ligne
picolo-84
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
Merci,
et comment ce fait-il que sur ce site D'Ubuntu qui est officielle, dans le tutoriel, premier paragraphe, pour les débutant, ici: http://doc.ubuntu-fr.org/efi on conseille d'installer Ubuntu-Secure-Remix 64bits qui n'ai pas officielle ?
Je comprends pas, en même temps il faut pas l'installé, cars on m'a dit que je risquerais d'avoir des surprise, et il est indiqué dans le tutoriel,
Je ne sais vraiment plus ou donner de la tête.
Dernière modification par picolo-84 (Le 30/10/2012, à 23:53)
Hors ligne
YannUbuntu
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
Bonne remarque, je viens de modifier le paragraphe en question pour expliquer le pourquoi de ce conseil.
Oui il faut se méfier des ISO ou programmes non officiels.
Ubuntu-Secure-Remix n'est pas officiel (il n'est pas créé par Canonical, il est créé par moi-même), mais:
- il diffère très peu de l'ISO officielle (voir différences ici), seuls 3 logiciels (libres) ont été ajoutés, donc pas de surprise
- et est utilisé par plusieurs milliers de personnes sans soucis depuis ~2 ans.
Dans le cas de l'UEFI, vous serez probablement amené à utiliser Boot-Repair, qui est aussi développé par moi-même A vous de juger si je suis digne de confiance ou pas...
Hors ligne
pinparasol
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
Bonsoir Malbo,
Merci pour toute la doc et les infos que tu as mis en ligne, cela m'a beaucoup aidé.
Je découvre l'Uefi, je commence à comprendre et j'ai 2 questions:
1- pourquoi conseilles-tu de créer une partition FAT-RESERVE au lieu de juste copier tous les dossiers/fichiers de la FAT32 uefi sur une clé usb ou un autre support ?
2- Dans un autre [Tuto] "Installation prudente de Ubuntu ...", tu as marqué:
"il faudra naviguer jusqu'au fichier bootmgfw.efi qui se trouve dans le chemin /EFI/Microsoft/Boot/bootmgfw.efi et donner un nom à l'entrée créée".
Que veut dire : "donner un nom à l'entrée créée" ?
Merci de bien vouloir m'éclairer.
Nota: tu as raison je me m'étais trompé de discussion, j'avais trop d'onglets d'ouverts. Désolé.
Hors ligne
malbo
Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI
pinparasol,
Ce tuto a été écrit il y a un an et demie à une époque où Ubuntu s'installait de façon catastrophique dans un ordi préinstallé Windows. A l'heure actuelle, Ubuntu s'installe toujours comme une bouse dans un ordi préinstallé Windows (rapport de Bug #807801) mais au moins il ne saccage plus la partition EFI. Ce tuto est donc obsolète comme je l'ai d’ailleurs rajouté dans l'intro du post #1.
Cela étant posé, ton idée de copier les dossiers/fichiers de la FAT32 uefi sur une clé usb ou un autre support doit fonctionner.
Pour ta question sur "donner un nom à l'entrée créée", il s'agissait de configurer "à la main" le système UEFI : cette procédure est toujours utilisable sur des ordi équipés d'un système UEFI vieillissant mais là encore, tu t'intéresses à une procédure obsolète puisque j'ai écrit en caractères gras un peu au-dessus : "La partie ci-après qui décrit la configuration à la main de l'UEFI n'est pas nécessaire dans le cas d'un système UEFI performant : la création des entrées est alors faite automatiquement par le système UEFI"
En conclusion, je te prie d'arrêter de t'intéresser à ce tuto obsolète sauf si tu as de bonnes raisons de le faire.
Dernière modification par malbo (Le 13/06/2013, à 08:32)
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
|
Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) areN-dimensional. Matrix objects are a subclass of ndarray, so they inherit allthe attributes and methods of ndarrays.
The main advantage of numpy matrices is that they provide a convenient notationfor matrix multiplication: if a and b are matrices, then a*b is their matrixproduct.
import numpy as np
a=np.mat('4 3; 2 1')
b=np.mat('1 2; 3 4')
print(a)
# [[4 3]
# [2 1]]
print(b)
# [[1 2]
# [3 4]]
print(a*b)
# [[13 20]
# [ 5 8]]
Both matrix objects and ndarrays have .T to return the transpose, but matrixobjects also have .H for the conjugate transpose, and .I for the inverse.
In contrast, numpy arrays consistently abide by the rule that operations areapplied element-wise. Thus, if a and b are numpy arrays, then a*b is the arrayformed by multiplying the components element-wise:
c=np.array([[4, 3], [2, 1]])
d=np.array([[1, 2], [3, 4]])
print(c*d)
# [[4 6]
# [6 4]]
To obtain the result of matrix multiplication, you use np.dot :
print(np.dot(c,d))
# [[13 20]
# [ 5 8]]
The ** operator also behaves differently:
print(a**2)
# [[22 15]
# [10 7]]
print(c**2)
# [[16 9]
# [ 4 1]]
Since a is a matrix, a**2 returns the matrix product a*a.Since c is an ndarray, c**2 returns an ndarray with each component squaredelement-wise.
There are other technical differences between matrix objects and ndarrays(having to do with np.ravel, item selection and sequence behavior).
The main advantage of numpy arrays is that they are more general than2-dimensional matrices. What happens when you want a 3-dimensional array? Thenyou have to use an ndarray, not a matrix object. Thus, learning to use matrixobjects is more work -- you have to learn matrix object operations, andndarray operations.
Writing a program that uses both matrices and arrays makes your life difficultbecause you have to keep track of what type of object your variables are, lestmultiplication return something you don't expect.
In contrast, if you stick solely with ndarrays, then you can do everythingmatrix objects can do, and more, except with slightly differentfunctions/notation.
If you are willing to give up the visual appeal of numpy matrix productnotation, then I think numpy arrays are definitely the way to go.
PS. Of course, you really don't have to choose one at the expense of the other,since np.asmatrix and np.asarray allow you to convert one to the other (aslong as the array is 2-dimensional).
|
This is a kind of follow-up question to this post, where the coloring of axes, ticks and labels was discussed. I hope it is alright to open a new, extended question for this.
Changing the color of a complete frame (ticks and axes) around a double-plot (via add_subplot) with axes [ax1, ax2] results in a lot of code. This snippet changes the color of the frame of the upper plot:
ax1.spines['bottom'].set_color('green')
ax1.spines['top'].set_color('green')
ax1.spines['left'].set_color('green')
ax1.spines['right'].set_color('green')
for t in ax1.xaxis.get_ticklines(): t.set_color('green')
for t in ax1.yaxis.get_ticklines(): t.set_color('green')
for t in ax2.xaxis.get_ticklines(): t.set_color('green')
for t in ax2.yaxis.get_ticklines(): t.set_color('green')
So for changing the frame color of two plots with two y-axes each, I would need 16(!) lines of code... This is how it looks like:
Other methods I dug up so far:
matplotlib.rc: discussed here; changes globally, not locally. I want to have some other plots in different colors. Please, no discussions about too many colors in plots... :-)
matplotlib.rc('axes',edgecolor='green')
dig out the spines of the axis, then change it: also discussed here; not really elegant, I think.
for child in ax.get_children():
if isinstance(child, matplotlib.spines.Spine):
child.set_color('#dddddd')
Is there an
elegantway of condensing the above block, something more "pythonic"?
I'm using python 2.6.5 with matplotlib 0.99.1.1 under ubuntu.
|
If I do runserver or gunicorn straight from the commandline, the website works fine. However, if I try to run gunicorn using Foreman as specified in the Heroku documentation:
web: gunicorn myapp.wsgi
Then my website's static files are suddenly inaccessible; trying to go to
http://0.0.0.0:5000/static/js/jquery-1.9.1.min.js
Only gives me this error message:
Using the URLconf defined in myapp.urls, Django tried these URL patterns, in this order:
^$ [name='homepage']
...
The current URL, static/js/jquery-1.9.1.min.js, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
As I've said, the static files are definitely accessible if calling gunicorn or runserver directly, or even if using runserver with foreman start, so I'm guessing it doesn't have too much to do with my static files settings?
Also, running gunicorn on foreman with DEBUG = False doesn't even return anything except for a 500 error. Nothing is logged, not even on Sentry, so I have no idea what's wrong. It also works fine using gunicorn or runserver alone, or using runserver with foreman.
Any ideas what I can do to fix this problem?
|
Hi I have been trying out this problem:
Suppose P(n) is sum of digits of 2^n
For example:
As 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26,so P(15)=26.
Catulate sum of the P(n) for n=1 to 10000.
Here is my python code which is giving 67783431 as answer but the judge doesn't seems to be agree on this:
def P(n):
n = int(1<<n)
S = 0
while n != 0:
S += (n%10)
n /= 10
return S
Sum = 0
for i in range(1,10001):
Sum += P(i)
else:
print(Sum)
Could anybody tell me what's wrong in my approach? I would be appreciate if somebody points me to a mathematical solution for the same.
|
I have implemented oauth and openid separately (that is, sign in with OpenId, separate authorization to Google Data API with OAuth) and would like to combine them.
Currently I have the following in my app.yaml
- url: /_ah/login_required
script: main.py
- url: .*
script: main.py
login: required
Then, in main.py I have: (imports removed for clarity)
def getClient():
client = gdata.calendar.service.CalendarService()
consumer_key = 'my-app.appspot.com'
consumer_secret = 'consumersecret'
client.SetOAuthInputParameters(
gdata.auth.OAuthSignatureMethod.HMAC_SHA1,
consumer_key=consumer_key,
consumer_secret=consumer_secret)
gdata.alt.appengine.run_on_appengine(client)
return client
class OAuthOne(webapp.RequestHandler):
def get(self):
client = getClient()
request_token = client.FetchOAuthRequestToken(oauth_callback='http://my-app.appspot.com/oauth2')
client.SetOAuthToken(request_token)
auth_url = client.GenerateOAuthAuthorizationURL()
self.redirect( auth_url )
class OAuthTwo(webapp.RequestHandler):
def get(self):
client = getClient()
token_from_url = gdata.auth.OAuthTokenFromUrl(self.request.uri)
if not token_from_url:
self.redirect('/oauth')
else:
client.SetOAuthToken(token_from_url)
oauth_verifier = self.request.get('oauth_verifier', default_value='')
client.UpgradeToOAuthAccessToken(oauth_verifier=oauth_verifier)
self.redirect('/')
class MainPage(webapp.RequestHandler):
def get(self):
self.user = users.get_current_user()
self.template_values = {}
if self.user:
# do calendar api stuff here
self.template_file = 'templates/index.html'
else:
self.template_file = 'templates/denied.html'
path = os.path.join(os.path.dirname(__file__), self.template_file)
self.response.out.write( template.render(path, self.template_values) )
application = webapp.WSGIApplication(
[('/oauth', OAuthOne),
('/oauth2', OAuthTwo),
('/_ah/login_required', OpenIDHandler),
('/', MainPage)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
also in main.py, from http://code.google.com/googleapps/marketplace/tutorial_python_gae.html
class OpenIDHandler(webapp.RequestHandler):
def get(self):
"""Begins the OpenID flow and begins Google Apps discovery for the supplied domain."""
login_url = users.create_login_url(dest_url='http://my-app.appspot.com/',
_auth_domain=None,
federated_identity='gmail.com')
self.redirect( login_url )
I assume that the start of the magic will need to happen in my OpenIDHandler, and that I need to use something other than users.create_login_url(). Google's documentation here tells me that I need to 'Create the mechanism for performing discovery and making authentication requests.' and 'Add OAuth capability to authentication requests' (more docs here ), but as far as I can tell, not how to do it. At least not with Python.
There is an example of a raw http request a little lower on this page
https://www.google.com/accounts/o8/id
?openid.ns=http://specs.openid.net/auth/2.0
&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select
&openid.identity=http://specs.openid.net/auth/2.0/identifier_select
&openid.return_to=http://www.example.com/checkauth
&openid.realm=http://www.example.com
&openid.assoc_handle=ABSmpf6DNMw
&openid.mode=checkid_setup
&openid.ns.oauth=http://specs.openid.net/extensions/oauth/1.0
&openid.oauth.consumer=www.example.com
&openid.oauth.scope=http://docs.google.com/feeds/+http://spreadsheets.google.com/feeds/
But I'm not sure how to use this.
So apart from helping this become a shining example of a best practice, I really need to know how to 'Add OAuth capability to authentication requests'.
|
For example, after running this command:
sudo add-apt-repository ppa:tualatrix/ppa
I get the following output :
Traceback (most recent call last):
File "/usr/bin/add-apt-repository", line 125, in <module>
ppa_info = get_ppa_info_from_lp(user, ppa_name)
File "/usr/lib/python2.7/dist-packages/softwareproperties/ppa.py", line 80, in get_ppa_info_from_lp
curl.perform()
pycurl.error: (6, "Couldn't resolve host 'launchpad.net'")
Why does this happen? I just installed Ubuntu 12.04 LTS. And it works fine. I have updated and installed the system. I have even installed all required packages. But the thing is as soon as I want to install more packages, like PPA's and that sort of thing, I am not able to do so.
Until now I have not been able to install any PPA.
I am working behind a proxy.
|
Is there a library or application that can decompile Python 2.4+ bytecode to obtain the source code?
A search revealed:
Is there a library or application that can decompile Python 2.4+ bytecode to obtain the source code?
A search revealed:
As others said, the free version of decompyle only works up to 2.3. But sometimes you can get it to work by converting your newer pyc to the old marshalling format.
The following script takes two arguments, the input and the output file, and converts it into something which decompyle will at least try its teeth on.
#!/usr/bin/python
import marshal
import sys
MAGIC23 = ';\xf2\r\n'
def load_pyc(filename):
f = open(filename, 'rb')
try:
magic = f.read(4)
timestamp = f.read(4)
codeobject = marshal.load(f)
finally:
f.close()
return magic, timestamp, codeobject
def dump_pyc_23(filename, timestamp, codeobject):
assert len(timestamp)==4
f = open(filename, 'wb')
try:
f.write(MAGIC23)
f.write(timestamp)
marshal.dump(codeobject, f, 0)
finally:
f.close()
magic, timestamp, codeobject = load_pyc(sys.argv[1])
dump_pyc_23(sys.argv[2], timestamp, codeobject)
Good Luck!
I have a good experience with UnPyc â it perfectly recovered my Django models.py.
I've used decompyle (the Ubuntu package, not the online service, I don't know if they're the same thing, though) in the past and was more than satisfied with the results. It saved me hours of work after a
You don't want an online service but depython.com is a good Python decompile service. Give it a try.
For others ever in this regrettable situation I can confirm that uncompyle2 now works with Python 2.7 (and only 2.7 it seems at this time) and just saved me from a nasty accident (and yes, I should have been using source control).
Here is a little more info on
It will decompile Python up to version 2.3, but not 2.4+.
There is a fork of decompyle called unpyc that has seen some activity recently. I tried using it with some pyc files but it didn't work with them.
I am incredibly surprised at the accuracy of depython.net
What I think they do is use the dis module and reconstruct your code with it. You'll have to find a way to do that or someone who has written the algorithm already.
|
Question
After running tasks via celery's periodic task scheduler, beat, why do I have so many unconsumed queues remaining in RabbitMQ?
Setup
Django web app running on Heroku
Tasks scheduled via celery beat
Tasks run via celery worker
Message broker is RabbitMQ from ClouldAMQP
Procfile
web: gunicorn --workers=2 --worker-class=gevent --bind=0.0.0.0:$PORT project_name.wsgi:application
scheduler: python manage.py celery worker --loglevel=ERROR -B -E --maxtasksperchild=1000
worker: python manage.py celery worker -E --maxtasksperchild=1000 --loglevel=ERROR
settings.py
CELERYBEAT_SCHEDULE = {
'do_some_task': {
'task': 'project_name.apps.appname.tasks.some_task',
'schedule': datetime.timedelta(seconds=60 * 15),
'args': ''
},
}
tasks.py
@celery.task
def some_task()
# Get some data from external resources
# Save that data to the database
# No return value specified
Result
Every time the task runs, I get (via the RabbitMQ web interface):
An additional message in the "Ready" state under my "Queued Messages"
An additional queue with a single message in the "ready" state
This queue has no listed consumers
|
You ever notice how when your script dies because of some uncaught error, you don’t get that error in your log files? This post walks through how to make sure that you log that uncaught exception.
This is a trivial script that will raise an uncaught exception (code available here):
$ cat rgl/kaboom1.py
# vim: set expandtab ts=4 sw=4 filetype=python:
import logging
def f():
return g()
def g():
return h()
def h():
return i()
def i():
1/0
if __name__ == '__main__':
logging.basicConfig(
level=logging.DEBUG,
filename='/tmp/kaboom1.log',
filemode='w')
logging.debug('About to do f().')
f()
Notice the helpful traceback:
$ python rgl/kaboom1.py
Traceback (most recent call last):
File "rgl/kaboom1.py", line 28, in <module>
f()
File "rgl/kaboom1.py", line 9, in f
return g()
File "rgl/kaboom1.py", line 13, in g
return h()
File "rgl/kaboom1.py", line 17, in h
return i()
File "rgl/kaboom1.py", line 21, in i
1/0
ZeroDivisionError: integer division or
modulo by zero
Unfortunately, that helpful traceback does not show up in the output logs!
$ cat /tmp/kaboom1.log
DEBUG:root:About to do f().
You could wrap your code with big try / except
This diaper pattern is a popular solution::
try:
f()
except Exception as ex:
logging.exception(ex)
raise
Make sure you re-raise the exception, otherwise your program will end with a zero return code.
Sidenote: how to log an exception instance
If you do any of these, you probably won’t like what you get:
logging.error(ex)
logging.error(str(ex))
In both cases, you are just turning the exception to a string. You won’t see the traceback and you won’t see the exception type.
Instead of those, make sure you do one of these:
logging.exception(ex)
# this is exactly what logging.exception does inside
logging.error(ex, exc_info=1)
# sets a higher log level than error
logging.critical(ex, exc_info=1)
For the last two, without that
exc_info=1 parameter, you won’t see the traceback in your logs. You’ll just see the message from the exception.
Or you can use sys.excepthook
Instead of nesting your code inside a try-except clause, you can customize the built-in sys.excepthook function.
The kaboom2.py script has this extra code:
def log_uncaught_exceptions(ex_cls, ex, tb):
logging.critical(''.join(traceback.format_tb(tb)))
logging.critical('{0}: {1}'.format(ex_cls, ex))
sys.excepthook = log_uncaught_exceptions
And here’s the results:
$ python rgl/kaboom2.py
$ cat /tmp/kaboom2.log
DEBUG:root:About to do f().
CRITICAL:root: File "rgl/kaboom2.py", line 39, in <module>
f()
File "rgl/kaboom2.py", line 9, in f
return g()
File "rgl/kaboom2.py", line 13, in g
return h()
File "rgl/kaboom2.py", line 17, in h
return i()
File "rgl/kaboom2.py", line 21, in i
1/0
CRITICAL:root:<type 'exceptions.ZeroDivisionError'>: integer division or modulo by zero
Incidentally, sys.excepthook preserves the non-zero return code.
Also incidentally, you can use sys.excepthook for all sorts of fun stuff. This shows how to make it fire off pdb when stuff blows up.
|
Virtualici
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
j'ai tout tenté ! au mieux j'ai ça : ):
[sudo] password for boubou:
Sorry, try again.
sudo: 3 incorrect password attempts
boubou@boubou-M51SE:~$ *******
******* : commande introuvable
boubou@boubou-M51SE:~$
les : ******* c'est mon pass.
Hors ligne
nam1962
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
On va changer ton mot de passe.
Fais
users-admin
et là change ton mot de passe pour un truc simple uniquement avec des lettres sans accents
Dernière modification par nam1962 (Le 17/11/2013, à 15:21)
Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961
Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis.
Score : 49 convertis IRL (leur ai pas donné le choix, aussi...).
Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com
Hors ligne
Virtualici
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
Je ne comprend pas, il ne veux pas accèpté mon mot de pass, déjà parce-qu'il faut enter l'ancien, ça a fonctionné une fois et après, en plein parcours de ton tuto, j'ai due repondre O/n, "j'ai fais comme dans le tuto" O majuscule, j'ai tout essayé le 0 le o len même, mais rien il me redemande mon mdp, mais il n'en veux pas il était on n'peu plus simple pourtant !!!
Bref désolé de faire le boulet comme ça mais merci quand même
Dernière modification par Virtualici (Le 17/11/2013, à 16:28)
Hors ligne
nam1962
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
Redémarre et retente
Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961
Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis.
Score : 49 convertis IRL (leur ai pas donné le choix, aussi...).
Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com
Hors ligne
Vaykadji
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
Ce que tu peux essayer c'est écrire ton mot de passe autre part, par exemple dans ton navigateur, ou dans un fichier texte. Ensuite tu peux le surligner avec ta souris, le sélectionner, et clic droit > copier.
Ensuite dans ton terminal, quand il te demande ton mot de passe, tu fais clic droit et coller, puis tu appuies sur la touche <Enter> de ton clavier.
Comme ça, tu es sûr de bien entrer exactement ce que tu veux
Netbook : Asus EeePC 1005PX : Atom N450 / 2Gb DDR2 - Ubuntu UnityDesktop : i5 4670k / MSI GTX760 / 8Gb DDR3 - Windows 8.1 pro & Ubuntu UnityTablette : Google Nexus 7 2013 'flo' - S4Pro 1,51Ghz / 2Gb RAM - Android 4.4.2 & Ubuntu Touch
Hors ligne
rb
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
bonsoir
en voulant mettre à niveau le portable de ma femme sous ubuntu 12.04
j'ai commencé les actions et la :
sudo apt-get install ubuntu-restricted-extras
je me retrouve avec , dans le terminal "outil de configuration des paquets"Configuration de ttf-mscorefonts-installer ,un topo microsoft dont je te mets que la fin, il y en a des tonnes et je n'arrive pas à sélectionner l'ensemble pour te mettre une copie.
est ce normale
@+
Richard
Outil de configuration des paquets
┌──────────────┤ Configuration de ttf-mscorefonts-installer ├───────────────┐
│ │
│ MISCELLANEOUS │ │ If you acquired this product in the United States, this EULA is governed │ by the laws of the State of Washington. │ │ If this product was acquired outside the United States, then local laws │ may apply. │ │ Should you have any questions concerning this EULA, or if you desire to │ contact Microsoft for any reason, please contact the Microsoft │ subsidiary serving your country, or write: Microsoft Sales Information │ Center/One Microsoft Way/Redmond, WA 98052-6399. │ │ Reference: http://www.microsoft.com/typography/fontpack/eula.htm
│ <Ok>
│ │
└───────────────────────────────────────────────────────────────────────────┘
MSI Wind Box DC500-005 - Intel Atom Dual-Core D510 4 Go XubuntuVoyager 14.04 32bits et HandyLinux
Hors ligne
nam1962
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
Oui, tu sélectionnes ok avec la touche tab (les deux flèches au dessus du verrouillage majuscules) ce sont les polices de caractères non libres, ça permet de bien interpréter les docs envoyés par les gens du monde W$
Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961
Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis.
Score : 49 convertis IRL (leur ai pas donné le choix, aussi...).
Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com
Hors ligne
rb
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
Ok
Merci
MSI Wind Box DC500-005 - Intel Atom Dual-Core D510 4 Go XubuntuVoyager 14.04 32bits et HandyLinux
Hors ligne
markusolympe
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
ah, ça semble pas mal, je prends, merci !
Hors ligne
Virtualici
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
Bonjour nam et les autres;)
Bon je suis boqué a cette étape :
boubou@boubou-M51SE:~$ software-properties-gtk
gpg: /tmp/tmpJJAotZ/trustdb.gpg : base de confiance créée
boubou@boubou-M51SE:~$ sudo apt-get update
[sudo] password for boubou:
Sorry, try again.
[sudo] password for boubou:
Atteint http://fr.archive.ubuntu.com precise Release.gpg
Atteint http://fr.archive.ubuntu.com precise-updates Release.gpg
Atteint http://fr.archive.ubuntu.com precise-backports Release.gpg
Réception de : 1 http://extras.ubuntu.com precise Release.gpg [72 B]
Atteint http://archive.canonical.com precise Release.gpg
Atteint http://fr.archive.ubuntu.com precise Release
Atteint http://fr.archive.ubuntu.com precise-updates Release
Atteint http://archive.canonical.com precise Release
Atteint http://extras.ubuntu.com precise Release
Atteint http://fr.archive.ubuntu.com precise-backports Release
Atteint http://security.ubuntu.com precise-security Release.gpg
Atteint http://fr.archive.ubuntu.com precise/main Sources
Atteint http://archive.canonical.com precise/partner Sources
Atteint http://fr.archive.ubuntu.com precise/restricted Sources
Atteint http://fr.archive.ubuntu.com precise/universe Sources
Atteint http://fr.archive.ubuntu.com precise/multiverse Sources
Atteint http://fr.archive.ubuntu.com precise/main i386 Packages
Atteint http://fr.archive.ubuntu.com precise/restricted i386 Packages
Atteint http://fr.archive.ubuntu.com precise/universe i386 Packages
Atteint http://fr.archive.ubuntu.com precise/multiverse i386 Packages
Atteint http://fr.archive.ubuntu.com precise/main TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/multiverse TranslationIndex
Atteint http://extras.ubuntu.com precise/main Sources
Atteint http://security.ubuntu.com precise-security Release
Atteint http://archive.canonical.com precise/partner i386 Packages
Ign http://archive.canonical.com precise/partner TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/restricted TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/universe TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-updates/main Sources
Atteint http://fr.archive.ubuntu.com precise-updates/restricted Sources
Atteint http://fr.archive.ubuntu.com precise-updates/universe Sources
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse Sources
Atteint http://extras.ubuntu.com precise/main i386 Packages
Ign http://extras.ubuntu.com precise/main TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-updates/main i386 Packages
Atteint http://fr.archive.ubuntu.com precise-updates/restricted i386 Packages
Atteint http://fr.archive.ubuntu.com precise-updates/universe i386 Packages
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse i386 Packages
Atteint http://fr.archive.ubuntu.com precise-updates/main TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-updates/restricted TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-updates/universe TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-backports/main Sources
Atteint http://fr.archive.ubuntu.com precise-backports/restricted Sources
Atteint http://security.ubuntu.com precise-security/main Sources
Atteint http://fr.archive.ubuntu.com precise-backports/universe Sources
Atteint http://fr.archive.ubuntu.com precise-backports/multiverse Sources
Atteint http://fr.archive.ubuntu.com precise-backports/main i386 Packages
Atteint http://fr.archive.ubuntu.com precise-backports/restricted i386 Packages
Atteint http://fr.archive.ubuntu.com precise-backports/universe i386 Packages
Atteint http://fr.archive.ubuntu.com precise-backports/multiverse i386 Packages
Atteint http://fr.archive.ubuntu.com precise-backports/main TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-backports/multiverse TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-backports/restricted TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-backports/universe TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/main Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/main Translation-fr
Atteint http://fr.archive.ubuntu.com precise/main Translation-en
Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-fr
Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com precise/restricted Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/restricted Translation-fr
Atteint http://fr.archive.ubuntu.com precise/restricted Translation-en
Atteint http://fr.archive.ubuntu.com precise/universe Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/universe Translation-fr
Atteint http://fr.archive.ubuntu.com precise/universe Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/main Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/main Translation-en
Atteint http://security.ubuntu.com precise-security/restricted Sources
Atteint http://security.ubuntu.com precise-security/universe Sources
Atteint http://security.ubuntu.com precise-security/multiverse Sources
Atteint http://security.ubuntu.com precise-security/main i386 Packages
Atteint http://security.ubuntu.com precise-security/restricted i386 Packages
Atteint http://security.ubuntu.com precise-security/universe i386 Packages
Atteint http://security.ubuntu.com precise-security/multiverse i386 Packages
Atteint http://security.ubuntu.com precise-security/main TranslationIndex
Atteint http://security.ubuntu.com precise-security/multiverse TranslationIndex
Atteint http://security.ubuntu.com precise-security/restricted TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/restricted Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/restricted Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/universe Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/universe Translation-en
Atteint http://fr.archive.ubuntu.com precise-backports/main Translation-en
Atteint http://fr.archive.ubuntu.com precise-backports/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com precise-backports/restricted Translation-en
Atteint http://fr.archive.ubuntu.com precise-backports/universe Translation-en
Atteint http://security.ubuntu.com precise-security/universe TranslationIndex
Atteint http://security.ubuntu.com precise-security/main Translation-en
Atteint http://security.ubuntu.com precise-security/multiverse Translation-en
Ign http://archive.canonical.com precise/partner Translation-fr_FR
Ign http://extras.ubuntu.com precise/main Translation-fr_FR
Ign http://archive.canonical.com precise/partner Translation-fr
Atteint http://security.ubuntu.com precise-security/restricted Translation-en
Ign http://extras.ubuntu.com precise/main Translation-fr
Ign http://archive.canonical.com precise/partner Translation-en
Ign http://extras.ubuntu.com precise/main Translation-en
Atteint http://security.ubuntu.com precise-security/universe Translation-en
72 o réceptionnés en 1s (54 o/s)
Lecture des listes de paquets... Fait
boubou@boubou-M51SE:~$ sudo apt-get install xfce4-goodies
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
Les paquets suivants ont été installés automatiquement et ne sont plus nécessaires :
linux-headers-3.2.0-52-generic linux-headers-3.2.0-52
Veuillez utiliser « apt-get autoremove » pour les supprimer.
Les paquets supplémentaires suivants seront installés :
hddtemp libfam0 libhal-storage1 libhal1 libthunar-vfs-1-2
libthunar-vfs-1-common lm-sensors mousepad squeeze xfce4-artwork
xfce4-battery-plugin xfce4-clipman xfce4-clipman-plugin xfce4-cpufreq-plugin
xfce4-diskperf-plugin xfce4-fsguard-plugin xfce4-genmon-plugin
xfce4-mount-plugin xfce4-sensors-plugin xfce4-smartbookmark-plugin
xfce4-timer-plugin xfce4-wavelan-plugin
Paquets suggérés :
ksensors fam fancontrol sensord read-edid i2c-tools xfprint4
xfce4-cellmodem-plugin xfce4-linelight-plugin xfce4-messenger-plugin
xfce4-mpc-plugin xfce4-radio-plugin xfce4-xfapplet-plugin xfswitch-plugin
xfce4-hdaps thunar-thumbnailers xfmpc xsensors
Les NOUVEAUX paquets suivants seront installés :
hddtemp libfam0 libhal-storage1 libhal1 libthunar-vfs-1-2
libthunar-vfs-1-common lm-sensors mousepad squeeze xfce4-artwork
xfce4-battery-plugin xfce4-clipman xfce4-clipman-plugin xfce4-cpufreq-plugin
xfce4-diskperf-plugin xfce4-fsguard-plugin xfce4-genmon-plugin xfce4-goodies
xfce4-mount-plugin xfce4-sensors-plugin xfce4-smartbookmark-plugin
xfce4-timer-plugin xfce4-wavelan-plugin
0 mis à jour, 23 nouvellement installés, 0 à enlever et 0 non mis à jour.
Il est nécessaire de prendre 11,8 Mo dans les archives.
Après cette opération, 22,2 Mo d'espace disque supplémentaires seront utilisés.
Souhaitez-vous continuer [O/n] ? O
Annulation.
boubou@boubou-M51SE:~$
Hors ligne
Vaykadji
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
C'est un O, pas un 0 (un "eau" de l'alphabet, pour OUI, pas le zéro), mais je pense que tu l'as compris ça.
Essaye avec un "o" minuscule, moi c'est ce que je fais. Essaye également avec un "y" qui est la réponse YES sur une installation en Anglais (on sait jamais que toute la traduction soit pas installée...)
Netbook : Asus EeePC 1005PX : Atom N450 / 2Gb DDR2 - Ubuntu UnityDesktop : i5 4670k / MSI GTX760 / 8Gb DDR3 - Windows 8.1 pro & Ubuntu UnityTablette : Google Nexus 7 2013 'flo' - S4Pro 1,51Ghz / 2Gb RAM - Android 4.4.2 & Ubuntu Touch
Hors ligne
nam1962
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
Ou tout simplement la touche entrée (valide dans la plupart des cas)
Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961
Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis.
Score : 49 convertis IRL (leur ai pas donné le choix, aussi...).
Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com
Hors ligne
Virtualici
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
Bon et bien merci, je ne sais pas si j'ai tout fais "bien" car parfois ni le O ni o ni Y ni y ni même Entrer, parfois les double flèches me proposais un (y/n) j'ai toujours mis y, mais parfois ça ne fonctionnais même pô ^^
Mais bon la bécane fonctionne c'est déjà top ! merci Nam
A+ ?
Hors ligne
alca94
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
@ nam1962
Je ne sais pas pourquoi (même dans la Doc en général) ils utilisent "sudo gedit" alors que ça devrait être "gksudo gedit" et je vois que vous également ?
http://doc.ubuntu-fr.org/sudo#quand_doi … udokdesudo
En ligne
moko138
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
@alca94 : merci d'enfoncer le clou !
@nam1962 : effectivement, ça serait bien que tu édites ton tuto en ce sens.
Depuis que je distingue gksudo de sudo, je ne me retrouve plus avec /home et HD externe en lecture seule.
Hors ligne
Vaykadji
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
C'est pareil pourtant, sauf que "sudo gedit" va tourner dans le terminal et demandera de laisser ouvert le terminal alors que "gksudo gedit" va faire appel à gksu pour ouvrir gedit, et donc tourner dans gksu et pas dans le terminal.
Dernière modification par Vaykadji (Le 21/11/2013, à 13:43)
Netbook : Asus EeePC 1005PX : Atom N450 / 2Gb DDR2 - Ubuntu UnityDesktop : i5 4670k / MSI GTX760 / 8Gb DDR3 - Windows 8.1 pro & Ubuntu UnityTablette : Google Nexus 7 2013 'flo' - S4Pro 1,51Ghz / 2Gb RAM - Android 4.4.2 & Ubuntu Touch
Hors ligne
moko138
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
Ce n'est pas pareil au niveau des droits admin, cf. lien donné par alca94,
et ça a parfois des conséquences embêtantes au redémarrage.
Hors ligne
nam1962
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
Modifié ! Merci du rappel bande de puristes
Dernière modification par nam1962 (Le 21/11/2013, à 14:59)
Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961
Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis.
Score : 49 convertis IRL (leur ai pas donné le choix, aussi...).
Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com
Hors ligne
moko138
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
Grand merci, nam1962 !
Hors ligne
jibel
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
@Tous ,
La guerre du GKsudo VS sudo est déclarée , au premier round sudo a envoyé un uppercut a GKsudo qui c'est retrouvé dans les cordes ....... Qu'elle va être la réponse de GKsudo ? suite au prochain épisode ....
Plus grande est la face, plus grand est le dos!
Toutes les fautes de frappe, d'orthographe, de grammaire et de syntaxe ci-dessus, sont la propriété intellectuelle de l'auteur.Elles peuvent être reproduites et même corrigées sans l'accord préalable du susdit.
Avec Ub.12.04, 14.04, Kub. 13.10, 14.04,Voy 14.04,13.10,13.04,12.04 LTS , Mint 17, hybryde fus13.04 .PC medion akira DD 1T + 2 .
Hors ligne
Vaykadji
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
Ah et il faut aussi se rappeler que certaines distributions ne supportent pas la commande gksudo (je pense à Fedora, notamment), alors que sudo est présent partout.
Note :
La différence entre sudo et gksudo est la suivante :
- sudo lance un programme en root en utilisant la configuration de l'utilisateur loggé.
- gksudo lance un programme en root en utilisant la configuration root du programme.
En fait, utiliser gksudo va permettre de ne pas modifier vos dossiers personnels, qui contiennent des fichiers nécessaires au bon fonctionnement de la session. Cependant, utiliser gksudo va également vous faire perdre vos paramètres personnalisés durant l'utilisation du programme puisqu'il va utiliser les fichiers de configuration root pour se lancer.
Il est déconseillé d'utiliser 'sudo' pour un programme avec interface graphique parce que dans de rares cas, ça pourrait causer des dommages importants à votre OS.
Source
Dernière modification par Vaykadji (Le 21/11/2013, à 19:03)
Netbook : Asus EeePC 1005PX : Atom N450 / 2Gb DDR2 - Ubuntu UnityDesktop : i5 4670k / MSI GTX760 / 8Gb DDR3 - Windows 8.1 pro & Ubuntu UnityTablette : Google Nexus 7 2013 'flo' - S4Pro 1,51Ghz / 2Gb RAM - Android 4.4.2 & Ubuntu Touch
Hors ligne
nam1962
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
Ce n'est plus un tuto : ça devient une encyclopédie ce topic
Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961
Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis.
Score : 49 convertis IRL (leur ai pas donné le choix, aussi...).
Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com
Hors ligne
alca94
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
Ah et il faut aussi se rappeler que certaines distributions ne supportent pas la commande gksudo (je pense à Fedora, notamment),
ça s'adresse a un public "ubuntu" .Ferdora doit avoir son propre forum ,non ?
En ligne
metalux
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
nam1962, tu peux S.T.P. m'apporter des précisions sur:1. TLP a un réglage douteux : SATA_LINKPWR_ON_BAT qu'il vaut mieux mettre sur max_performance
et son utilité.
J'utilise également TLP depuis un certains temps et justement je change cette option pour mettre SATA_LINKPWR_ON_AC=min_power sinon mon PC ressemble plus à un grille-pain....euh grille-mains
Xubuntu 14.04 LTS sur HP Pavilion t728.fr
Precise Pangolin 64 bits sur Acer aspire 5738ZG
Voyager 13.04 mise à niveau en 14.04 sur TOSHIBA Satellite C870-196.
Faîtes la mise à jour de vos P.P.A. automatiquement
Hors ligne
nam1962
Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes)
Ça venait d'une observation sur un fofo qui depuis a disparu : ce premier qui me l'a conseillé considérait que min_power était mal géré.
De mon côté, ça m'a bien été sur 36 installs. (Mais du coup n'ai pas testé min_power)
Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961
Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis.
Score : 49 convertis IRL (leur ai pas donné le choix, aussi...).
Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com
Hors ligne
|
joko
Re : Qarte arte.tv browser (ex Qarte+7)
bonjour, grands compliments à VinsS et consors, vraiment épaté. bravo à tous les p'tits fouineurs !
qualité vidéo géniale, rien à voir avec celle du site d'arte +7 !!!
Dernière modification par joko (Le 06/11/2012, à 12:35)
Je suis un homme, quoi de plus naturel en somme ?
linux on the rocks
Hors ligne
kykyou
Re : Qarte arte.tv browser (ex Qarte+7)
bonjour, superbe programme , sauf que cela ne fonctionne pas chez moi j ai l erreur :
qarte
Erreur de segmentation (core dumped)
j ai bien vu que je n etais pas le seul , mais j ai pas trop compris comment faire
je suis sous xubuntu voyager 12.04
j ai cru comprendre que cela venais du 64 bit !
merci de votre aide ..
resolu , j ai changé de theme et hop tout fonctionne .....
merci vinz
Dernière modification par kykyou (Le 07/11/2012, à 14:48)
Hors ligne
VinsS
Re : Qarte arte.tv browser (ex Qarte+7)
Nouvelle version 1.5.0
L'extension des fichiers est redevenue .flv comme avant. Le format n'a pas changé bien sur mais l'extension .mp4 n'était pas exacte et on me signalait que des lecteurs multimédia ne les acceptaient pas obligeant les utilisateurs à renommer leurs fichiers.
J'ai aussi ajouter dans la boîte de dialogue 'Préférences' une option pour rajouter à chaque téléchargement une vignette du même nom.
Ceci n'est utile que pour certains serveur de médias comme Minidla qui utilisent cette icône pour leur cover.
La mise à jour du ppa est en route, sinon, comme d'hab, j'ai mis un .tar.gz et un .all.deb sur la page Download de www.oqapy.eu
Bon Arte
Hors ligne
mydjey
Re : Qarte arte.tv browser (ex Qarte+7)
Grand merci VinsS pour ce soft qui m'est très utile.
Mon site : http://mydjey.eu/
Hors ligne
souleika
Re : Qarte arte.tv browser (ex Qarte+7)
Bonjour,
Je n'arrive pas à afficher la fenêtre des préférences. Elle est apparue la première fois que j'ai utlisé Qarte, mais maintenant impossible de l'afficher à nouveau. La rubrique "Options" du menu "options" n'affiche rien.
A part ça c'est vraiment un super logiciel, merci
Hors ligne
LRDP
Re : Qarte arte.tv browser (ex Qarte+7)
Bonsoir,
Bravo pour Qarte. Je n'arrivais pas à l'installer, mais en reprenant à l'instant le lien http://www.ubuntuupdates.org/package/xb … e/rtmpdump en installant un autre dépot, j'ai pu installer rtpmdump très simplement, puis Qarte dans la logithèque, et en voiture Simone! Excellent développement, excellente qualité.
Hors ligne
Api07
Re : Qarte arte.tv browser (ex Qarte+7)
Comme je galérais grave pour regarder l'excellente série Breaking Bad sur le site d'arte+7 j'ai fini par découvrir et installer le non moins excellent qarte dont je remercie l'auteur.
Le soucis est que je n'arrive à télécharger aucune vidéo car j'obtiens le message suivant : url introuvable.
Serais-ce une erreur de paramétrage? Un problème de connexion? Comme je suis un novice total sur ubuntu merci de m'exposer votre éventuelle solution en termes adaptés à mon niveau.
Merci.
Hors ligne
eochu
Re : Qarte arte.tv browser (ex Qarte+7)
Tout est question d'intention, quand j'ai repris le code d'arte+7recorder mon intention était bien de faire une application graphique et pas du tout une appli en ligne de commande.
La partie graphique ne peut plus être dissociée du code sans une réécriture complète, ce que je ne ferais pas vu que j'ai du mal à en saisir l'intérêt et que, comme je l'ai dis, cela n'a jamais été dans mes intentions.
Je comprends ton point de vue de vouloir faire une application graphique. Ce que je voulais dire, c'est qu'avec le langage et les bibliothèques que tu utilises pour développer ce programme, ça ne coûterait pas « plus cher » en temps de développement de faire une partie ligne de commande et une partie graphique à part (sauf peut-être maintenant puisque le développement n'a pas été pensé dans ce sens).
L'intérêt, comme je le mentionnais dans mon précédent message, est de pouvoir faire tourner Qarte sur un serveur dépourvu de couche graphique. Ça ne concerne peut-être pas beaucoup de monde, mais c'est techniquement possible et facile de concevoir un programme qui fonctionne à la fois en CLI et avec une surcouche graphique pour ceux qui veulent.
Là par exemple, si je veux faire en sorte que Qarte tourne sans couche graphique, ça va me demander beaucoup de travail (d'autant plus que je ne connais pas le code), un fork (donc deux projets séparés), et donc beaucoup de temps et d'énergie perdus. Je trouve ça dommage.
Hors ligne
atunoa
Re : Qarte arte.tv browser (ex Qarte+7)
Super, qarte est compatible avec voyager 12.10 - xubuntu 12.10. Merci pour tes améliorations continues sur un de mes programmes favoris.
Dernière modification par atunoa (Le 13/11/2012, à 19:21)
Panasonic cf-51 X 2 Obsolescence inconnue, Core Duo T2500 2.0 GHz / 2 Go (c'est court) ; Voyager 13.04 en étant passé par toutes les autres;
Hors ligne
tuxmarc
Re : Qarte arte.tv browser (ex Qarte+7)
SU-PER-BE
Merci Vincent, quel magnifique travail !!
J'ai vu un billet sur le sujet Voyager 12.10 et je me suis empressé d'installer en console.
Tout baigne chez moi, autant sur le portable que sur la tour.
Par la passé, j'avais réussi à télécharger des émissions d'Arte grâce à Arte7recorder puis TvDownloader, mais à cause ce changements de protocole chez Arte, c'était devenu un enfer, surtout pour les développeurs qui devaient courir derrière des modifs chez Arte, qu'on ne leur avait pas signalé.
J'espère que leur politique de changer de protocole va se calmer !
Vive Richard Stalmann, Linus Torvalds, et tous les fondus de Linux.
De l'Ordinosaure fait à 90% de récup, à un portable LDLC neuf sans système, en passant par une tour, un serveur et une carte mère sans boitier, tous libres !!
Collection de 15 DD tous bien élevés au Linux sous la mère et se baladant d'une machine à l'autre.
Parrain Linux sur www.parrain-linux.com et www.parrains.linux.free.fr
Hors ligne
Titanet
Re : Qarte arte.tv browser (ex Qarte+7)
Nouvelle version 1.5.0
L'extension des fichiers est redevenue .flv comme avant. Le format n'a pas changé bien sur mais l'extension .mp4 n'était pas exacte et on me signalait que des lecteurs multimédia ne les acceptaient pas obligeant les utilisateurs à renommer leurs fichiers.
Bonjour Vincent,
J'avoue que je ne comprends pas bien cette histoire de format de fichier, et pour quelle raison précisément tu as modifié l'extension. Je n'ai pas encore installé la nouvelle version que tu proposes, j'en suis resté à la version 1.4 que j'utilise régulièrement.
Puisque le but de ton application est de s'affranchir du format Flash d'Adobe, pourquoi ajouter l'extension .flv ?? Quand je regarde les propriétés des fichiers téléchargés sous Ubuntu, je vois que le codec vidéo est H264 et le codec audio MPEG-4 AAC. En quoi l'extension .mp4 empêcherai d'autres utilisateurs de lire ces fichiers ?? Je ne comprends pas du tout où est le problème. Merci d'éclairer ma lanterne !
"Ce n’est pas parce que les choses sont difficiles que nous n’osons pas, c’est parce que nous n’osons pas qu’elles sont difficiles." Sénèque
Sous Ubuntu 12.04 Precise Pangolin (desktop) et 14.04 beta (portable), avec Ubuntu depuis The Hoary Hedgehog 5.04
Hors ligne
VinsS
Re : Qarte arte.tv browser (ex Qarte+7)
@ Titanet,
Bonsoir,
Comme je dis dans mon post, le format est inchangé, il s'agit donc toujours de paquets flash.
L'extension .mp4 est due à une mauvaise interprétation de ma part de l'entête du fichier, erreur dont je ne me rendis pas compte du fait que j'utilise VLC qui ouvre tout ce qu'il reconnaît sans se formaliser de l'extension.
Ce n'est pas le cas de tous les lecteurs multimédias.
L'extension .flv était celle des versions Qarte+7 et cela ne posait aucun problème.
Maintenant, si une option dans la boîte préférences pour le choix de l'extension peut être utile à certains, c'est très simple à ajouter.
Dans le même sujet on m'a demandé si je pouvais ajouter un fonctionnalité de conversion de format. Ce n'est pas la finalité première de Qarte mais si ça peut rendre l'outil plus complet, pourquoi pas. Je suis ouvert au débat.
Hors ligne
Titanet
Re : Qarte arte.tv browser (ex Qarte+7)
Vincent, merci pour ta réponse rapide.
Je suis désolé mais je ne comprends toujours pas ! J'utilise moi aussi VLC pour lire les vidéos téléchargées, et si j'essaye de les lire avec Totem, le lecteur par défaut dans Ubuntu, çà marche aussi. Dois-je comprendre que des utilisateurs de ton application utilisent un autre système (Windows ou une autre distribution) ? Quel autre lecteur multimédia utilisent-ils ? Ont-ils remonté ce problème ?
De toute façon, les fichiers sont bien au format mp4, je veux dire l'entête semble bien être du mp4, pas flv, non ?
En tant que partisan des formats libres et ouverts, et je ne pense pas être le seul, je ne saisi pas ce revirement. Si tu peux proposer le choix de l'extension de fichier dans une boite de dialogue, ce serait bien aussi. Et encore mieux si tu offres la possibilité de convertir les fichiers en les encapsulant dans un conteneur Matroska (.mkv). Un petit script de conversion utilisant ffmpeg doit pouvoir faire ce travail.
Dernière modification par Titanet (Le 18/11/2012, à 00:44)
"Ce n’est pas parce que les choses sont difficiles que nous n’osons pas, c’est parce que nous n’osons pas qu’elles sont difficiles." Sénèque
Sous Ubuntu 12.04 Precise Pangolin (desktop) et 14.04 beta (portable), avec Ubuntu depuis The Hoary Hedgehog 5.04
Hors ligne
Xavier21
Re : Qarte arte.tv browser (ex Qarte+7)
Bonjour,
Je prends part à cette discussion autour du format, modeste contribution de ma part, car je ne suis pas expert. Je note cependant qu'avec la dernière version de Qarte (avec l'extension flv), j'ai de grosse difficulté à convertir le fichier en mkv, seul moyen pour moi de lire le fichier sur mon lecteur de salon. Les petits fichiers passent sans difficulté, mais dès que le fichier est plus long, avidemux plante. Le fichier mkv est bien créé, mais l'image est quelque peu saccadée.
Je précise qu'avant le changement de version, les fichiers mp4 se convertissaient sans problème.
Je ne serai pas contre que le choix de l'extension soit proposé dans les versions futures.
En tout état de cause, un grand merci pour cette application dont je suis devenu totalement accro !
Bonne journée à tous
Dernière modification par Xavier21 (Le 20/11/2012, à 08:57)
Hors ligne
Zoulou.4556
Re : Qarte arte.tv browser (ex Qarte+7)
slt VinsS, je trouve que l'idée du format de conversion que tu propose n'est pas mauvaise et personnellement ça me rendrait service, je partage souvent dans le cadre de ma famille ou de mes amis(e) les vidéos que je récupère sur Qarte .
Une petite option en plus serait sympa !
Asus X66IC Manjaro 64bits dual Ubuntu 14.04 64 bits / Dell Latitude D520 Xubuntu 14.04 32 bits/ Aurore BG6-I3-4-H10S1 SSD 120 go +DD 1To Manjaro 64 bits dual Ubuntu 64 bits
Hors ligne
VinsS
Re : Qarte arte.tv browser (ex Qarte+7)
Je pense qu'une mise au point s'impose ici.
Le format des vidéos téléchargées n'a jamais changé, il est toujours le même que depuis la première version de Qarte, le même format que précédemment avec Qarte+7 et toujours le même qu'avec Arte+7recorder.
L'extension .flv ne posait aucun problème alors, il n'y a pas de raison que ce soit le cas maintenant.
L'extension .mp4 était une mauvaise interprétation de ma part des metadata des fichiers, ce que j'ai rectifié, mais, j'insiste, il s'agit de l'extension et non du format réel, inchangé lui.
Si Qarte ne propose pas de conversion de format des vidéos c'est parce que ce n'était pas la finalité première de ce logiciel. Les applications dans ce domaine ne manquent pas.
Toutefois, comme je le dis déjà dans mon post #214, je ne suis pas opposé à l'ajout de fonctionnalités permettant à chacun de faire choix de son format de fichier.
Hors ligne
mydjey
Re : Qarte arte.tv browser (ex Qarte+7)
VinsS si je comprend bien ce que tu expliques, il suffit de renommer fichier.flv en fichier.mp4 et on obtient un fichier identique à celui que l'on obtenait avant que tu fasses cette modif ?
Je me trompe ?
Dernière modification par mydjey (Le 21/11/2012, à 09:14)
Mon site : http://mydjey.eu/
Hors ligne
Xavier21
Re : Qarte arte.tv browser (ex Qarte+7)
Bonjour,
J'ai suivi avec intérêt tes explications VinsS, et pour le coup, je me rends compte que j'ai eu de la chance dans mes conversions précédentes, car elles ne marchent pas à tous les coups non plus. J'ai converti un fichier que j'avais récupéré avec la version précédente de Qarte et il a planté également sur la fin.
Pour le coup, cela n' a effectivement aucun lien avec le changement de version.
À moi de trouver la bonne application qui fera bien le boulot de conversion !
Bonne journée
Hors ligne
souleika
Re : Qarte arte.tv browser (ex Qarte+7)
@ souleika,
Lance-le dans un terminal avec l'argument -d (debug)
qarte -d
puis tu copies ici ce qui apparaîtra dans le terminal après que tu aies cliqué sur le menu Options.
Bonjour, désolée pour le délai de réaction.
Quand je clique sur Options > options, j'obtiens ceci
21:09:40: INFO - qarte Call setting dialogbox
Traceback (most recent call last):
File "/usr/share/qarte-1.5.0/qarte.py", line 208, in edit_settings
sett.setupUi(Dialog, self)
File "/usr/share/qarte-1.5.0/ui_config.py", line 369, in setupUi
self.set_config()
File "/usr/share/qarte-1.5.0/ui_config.py", line 385, in set_config
self.cfg['cur_cat']))
ValueError: list.index(x): x not in list
Hors ligne
souleika
Re : Qarte arte.tv browser (ex Qarte+7)
@ souleika,
M'a tout l'air que ta config contient encore un paramètre d'une ancienne version.
Supprime ce fichier:
~/.Qarte/config.cfget relance Qarte, il le recréera.
(
~/représente ton dossier à toi)
Merci !
Hors ligne
Upsa
Re : Qarte arte.tv browser (ex Qarte+7)
Bonsoir VinsS,
Bravo pour votre Qarte+.
Je viens de changer d'ordinateur et d'installer Ubuntu 12.10 en 64 bits. Qarte ne fonctionne plus correctement en 64 bits alors que cela fonctionne correctement en 32 bits.
Lorsque je lance qarte dans le terminal et que je veux simplement fermer la fenêtre "Qarte Préférences" ou bien si je clique sur n'importe où sur cette fenêtre voilà ce que j'obtiens :
qarte
Erreur de segmentation (core dumped)
Dans le terminal, si je lance qarte -d et que je ferme simplement a fenêtre "Qarte Préférences" voici ce que j'obtiens :
qarte -d
22:26:22: INFO - qarte Main thread: <_MainThread(MainThread, started 139759807784704)>
22:26:22: INFO - ui_main setup main window
22:26:22: INFO - ui_main set page arte+
22:26:22: INFO - ui_main set button's group arte+
22:26:22: INFO - ui_main set basket arte+
22:26:22: INFO - ui_main set dwnld button arte+
22:26:22: INFO - ui_main set page arteLive
22:26:22: INFO - ui_main set categories buttons
22:26:22: INFO - ui_main set button's group arteLive
22:26:22: INFO - ui_main set basket arteLive
22:26:22: INFO - ui_main set dwnld buttons
22:26:22: INFO - ui_main set page arteLive extra
22:26:22: INFO - ui_main set extra categories buttons
22:26:22: INFO - ui_main set button's group arteLive extra
22:26:22: INFO - ui_main set basket arteLive extra
22:26:22: INFO - ui_main set extra dwnld buttons
22:26:22: INFO - ui_main set menu bar
22:26:22: INFO - ui_main set status bar
22:26:22: INFO - ui_main set actions
22:26:22: INFO - ui_main make connections
22:26:22: INFO - ui_main set theme
22:26:22: INFO - ui_main main window complete
22:26:22: INFO - utils Updating
22:26:22: INFO - utils File /home/upsa/.Qarte/livedata_fr.py saved
22:26:22: INFO - utils The file has been updated at: lun. 17 sept. 2012 09:20:46 CEST
22:26:22: INFO - artePlus arte+7 folder: None
22:26:22: INFO - parsers Get page: http://liveweb.arte.tv/fr
22:26:22: INFO - parsers get page http://liveweb.arte.tv/fr
22:26:23: INFO - qarte Call setting dialogbox
Erreur de segmentation (core dumped)
Avez-vous une petite idée du problème ?
Cordialement,
Hors ligne
|
I have some script on Ruby 1.9.3:
require "net/imap"
imap = Net::IMAP.new(mail_imap_server)
imap.login(mail_login, mail_password)
imap.select("INBOX")
puts imap.search(["FROM", "homer@simpson.com"])
imap.logout
imap.disconnect
If the desired message is present, then all is well. If the desired message is missing, an error:
/opt/local/lib/ruby1.9/1.9.1/net/imap.rb:1332:in `block in search_internal': undefined method `[]' for nil:NilClass (NoMethodError)
from /opt/local/lib/ruby1.9/1.9.1/monitor.rb:211:in `mon_synchronize'
from /opt/local/lib/ruby1.9/1.9.1/net/imap.rb:1326:in `search_internal'
from /opt/local/lib/ruby1.9/1.9.1/net/imap.rb:752:in `search'
from ./mail.rb:12:in `mail'
from ./mail.rb:26:in `<main>'
How can I solve this problem?
|
I am told to
Write a function, square(a), that takes an array, a, of numbers and returns an array containing each of the values of a squared.
At first, I had
def square(a):
for i in a: print i**2
But this does not work since I'm printing, and not returning like I was asked. So I tried
def square(a):
for i in a: return i**2
But this only squares the last number of my array. How can I get it to square the whole list?
|
How do I check if a file exists, using Python, without using a try: statement?
You can also use
import os.path
os.path.isfile(fname)
if you need to be sure it's a file.
You have the
import os.path
os.path.isfile(file_path)
>>> print os.path.isfile("/etc/passwd")
True
>>> print os.path.isfile("/etc")
False
>>> print os.path.isfile("/does/not/exist")
False
>>> print os.path.exists("/etc/passwd")
True
>>> print os.path.exists("/etc")
True
>>> print os.path.exists("/does/not/exist")
False
import os
import os.path
PATH='./file.txt'
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
print "File exists and is readable"
else:
print "Either file is missing or is not readable"
import os
os.path.exists(filename)
Prefer the try statement. It's considered better style and avoids race conditions.
Don't take my word for it. There's plenty of support for this theory. Here's a couple:
This is the simplest way to check if a file exists. Just
import os
fname = "foo.txt"
if os.path.isfile(fname):
print "file does exist at this time"
else:
print "no such file"
import os
if os.path.isfile(filename):
It doesn't seem like there's a meaningful functional difference between try/except and exists(), so you should use which one makes sense.
If you want to read a file, if it exists, do
try:
f = open(filepath)
except IOError:
print 'Oh dear.'
But if you just wanted to rename a file if it exists, and therefore don't need to open it, do
if os.path.exists(filepath):
os.rename(filepath, filepath + '.old')
If you want to write to a file, if it doesn't exist, do
if not os.path.exists(filepath):
f = open(filepath, 'w')
If you need file locking, that's a different matter.
import pathlib
p = pathlib.Path('path/to/file')
if p.exists():
# do stuff
You can (and usually should) still use a
try:
with p.open() as f:
# do awesome stuff
except OSError:
print('Well darn.')
The pathlib module has lots of cool stuff in it: convenient globbing, checking file's owner, easier path joining, etc. It's worth checking out.
You could try this: (safer)
try:
# http://effbot.org/zone/python-with-statement.htm
# with is more safe to open file
with open('whatever.txt') as fh:
# do something with fh
except IOError as e:
print("({})".format(e))
the ouput would be:
then, depending on the result, your program can just keep running from there or you can code to stop it if you want.
Just to add to the confusion, it seems that the try: open() approach suggested above doesn't work in Python, as file access isn't exclusive, not even when writing to files, c.f. What is the best way to open a file for exclusive access in Python?.
You should definitely use this one.
from os.path import exists
if exists("file") == True:
print "File exists."
elif exists("file") == False:
print "File doesn't exist."
You can simply use tempfile module to know whether file exists or not:
import tempfile
tempfile._exists('filename') # return True or False
If you want to do what in bash would be
if [ -e '$FILE' ]; then
prog '$FILE'
fi
which I sometimes do when using Python to do more complicated manipulation of a list of names (as I sometimes need to use Python for), the try open(file): except: method isn't really what's wanted, as it is not the Python process that is intended to open the file. In one case, the purpose is to filter a list of names according to whether they exist at present (and there are no processes likely to delete the file, nor security issues since this is on my Raspberry Pi which has no sensitive files on its SD).
I'm wondering whether a 'Simple Patterns' site would be a good idea? So that, for example, you could illustrate both methods with links between them and links to discussions as to when to use which pattern.
You can write Brian's suggestion without the
from contextlib import suppress
with suppress(IOError), open('filename'):
process()
from contextlib import contextmanager
@contextmanager
def suppress(*exceptions):
try:
yield
except exceptions:
pass
You can use following open method to check if file exists + readable
open(inputFile, 'r')
import os
path = /path/to/dir
root,dirs,files = os.walk(path).next()
if myfile in files:
print "yes it exists"
This is helpful when checking for several files. Or you want to do a set intersection/ subtraction with an existing list.
This sample function will test for a file's presence in a very Pythonic way using try .. except:
def file_exists(filename):
try:
with open(filename) as f:
return True
except IOError:
return False
protected by NullPoiиteÑ Jun 10 '13 at 5:13
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?
|
So I'm trying to authenticate with the v2 API via oauth2. I have a code, so I'm POSTing to https://stackexchange.com/oauth/access_token and ideally get an access_token back.
Instead I get an invalid_request error saying client_id not provided - below is my minimal reproduction case:
def oauth_explicit_two(client_id, client_secret, code, redirect_uri):
params = {'client_id': client_id, 'client_secret': client_secret,
'code': code, 'redirect_uri': redirect_uri}
connection = httplib.HTTPSConnection('stackexchange.com', strict=True)
connection.request('POST', '/oauth/access_token', urllib.urlencode(params))
#Used the below to route via CharlesProxy and dump request body
#connection = httplib.HTTPConnection('localhost:8888') # Via CharlesProxy
#connection.request('POST', 'https://stackexchange.com/oauth/access_token', urllib.urlencode(params))
response = connection.getresponse()
return response.read()
This is being called like so:
$ cat example.py
from stackpy import *
print oauth_explicit_two(274, 'elided', 'elided', 'http://stackcompare.com/')
And from this:
$ python example.py
{"error":{"type":"invalid_request","message":"client_id not provided"}}
From Charles, I've verified the POST body, in which client_id most definitely seems to appear:
client_secret=elided&code=elided&client_id=274&redirect_uri=http%3A%2F%2Fstackcompare.com%2F
So I'm currently at a bit of a loss, as I can't see how I'm not providing the client_id...
|
Services
The W3C defines a web service as "a software system designed to support interoperable machine-to-machine interaction over a network". This is a broad definition, and it encompasses a large number of protocols designed not for machine-to-human communication, but for machine-to-machine communication such as XML, JSON, RSS, etc.
In this chapter we discuss how to expose web services using web2py. If you are interested in examples of consuming third party services (Twitter, Dropbox, etc.) you should look into Chapter 9 and Chapter 14.
web2py provides, out of the box, support for many protocols, including XML, JSON, RSS, CSV, XMLRPC, JSONRPC, AMFRPC, and SOAP. web2py can also be extended to support additional protocols.
Each of those protocols are supported in multiple ways, and we make a distinction between:
Rendering the output of a function in a given format (for example XML, JSON, RSS, CSV)
Remote Procedure Calls (for example XMLRPC, JSONRPC, AMFRPC)
Rendering a dictionary
HTML, XML, and JSON
Consider the following action:
def count():
session.counter = (session.counter or 0) + 1
return dict(counter=session.counter, now=request.now)
This action returns a counter that is increased by one when a visitor reloads the page, and the timestamp of the current page request.
Normally this page would be requested via:
http://127.0.0.1:8000/app/default/count
and rendered in HTML. Without writing one line of code, we can ask web2py to render this page using different protocols by adding an extension to the URL:
http://127.0.0.1:8000/app/default/count.html
http://127.0.0.1:8000/app/default/count.xml
http://127.0.0.1:8000/app/default/count.json
The dictionary returned by the action will be rendered in HTML, XML and JSON, respectively.
Here is the XML output:
<document>
<counter>3</counter>
<now>2009-08-01 13:00:00</now>
</document>
Here is the JSON output:
{ 'counter':3, 'now':'2009-08-01 13:00:00' }
Notice that date, time and datetime objects are rendered as strings in ISO format. This is not part of the JSON standard, but rather a web2py convention.
Generic views
When, for example, the ".xml" extension is called, web2py looks for a template file called "default/count.xml", and if it does not find it, looks for a template called "generic.xml". The files "generic.html", "generic.xml", "generic.json" are provided with the current scaffolding application. Other extensions can be easily defined by the user.
For security reasons the generic views are only allowed to be accessed on localhost. In order to enable the access from remote clients you may need to set the response.generic_patterns.
Assuming you are using a copy of scaffold app, edit the following line in models/db.py
restrict access only to localhost
response.generic_patterns = ['*'] if request.is_local else []
to allow all generic views
response.generic_patterns = ['*']
to allow only .json
response.generic_patterns = ['*.json']
The generic_patterns is a glob pattern, it means you can use any patterns that matches with your app actions or pass a list of patterns.
response.generic_patterns = ['*.json','*.xml']
To use it in an older web2py app, you may need to copy the "generic.*" files from a later scaffolding app (after version 1.60).
Here is the code for "generic.html"
{{extend 'layout.html'}}
{{=BEAUTIFY(response._vars)}}
<button onclick="document.location='{{=URL("admin","default","design",
args=request.application)}}'">admin</button>
<button onclick="jQuery('#request').slideToggle()">request</button>
<div class="hidden" id="request"><h2>request</h2>{{=BEAUTIFY(request)}}</div>
<button onclick="jQuery('#session').slideToggle()">session</button>
<div class="hidden" id="session"><h2>session</h2>{{=BEAUTIFY(session)}}</div>
<button onclick="jQuery('#response').slideToggle()">response</button>
<div class="hidden" id="response"><h2>response</h2>{{=BEAUTIFY(response)}}</div>
<script>jQuery('.hidden').hide();</script>
Here is the code for "generic.xml"
{{
try:
from gluon.serializers import xml
response.write(xml(response._vars),escape=False)
response.headers['Content-Type']='text/xml'
except:
raise HTTP(405,'no xml')
}}
And here is the code for "generic.json"
{{
try:
from gluon.serializers import json
response.write(json(response._vars),escape=False)
response.headers['Content-Type']='text/json'
except:
raise HTTP(405,'no json')
}}
Any dictionary can be rendered in HTML, XML and JSON as long as it only contains python primitive types (int, float, string, list, tuple, dictionary). response._vars contains the dictionary returned by the action.
If the dictionary contains other user-defined or web2py-specific objects, they must be rendered by a custom view.
Rendering Rows
If you need to render a set of Rows as returned by a select in XML or JSON or another format, first transform the Rows object into a list of dictionaries using the as_list() method.
Consider for example the following mode:
db.define_table('person', Field('name'))
The following action can be rendered in HTML, but not in XML or JSON:
def everybody():
people = db().select(db.person.ALL)
return dict(people=people)
while the following action can rendered in XML and JSON:
def everybody():
people = db().select(db.person.ALL).as_list()
return dict(people=people)
Custom formats
If, for example, you want to render an action as a Python pickle:
http://127.0.0.1:8000/app/default/count.pickle
you just need to create a new view file "default/count.pickle" that contains:
{{
import cPickle
response.headers['Content-Type'] = 'application/python.pickle'
response.write(cPickle.dumps(response._vars),escape=False)
}}
If you want to be able to render any action as a pickled file, you need only to save the above file with the name "generic.pickle".
Not all objects are pickleable, and not all pickled objects can be un-pickled. It is safe to stick to primitive Python objects and combinations of them. Objects that do not contain references to file streams or database connections are usually pickleable, but they can only be un-pickled in an environment where the classes of all pickled objects are already defined.
RSS
web2py includes a "generic.rss" view that can render the dictionary returned by the action as an RSS feed.
Because the RSS feeds have a fixed structure (title, link, description, items, etc.) then for this to work, the dictionary returned by the action must have the proper structure:
{'title' : '',
'link' : '',
'description': '',
'created_on' : '',
'entries' : []}
and each entry in entries must have the same similar structure:
{'title' : '',
'link' : '',
'description': '',
'created_on' : ''}
For example the following action can be rendered as an RSS feed:
def feed():
return dict(title="my feed",
link="http://feed.example.com",
description="my first feed",
entries=[
dict(title="my feed",
link="http://feed.example.com",
description="my first feed")
])
by simply visiting the URL:
http://127.0.0.1:8000/app/default/feed.rss
Alternatively, assuming the following model:
db.define_table('rss_entry',
Field('title'),
Field('link'),
Field('created_on','datetime'),
Field('description'))
the following action can also be rendered as an RSS feed:
def feed():
return dict(title="my feed",
link="http://feed.example.com",
description="my first feed",
entries=db().select(db.rss_entry.ALL).as_list())
The as_list() method of a Rows object converts the rows into a list of dictionaries.
If additional dictionary items are found with key names not explicitly listed here, they are ignored.
Here is the "generic.rss" view provided by web2py:
{{
try:
from gluon.serializers import rss
response.write(rss(response._vars),escape=False)
response.headers['Content-Type']='application/rss+xml'
except:
raise HTTP(405,'no rss')
}}
As one more example of an RSS application, we consider an RSS aggregator that collects data from the "slashdot" feed and returns a new web2py rss feed.
def aggregator():
import gluon.contrib.feedparser as feedparser
d = feedparser.parse(
"http://rss.slashdot.org/Slashdot/slashdot/to")
return dict(title=d.channel.title,
link = d.channel.link,
description = d.channel.description,
created_on = request.now,
entries = [
dict(title = entry.title,
link = entry.link,
description = entry.description,
created_on = request.now) for entry in d.entries])
It can be accessed at:
http://127.0.0.1:8000/app/default/aggregator.rss
CSV
The Comma Separated Values (CSV) format is a protocol to represent tabular data.
Consider the following model:
db.define_table('animal',
Field('species'),
Field('genus'),
Field('family'))
and the following action:
def animals():
animals = db().select(db.animal.ALL)
return dict(animals=animals)
web2py does not provide a "generic.csv"; you must define a custom view "default/animals.csv" that serializes the animals into CSV. Here is a possible implementation:
{{
import cStringIO
stream=cStringIO.StringIO()
animals.export_to_csv_file(stream)
response.headers['Content-Type']='application/vnd.ms-excel'
response.write(stream.getvalue(), escape=False)
}}
Notice that one could also define a "generic.csv" file, but one would have to specify the name of the object to be serialized ("animals" in the example). This is why we do not provide a "generic.csv" file.
Remote procedure calls
web2py provides a mechanism to turn any function into a web service. The mechanism described here differs from the mechanism described before because:
The function may take arguments
The function may be defined in a model or a module instead of controller
You may want to specify in detail which RPC method should be supported
It enforces a more strict URL naming convention
It is smarter than the previous methods because it works for a fixed set of protocols. For the same reason it is not as easily extensible.
To use this feature:
First, you must import and initiate a service object.
from gluon.tools import Service
service = Service()
This is already done in the "db.py" model file in the scaffolding application.
Second, you must expose the service handler in the controller:
def call():
session.forget()
return service()
This is already done in the "default.py" controller of the scaffolding application. Remove session.forget() if you plan to use session cookies with the services.
Third, you must decorate those functions you want to expose as a service. Here is a list of currently supported decorators:
@service.run
@service.xml
@service.json
@service.rss
@service.csv
@service.xmlrpc
@service.jsonrpc
@service.amfrpc3('domain')
@service.soap('FunctionName',returns={'result':type},args={'param1':type,})
As an example, consider the following decorated function:
@service.run
def concat(a,b):
return a+b
This function can be defined in a model or in the controller where the call action is defined. This function can now be called remotely in two ways:
http://127.0.0.1:8000/app/default/call/run/concat?a=hello&b=world
http://127.0.0.1:8000/app/default/call/run/concat/hello/world
In both cases the http request returns:
helloworld
If the @service.xml decorator is used, the function can be called via:
http://127.0.0.1:8000/app/default/call/xml/concat?a=hello&b=world
http://127.0.0.1:8000/app/default/call/xml/concat/hello/world
and the output is returned as XML:
<document> <result>helloworld</result></document>
It can serialize the output of the function even if this is a DAL Rows object. In this case, in fact, it will call as_list() automatically.
If the @service.json decorator is used, the function can be called via:
http://127.0.0.1:8000/app/default/call/json/concat?a=hello&b=world
http://127.0.0.1:8000/app/default/call/json/concat/hello/world
and the output returned as JSON.
If the @service.csv decorator is used, the service handler requires, as the return value, an iterable object of iterable objects, such as a list of lists. Here is an example:
@service.csv
def table1(a,b):
return [[a,b],[1,2]]
This service can be called by visiting one of the following URLs:
http://127.0.0.1:8000/app/default/call/csv/table1?a=hello&b=world
http://127.0.0.1:8000/app/default/call/csv/table1/hello/world
and it returns:
hello,world1,2
The @service.rss decorator expects a return value in the same format as the "generic.rss" view discussed in the previous section.
Multiple decorators are allowed for each function.
So far, everything discussed in this section is simply an alternative to the method described in the previous section. The real power of the service object comes with XMLRPC, JSONRPC and AMFRPC, as discussed below.
XMLRPC
Consider the following code, for example, in the "default.py" controller:
@service.xmlrpc
def add(a,b):
return a+b
@service.xmlrpc
def div(a,b):
return a/b
Now in a python shell you can do
>>> from xmlrpclib import ServerProxy
>>> server = ServerProxy(
'http://127.0.0.1:8000/app/default/call/xmlrpc')
>>> print server.add(3,4)
7
>>> print server.add('hello','world')
'helloworld'
>>> print server.div(12,4)
3
>>> print server.div(1,0)
ZeroDivisionError: integer division or modulo by zero
The Python xmlrpclib module provides a client for the XMLRPC protocol. web2py acts as the server.
The client connects to the server via ServerProxy and can remotely call decorated functions in the server. The data (a,b) is passed to the function(s), not via GET/POST variables, but properly encoded in the request body using the XMLPRC protocol, and thus it carries with itself type information (int or string or other). The same is true for the return value(s). Moreover, any exception raised on the server propagates back to the client.
There are XMLRPC libraries for many programming languages (including C, C++, Java, C#, Ruby, and Perl), and they can interoperate with each other. This is one the best methods to create applications that talk to each other independent of the programming language.
The XMLRPC client can also be implemented inside a web2py action, so that one action can talk to another web2py application (even within the same installation) using XMLRPC. Beware of session deadlocks in this case. If an action calls via XMLRPC a function in the same app, the caller must release the session lock before the call:
session.forget(response)
JSONRPC
In this section we are going to use the same code example as for XMLRPC but we will expose the service using JSONRPC instead:
@service.jsonrpc
def add(a,b):
return a+b
def call():
return service()
JSONRPC is very similar to XMLRPC but uses JSON instead of XML as data serialization protocol.
Of course we can call the service from any program in any language but here we will do it in Python. web2py ships with a module "gluon/contrib/simplejsonrpc.py" created by Mariano Reingart. Here is an example of how to use to call the above service:
>>> from gluon.contrib.simplejsonrpc import
>>> URL = "http://127.0.0.1:8000/app/default/call/jsonrpc"
>>> service = ServerProxy(URL, verbose=True)
>>> print service.add(1, 2)
JSONRPC and Pyjamas
JSONRPC is very similar to XMLRPC, but uses the JSON-based protocol instead of XML to encode the data. As an example of application here, we discuss its usage with Pyjamas. Pyjamas is a Python port of the Google Web Toolkit (originally written in Java). Pyjamas allows writing a client application in Python. Pyjamas translates this code into JavaScript. web2py serves the JavaScript and communicates with it via AJAX requests originating from the client and triggered by user actions.
Here we describe how to make Pyjamas work with web2py. It does not require any additional libraries other than web2py and Pyjamas.
We are going to build a simple "todo" application with a Pyjamas client (all JavaScript) that talks to the server exclusively via JSONRPC.
First, create a new application called "todo".
Second, in "models/db.py", enter the following code:
db=DAL('sqlite://storage.sqlite')
db.define_table('todo', Field('task'))
service = Service()
(Note: Service class is from gluon.tools).
Third, in "controllers/default.py", enter the following code:
def index():
redirect(URL('todoApp'))
@service.jsonrpc
def getTasks():
todos = db(db.todo).select()
return [(todo.task,todo.id) for todo in todos]
@service.jsonrpc
def addTask(taskFromJson):
db.todo.insert(task= taskFromJson)
return getTasks()
@service.jsonrpc
def deleteTask (idFromJson):
del db.todo[idFromJson]
return getTasks()
def call():
session.forget()
return service()
def todoApp():
return dict()
The purpose of each function should be obvious.
Fourth, in "views/default/todoApp.html", enter the following code:
<html>
<head>
<meta name="pygwt:module"
content="{{=URL('static','output/TodoApp')}}" />
<title>
simple todo application
</title>
</head>
<body bgcolor="white">
<h1>
simple todo application
</h1>
<i>
type a new task to insert in db,
click on existing task to delete it
</i>
<script language="javascript"
src="{{=URL('static','output/pygwt.js')}}">
</script>
</body>
</html>
This view just executes the Pyjamas code in "static/output/todoapp" - code that we have not yet created.
Fifth, in "static/TodoApp.py" (notice it is TodoApp, not todoApp!), enter the following client code:
from pyjamas.ui.RootPanel import RootPanel
from pyjamas.ui.Label import Label
from pyjamas.ui.VerticalPanel import VerticalPanel
from pyjamas.ui.TextBox import TextBox
import pyjamas.ui.KeyboardListener
from pyjamas.ui.ListBox import ListBox
from pyjamas.ui.HTML import HTML
from pyjamas.JSONService import JSONProxy
class TodoApp:
def onModuleLoad(self):
self.remote = DataService()
panel = VerticalPanel()
self.todoTextBox = TextBox()
self.todoTextBox.addKeyboardListener(self)
self.todoList = ListBox()
self.todoList.setVisibleItemCount(7)
self.todoList.setWidth("200px")
self.todoList.addClickListener(self)
self.Status = Label("")
panel.add(Label("Add New Todo:"))
panel.add(self.todoTextBox)
panel.add(Label("Click to Remove:"))
panel.add(self.todoList)
panel.add(self.Status)
self.remote.getTasks(self)
RootPanel().add(panel)
def onKeyUp(self, sender, keyCode, modifiers):
pass
def onKeyDown(self, sender, keyCode, modifiers):
pass
def onKeyPress(self, sender, keyCode, modifiers):
"""
This function handles the onKeyPress event, and will add the
item in the text box to the list when the user presses the
enter key. In the future, this method will also handle the
auto complete feature.
"""
if keyCode == KeyboardListener.KEY_ENTER and sender == self.todoTextBox:
id = self.remote.addTask(sender.getText(),self)
sender.setText("")
if id<0:
RootPanel().add(HTML("Server Error or Invalid Response"))
def onClick(self, sender):
id = self.remote.deleteTask(
sender.getValue(sender.getSelectedIndex()),self)
if id<0:
RootPanel().add(
HTML("Server Error or Invalid Response"))
def onRemoteResponse(self, response, request_info):
self.todoList.clear()
for task in response:
self.todoList.addItem(task[0])
self.todoList.setValue(self.todoList.getItemCount()-1,
task[1])
def onRemoteError(self, code, message, request_info):
self.Status.setText("Server Error or Invalid Response: " + "ERROR " + code + " - " + message)
class DataService(JSONProxy):
def __init__(self):
JSONProxy.__init__(self, "../../default/call/jsonrpc",
["getTasks", "addTask","deleteTask"])
if __name__ == '__main__':
app = TodoApp()
app.onModuleLoad()
Sixth, run Pyjamas before serving the application:
cd /path/to/todo/static/
python /python/pyjamas-0.5p1/bin/pyjsbuild TodoApp.py
This will translate the Python code into JavaScript so that it can be executed in the browser.
To access this application, visit the URL:
http://127.0.0.1:8000/todo/default/todoApp
This subsection was created by Chris Prinos with help from Luke Kenneth Casson Leighton (creators of Pyjamas), updated by Alexei Vinidiktov. It has been tested with Pyjamas 0.5p1. The example was inspired by this Django page in ref.[blogspot1].
Amfrpc
AMFRPC is the Remote Procedure Call protocol used by Flash clients to communicate with a server. web2py supports AMFRPC, but it requires that you run web2py from source and that you preinstall the PyAMF library. This can be installed from the Linux or Windows shell by typing:
easy_install pyamf
(please consult the PyAMF documentation for more details).
In this subsection we assume that you are already familiar with ActionScript programming.
We will create a simple service that takes two numerical values, adds them together, and returns the sum. We will call our web2py application "pyamf_test", and we will call the service addNumbers.
First, using Adobe Flash (any version starting from MX 2004), create the Flash client application by starting with a new Flash FLA file. In the first frame of the file, add these lines:
import mx.remoting.Service;
import mx.rpc.RelayResponder;
import mx.rpc.FaultEvent;
import mx.rpc.ResultEvent;
import mx.remoting.PendingCall;
var val1 = 23;
var val2 = 86;
service = new Service(
"http://127.0.0.1:8000/pyamf_test/default/call/amfrpc3",
null, "mydomain", null, null);
var pc:PendingCall = service.addNumbers(val1, val2);
pc.responder = new RelayResponder(this, "onResult", "onFault");
function onResult(re:ResultEvent):Void {
trace("Result : " + re.result);
txt_result.text = re.result;
}
function onFault(fault:FaultEvent):Void {
trace("Fault: " + fault.fault.faultstring);
}
stop();
This code allows the Flash client to connect to a service that corresponds to a function called "addNumbers" in the file "/pyamf_test/default/gateway". You must also import ActionScript version 2 MX remoting classes to enable Remoting in Flash. Add the path to these classes to the classpath settings in the Adobe Flash IDE, or just place the "mx" folder next to the newly created file.
Notice the arguments of the Service constructor. The first argument is the URL corresponding to the service that we want will create. The third argument is the domain of the service. We choose to call this domain "mydomain".
Second, create a dynamic text field called "txt_result" and place it on the stage.
Third, you need to set up a web2py gateway that can communicate with the Flash client defined above.
Proceed by creating a new web2py app called pyamf_test that will host the new service and the AMF gateway for the flash client. Edit the "default.py" controller and make sure it contains
@service.amfrpc3('mydomain')
def addNumbers(val1, val2):
return val1 + val2
def call(): return service()
Fourth, compile and export/publish the SWF flash client as pyamf_test.swf, place the "pyamf_test.amf", "pyamf_test.html", "AC_RunActiveContent.js", and "crossdomain.xml" files in the "static" folder of the newly created appliance that is hosting the gateway, "pyamf_test".
You can now test the client by visiting:
http://127.0.0.1:8000/pyamf_test/static/pyamf_test.html
The gateway is called in the background when the client connects to addNumbers.
If you are using AMF0 instead of AMF3 you can also use the decorator:
@service.amfrpc
instead of:
@service.amfrpc3('mydomain')
In this case you also need to change the service URL to:
http://127.0.0.1:8000/pyamf_test/default/call/amfrpc
SOAP
web2py includes a SOAP client and server created by Mariano Reingart. It can be used very much like XML-RPC:
Consider the following code, for example, in the "default.py" controller:
@service.soap('MyAdd',returns={'result':int},args={'a':int,'b':int,})
def add(a,b):
return a+b
Now in a python shell you can do:
>>> from gluon.contrib.pysimplesoap.client import SoapClient
>>> client = SoapClient(wsdl="http://localhost:8000/app/default/call/soap?WSDL")
>>> print client.MyAdd(a=1,b=2)
{'result': 3}
To get proper encoding when returning a text values, specify string as u'proper utf8 text'.
You can obtain the WSDL for the service at
http://127.0.0.1:8000/app/default/call/soap?WSDL
And you can obtain documentation for any of the exposed methods:
http://127.0.0.1:8000/app/default/call/soap
Low level API and other recipes
simplejson
web2py includes gluon.contrib.simplejson, developed by Bob Ippolito. This module provides the most standard Python-JSON encoder-decoder.
SimpleJSON consists of two functions:
gluon.contrib.simplesjson.dumps(a)encodes a Python objectainto JSON.
gluon.contrib.simplejson.loads(b)decodes a JavaScript objectbinto a Python object.
Object types that can be serialized include primitive types, lists, and dictionaries. Compound objects can be serialized with the exception of user defined classes.
Here is a sample action (for example in controller "default.py") that serializes the Python list containing weekdays using this low level API:
def weekdays():
names=['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday']
import gluon.contrib.simplejson
return gluon.contrib.simplejson.dumps(names)
Below is a sample HTML page that sends an Ajax request to the above action, receives the JSON message and stores the list in a corresponding JavaScript variable:
{{extend 'layout.html'}}
<script>
$.getJSON('/application/default/weekdays',
function(data){ alert(data); });
</script>
The code uses the jQuery function $.getJSON, which performs the Ajax call and, on response, stores the weekdays names in a local JavaScript variable data and passes the variable to the callback function. In the example the callback function simply alerts the visitor that the data has been received.
PyRTF
Another common need of web sites is that of generating Word-readable text documents. The simplest way to do so is using the Rich Text Format (RTF) document format. This format was invented by Microsoft and it has since become a standard.
web2py includes gluon.contrib.pyrtf, developed by Simon Cusack and revised by Grant Edwards. This module allows you to generate RTF documents programmatically, including colored formatted text and pictures.
In the following example we initiate two basic RTF classes, Document and Section, append the latter to the former and insert some dummy text in the latter:
def makertf():
import gluon.contrib.pyrtf as q
doc=q.Document()
section=q.Section()
doc.Sections.append(section)
section.append('Section Title')
section.append('web2py is great. '*100)
response.headers['Content-Type']='text/rtf'
return q.dumps(doc)
In the end the Document is serialized by q.dumps(doc). Notice that before returning an RTF document it is necessary to specify the content-type in the header else the browser does not know how to handle the file.
Depending on the configuration, the browser may ask you whether to save this file or open it using a text editor.
ReportLab and PDF
web2py can also generate PDF documents, with an additional library called "ReportLab"[ReportLab] .
If you are running web2py from source, it is sufficient to have ReportLab installed. If you are running the Windows binary distribution, you need to unzip ReportLab in the "web2py/" folder. If you are running the Mac binary distribution, you need to unzip ReportLab in the folder:
web2py.app/Contents/Resources/
From now on we assume ReportLab is installed and that web2py can find it. We will create a simple action called "get_me_a_pdf" that generates a PDF document.
from reportlab.platypus import *
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.rl_config import defaultPageSize
from reportlab.lib.units import inch, mm
from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER, TA_JUSTIFY
from reportlab.lib import colors
from uuid import uuid4
from cgi import escape
import os
def get_me_a_pdf():
title = "This The Doc Title"
heading = "First Paragraph"
text = 'bla '* 10000
styles = getSampleStyleSheet()
tmpfilename=os.path.join(request.folder,'private',str(uuid4()))
doc = SimpleDocTemplate(tmpfilename)
story = []
story.append(Paragraph(escape(title),styles["Title"]))
story.append(Paragraph(escape(heading),styles["Heading2"]))
story.append(Paragraph(escape(text),styles["Normal"]))
story.append(Spacer(1,2*inch))
doc.build(story)
data = open(tmpfilename,"rb").read()
os.unlink(tmpfilename)
response.headers['Content-Type']='application/pdf'
return data
Notice how we generate the PDF into a unique temporary file, tmpfilename, we read the generated PDF from the file, then we deleted the file.
For more information about the ReportLab API, refer to the ReportLab documentation. We strongly recommend using the Platypus API of ReportLab, such as Paragraph, Spacer, etc.
Restful Web Services
REST stands for "REpresentational State Transfer" and it is a type of web service architecture and not, like SOAP, a protocol. In fact there is no standard for REST.
Loosely speaking REST says that a service can be thought of as a collection of resources. Each resource should be identified by a URL. There are four methods actions on a resource and they are POST (create), GET (read), PUT (update) and DELETE, from which the acronym CRUD (create-read-update-delete) stands for. A client communicates with the resource by making an HTTP request to the URL that identifies the resource and using the HTTP method POST/PUT/GET/DELETE to pass instructions to the resource. The URL may have an extension, for example json that specify how the protocol for encoding the data.
So for example a POST request to
http://127.0.0.1/myapp/default/api/person
means that you want to create a new person. In this case a person may correspond to a record in table person but may also be some other type of resource (for example a file).
Similarly a GET request to
http://127.0.0.1/myapp/default/api/persons.json
indicates a request for a list of persons (records from the data person) in json format.
A GET request to
http://127.0.0.1/myapp/default/api/person/1.json
indicates a request for the information associated to person/1 (the record with id==1) and in json format.
In the case of web2py each request can be split into three parts:
A first part that identify the location of the service, i.e. the action that exposes the service:
http://127.0.0.1/myapp/default/api/
The name of the resource (person,persons,person/1, etc.)
The communication protocol specified y the extension.
Notice that we can always use the router to eliminate any unwanted prefix in the URL and for example simplify this:
http://127.0.0.1/myapp/default/api/person/1.json
into this:
http://127.0.0.1/api/person/1.json
yet this is a matter of test and we have already discussed it at length in chapter 4.
In our example we used an action called api but this is not a requirement. We can in fact name the action that exposes the RESTful service any way we like and we can in fact even create more than one. For the sake of argument we will continue to assume that our RESTful action is called api.
We will also assume we have defined the following two tables:
db.define_table('person',Field('name'),Field('info'))
db.define_table('pet',Field('owner',db.person),Field('name'),Field('info'))
and they are the resources we want to expose.
The first thing we do is create the RESTful action:
def api():
return locals()
Now we modify it so that the extension is filtered out of the request args (so that request.args can be used to identify the resource) and so that it can handle the different methods separately:
@request.restful()
def api():
def GET(*args,**vars):
return dict()
def POST(*args,**vars):
return dict()
def PUT(*args,**vars):
return dict()
def DELETE(*args,**vars):
return dict()
return locals()
Now when we make a GET http request to
http://127.0.0.1:8000/myapp/default/api/person/1.json
it calls and returns GET('person','1') where GET is the function defined inside the action. Notice that:
we do not need to define all four methods, only those that we wish to expose.
the method function can take named arguments
the extension is stored in request.extensionand the content type is set automatically.
The@request.restful()decorator makes sure that the extension in the path info is stored intorequest.extension, maps the request method into the corresponding function within the action (POST, GET, PUT, DELETE), and passesrequest.argsandrequest.varsto the selected function.
Now we build a service to POST and GET individual records:
@request.restful()
def api():
response.view = 'generic.json'
def GET(tablename,id):
if not tablename=='person': raise HTTP(400)
return dict(person = db.person(id))
def POST(tablename,**fields):
if not tablename=='person': raise HTTP(400)
return db.person.validate_and_insert(**fields)
return locals()
Notice that:
the GET and POST are dealt with by different functions
the function expect the correct arguments (un-named arguments parsed by request.argsand named arguments are fromrequest.vars)
they check the input is correct and eventually raise an exception
GET perform a select and returns the record, db.person(id). The output is automatically converted to JSON because the generic view is called.
POST performs a validate_and_insert(..)and returns theidof the new record or, alternatively, validation errors. The POST variables,**fields, are the post variables.
parse_as_rest (experimental)
The logic explained so far is sufficient to create any type of RESTful web service yet web2py helps us even more.
In fact, web2py provides a syntax to describe which database tables we want to expose and how to map resource into URLs and vice versa.
This is done using URL patterns. A pattern is a string that maps the request args from a URL into a database query. There 4 types of atomic patterns:
String constants for example "friend"
String constant corresponding to a table. For example "friend[person]" will match "friends" in the URL to the "person" table.
Variables to be used to filter. For example "{person.id}" will apply a db.person.name=={person.id}filter.
Names of fields, represented by ":field"
Atomic patters can be combined into complex URL patters using "/" such as in
"/friend[person]/{person.id}/:field"
which gives a url of the form
http://..../friend/1/name
Into a query for a person.id that returns the name of the person. Here "friend[person]" matches "friend" and filters the table "person". "{person.id}" matches "1" and filters "person.id==1". ":field" matches "name" and returns:
db(db.person.id==1).select().first().name
Multiple URL patters can be combined into a list so that one single RESTful action can serve different types of requests.
The DAL has a method parse_as_rest(pattern,args,vars) that given a list of patterns, the request.args and the request.vars matches the pattern and returns a response (GET only).
So here is a more complex example:
@request.restful()
def api():
response.view = 'generic.'+request.extension
def GET(*args,**vars):
patterns = [
"/friends[person]",
"/friend/{person.name.startswith}",
"/friend/{person.name}/:field",
"/friend/{person.name}/pets[pet.owner]",
"/friend/{person.name}/pet[pet.owner]/{pet.name}",
"/friend/{person.name}/pet[pet.owner]/{pet.name}/:field"
]
parser = db.parse_as_rest(patterns,args,vars)
if parser.status == 200:
return dict(content=parser.response)
else:
raise HTTP(parser.status,parser.error)
def POST(table_name,**vars):
if table_name == 'person':
return db.person.validate_and_insert(**vars)
elif table_name == 'pet':
return db.pet.validate_and_insert(**vars)
else:
raise HTTP(400)
return locals()
Which understands the following URLs that correspond to the listed patters:
GET all persons
http://.../api/friends
GET one person with name starting with "t"
http://.../api/friend/t
GET the "info" field value of the first person with name equal to "Tim"
http://.../api/friend/Tim/info
GET a list of pets of the person (friend) above
http://.../api/friend/Tim/pets
GET the pet with name "Snoopy of person with name "Tim"
http://.../api/friend/Tim/pet/Snoopy
GET the "info" field value for the pet
http://.../api/friend/Tim/pet/Snoopy/info
The action also exposes two POST urls:
POST a new friend
POST a new pet
If you have the "curl" utility installed you can try:
$ curl -d "name=Tim" http://127.0.0.1:8000/myapp/default/api/friend.json
{"errors": {}, "id": 1}
$ curl http://127.0.0.1:8000/myapp/default/api/friends.json
{"content": [{"info": null, "name": "Tim", "id": 1}]}
$ curl -d "name=Snoopy&owner=1" http://127.0.0.1:8000/myapp/default/api/pet.json
{"errors": {}, "id": 1}
$ curl http://127.0.0.1:8000/myapp/default/api/friend/Tim/pet/Snoopy.json
{"content": [{"info": null, "owner": 1, "name": "Snoopy", "id": 1}]}
It is possible to declare more complex queries such where a value in the URL is used to build a query not involving equality. For example
patterns = ['friends/{person.name.contains}'
maps
http://..../friends/i
into
db.person.name.contains('i')
And similarly:
patterns = ['friends/{person.name.ge}/{person.name.gt.not}'
maps
http://..../friends/aa/uu
into
(db.person.name>='aa')&(~(db.person.name>'uu'))
valid attributes for a field in a pattern are: contains, startswith, le, ge, lt, gt, eq (equal, default), ne (not equal). Other attributes specifically for date and datetime fields are day, month, year, hour, minute, second.
Notice that this pattern syntax is not designed to be general. Not every possible query can be described via a pattern but a lot of them are. The syntax may be extended in the future.
Often you want to expose some RESTful URLs but you want to restrict the possible queries. This can be done by passing an extra argument queries to the parse_as_rest method. queries is a dictionary of (tablename,query) where query is a DAL query to restrict access to table tablename.
We can also order results using the order GET variables
http://..../api/friends?order=name|~info
which order alphabetically (name) and then by reversed info order.
We can also limit the number of records by specifying a limit and offset GET variables
http://..../api/friends?offset=10&limit=1000
which will return up to 1000 friends (persons) and skip the first 10. limit defaults to 1000 and offset default to 0.
Let's now consider an extreme case. We want to build all possible patterns for all tables (except auth_ tables). We want to be able to search by any text field, any integer field, any double field (by range) and any date (also by range). We also want to be able to POST into any table:
In the general case this requires a lot of patterns. Web2py makes it simple:
@request.restful()
def api():
response.view = 'generic.'+request.extension
def GET(*args,**vars):
patterns = 'auto'
parser = db.parse_as_rest(patterns,args,vars)
if parser.status == 200:
return dict(content=parser.response)
else:
raise HTTP(parser.status,parser.error)
def POST(table_name,**vars):
return db[table_name].validate_and_insert(**vars)
return locals()
Settings patterns='auto' results in web2py generating all possible patterns for all non-auth tables. There is even a pattern for querying about patterns:
http://..../api/patterns.json
which for out person and pet tables results in:
{"content": [
"/person[person]",
"/person/id/{person.id}",
"/person/id/{person.id}/:field",
"/person/id/{person.id}/pet[pet.owner]",
"/person/id/{person.id}/pet[pet.owner]/id/{pet.id}",
"/person/id/{person.id}/pet[pet.owner]/id/{pet.id}/:field",
"/person/id/{person.id}/pet[pet.owner]/owner/{pet.owner}",
"/person/id/{person.id}/pet[pet.owner]/owner/{pet.owner}/:field",
"/person/name/pet[pet.owner]",
"/person/name/pet[pet.owner]/id/{pet.id}",
"/person/name/pet[pet.owner]/id/{pet.id}/:field",
"/person/name/pet[pet.owner]/owner/{pet.owner}",
"/person/name/pet[pet.owner]/owner/{pet.owner}/:field",
"/person/info/pet[pet.owner]",
"/person/info/pet[pet.owner]/id/{pet.id}",
"/person/info/pet[pet.owner]/id/{pet.id}/:field",
"/person/info/pet[pet.owner]/owner/{pet.owner}",
"/person/info/pet[pet.owner]/owner/{pet.owner}/:field",
"/pet[pet]",
"/pet/id/{pet.id}",
"/pet/id/{pet.id}/:field",
"/pet/owner/{pet.owner}",
"/pet/owner/{pet.owner}/:field"
]}
You can specify auto patterns for some tables only:
patterns = [':auto[person]',':auto[pet]']
smart_query (experimental)
There are times when you need more flexibility and you want to be able to pass to a RESTful service an arbitrary query like
http://.../api.json?search=person.name starts with 'T' and person.name contains 'm'
You can do this using
@request.restful()
def api():
response.view = 'generic.'+request.extension
def GET(search):
try:
rows = db.smart_query([db.person,db.pet],search).select()
return dict(result=rows)
except RuntimeError:
raise HTTP(400,"Invalid search string")
def POST(table_name,**vars):
return db[table_name].validate_and_insert(**vars)
return locals()
The method db.smart_query takes two arguments:
a list of field or table that should be allowed in the query
a string containing the query expressed in natural language
and it returns a db.set object with the records that have been found.
Notice that the search string is parsed, not evaluated or executed and therefore it provides no security risk.
Access Control
Access to the API can be restricted as usual by using decorators. So, for example
auth.settings.allow_basic_login = True
@auth.requires_login()
@request.restful()
def api():
def GET(s):
return 'access granted, you said %s' % s
return locals()
can now be accessed with
$ curl --user name:password http://127.0.0.1:8000/myapp/default/api/hello
access granted, you said hello
Services and Authentication
In the previous chapter we have discussed the use of the following decorators:
@auth.requires_login()
@auth.requires_membership(...)
@auth.requires_permission(...)
For normal actions (not decorated as services), these decorators can be used even if the output is rendered in a format other than HTML.
For functions defined as services and decorated using the @service... decorators, the @auth... decorators should not be used. The two types of decorators cannot be mixed. If authentication is to be performed, it is the call actions that needs to be decorated:
@auth.requires_login()
def call(): return service()
Notice that it also possible to instantiate multiple service objects, register the same different functions with them, and expose some of them with authentication and some not:
public_services=Service()
private_services=Service()
@public_service.jsonrpc
@private_service.jsonrpc
def f(): return 'public'
@private_service.jsonrpc
def g(): return 'private'
def public_call(): return public_service()
@auth.requires_login()
def private_call(): return private_service()
This assumes that the caller is passing credentials in the HTTP header (a valid session cookie or using basic authentication, as discussed in the previous section). The client must support it; not all clients do.
top
|
I am having an application developed in python and google app engine, but when i am try to customize this application then it is giving me compile time error in the previous code which is running fine on live. Code is:
if version in ['beta', 'alpha'] :
type=version
version = memcache.get(type)
if not version:
v = RouterVersions.get_by_key_name(type)
if not v :
logging.error('No version found in RouterModel for %s', type)
self.error(404)
return;
version = v.version
memcache.add(v.type, version)
whenver i am using memcache.add or get property it is giving compile time error "undefined variable from import get". I am not able to know why is it so. I am new to python and google app engine. My application was created in python 2.5 and i am using 2.7 now. Is that the issue or something else ?
|
The current backend name is accessible via
>>> import matplotlib.pyplot as plt >>> plt.get_backend() 'GTKAgg'
Is there a way to get a list of all backends that can be used on a particular machine?
Thanks in advance.
You can access the lists
the third being the concatenation of the former two. If I read the source code correctly, those lists are hard-coded though, and don't tell you what backends are actually usable. There is also
matplotlib.rcsetup.validate_backend(name)
but this also only checks against the hard-coded list.
Here is a modification of the script posted previously. It finds all supported backends, validates them and measures their fps. On OSX it crashes python when it comes to tkAgg, so use at your own risk ;)
from pylab import *
import time
import matplotlib.backends
import matplotlib.pyplot as p
import os.path
def is_backend_module(fname):
"""Identifies if a filename is a matplotlib backend module"""
return fname.startswith('backend_') and fname.endswith('.py')
def backend_fname_formatter(fname):
"""Removes the extension of the given filename, then takes away the leading 'backend_'."""
return os.path.splitext(fname)[0][8:]
# get the directory where the backends live
backends_dir = os.path.dirname(matplotlib.backends.__file__)
# filter all files in that directory to identify all files which provide a backend
backend_fnames = filter(is_backend_module, os.listdir(backends_dir))
backends = [backend_fname_formatter(fname) for fname in backend_fnames]
print "supported backends: \t" + str(backends)
# validate backends
backends_valid = []
for b in backends:
try:
p.switch_backend(b)
backends_valid += [b]
except:
continue
print "valid backends: \t" + str(backends_valid)
# try backends performance
for b in backends_valid:
ion()
try:
p.switch_backend(b)
clf()
tstart = time.time() # for profiling
x = arange(0,2*pi,0.01) # x-array
line, = plot(x,sin(x))
for i in arange(1,200):
line.set_ydata(sin(x+i/10.0)) # update the data
draw() # redraw the canvas
print b + ' FPS: \t' , 200/(time.time()-tstart)
ioff()
except:
print b + " error :("
There is the hard-coded list mentioned by Sven, but to find every backend which Matplotlib can use (based on the current implementation for setting up a backend) the
The following code does this:
import matplotlib.backends
import os.path
def is_backend_module(fname):
"""Identifies if a filename is a matplotlib backend module"""
return fname.startswith('backend_') and fname.endswith('.py')
def backend_fname_formatter(fname):
"""Removes the extension of the given filename, then takes away the leading 'backend_'."""
return os.path.splitext(fname)[0][8:]
# get the directory where the backends live
backends_dir = os.path.dirname(matplotlib.backends.__file__)
# filter all files in that directory to identify all files which provide a backend
backend_fnames = filter(is_backend_module, os.listdir(backends_dir))
backends = [backend_fname_formatter(fname) for fname in backend_fnames]
print backends
You can also see some documentation for a few backends here:
the pages lists just a few backends, some of them don't have a proper documentation:
You could look at the following folder for a list of possible backends...
/Library/Python/2.6/site-packages/matplotlib/backends
/usr/lib64/Python2.6/site-packages/matplotlib/backends
|
You can write anything as a migration. That's the point!
Once you have South up and running, type in python manage.py schemamigration myapp --empty my_custom_migration to create a blank migration that you can customize.
Open up the XXXX_my_custom_migration.py file in myapp/migrations/ and type in your custom SQL migration there in the forwards method. For example you could use db.execute
The migration might look something like this:
class Migration(SchemaMigration):
def forwards(self, orm):
db.execute("CREATE FULLTEXT INDEX foo ON bar (foobar)")
print "Just created a fulltext index..."
print "And calculated {answer}".format(answer=40+2)
def backwards(self, orm):
raise RuntimeError("Cannot reverse this migration.")
# or what have you
$ python manage.py migrate myapp XXXX # or just python manage.py migrate.
"Just created fulltext index...."
"And calculated 42"
|
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...
~38 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.
[4/5/2012] Challenge #36 [easy] (self.dailyprogrammer)
submitted 2 years ago by mattryan
1000 Lockers Problem.
In an imaginary high school there exist 1000 lockers labelled 1, 2, ..., 1000. All of them are closed. 1000 students are to "toggle" a locker's state. * The first student toggles all of them * The second one toggles every other one (i.e, 2, 4, 6, ...) * The third one toggles the multiples of 3 (3, 6, 9, ...) and so on until all students have finished.
To toggle means to close the locker if it is open, and to open it if it's closed.
How many and which lockers are open in the end?
Thanks to ladaghini for submitting this challenge to /r/dailyprogrammer_ideas!
[–]blisse 8 points9 points10 points 2 years ago (2 children)
Can someone explain why the output is exactly all the squares? I sort of get it, but I would like a more in-depth answer.
eruonna just wrote a script for the result, which was cool, but didn't explain why it ended like that.
[–]luxgladius0 0 7 points8 points9 points 2 years ago (0 children)
Let the factors of a number n be f1, f2, f3, f4,... where f1 * f2=f3 * f4 ...= n. Naturally all the factors must be less than or equal to n. Equally naturally, they all must occur in pairs EXCEPT if f1=f2, which is to say that n is a perfect square. So each number in an interval has an even number of factors unless it is a perfect square. An even number of toggles equates to a closed state since counting by each factor you will pass over the number once, so each locker is closed except for those perfect squares.
Example: 8 has factors 1, 2, 4, and 8. 9 has factors 1, 3, and 9. Therefore 8 will be toggled four times (closed) and 9 will be toggled 3 times (open).
[–]HazzyPls0 0 2 points3 points4 points 2 years ago (0 children)
singingbanana has a nice video on it.
[–]luxgladius0 0 2 points3 points4 points 2 years ago (0 children)
Perl
@locker = map 0, 1 .. 1000; for my $student (1 .. 1000) { for(my $l = $student; $l <= 1000; $l += $student) { $locker[$l-1] = !$locker[$l-1]; } } @open = grep $locker[$_-1],1 .. 1000; print "Open lockers: ", 0+@open, "\n"; print join(", ", @open),"\n";
Output
Open lockers: 311, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961
[–]eruonna 4 points5 points6 points 2 years ago (1 child)
Haskell:
openLockers n = [x*x | x <- [1..floor$sqrt$fromIntegral n]]
Output:
[1,4,9,16,25,36,49,64,81,100,121,144,169,196,225,256,289,324,361,400,441,484,529,576,625,676,729,784,841,900,961]
[–]namekuseijin 1 point2 points3 points 2 years ago (0 children)
good, you compiled the solution in your math mind and wrote a short haskell expression that generates it...
[–]Ttl 1 point2 points3 points 2 years ago (0 children)
Mathematica:
Select[Table[i,{i,1,1000}],OddQ[Length[Divisors[#]]]&]
[–]school_throwaway 1 point2 points3 points 2 years ago (0 children)
python
lockers=[] open_lockers=[] for x in range(1001): lockers.append(True) for x in range(1,1001): for y in range(1,1000): if y % x == 0: if lockers[y] is False: lockers[y] = True else: lockers[y] = False for x in range(len(lockers)): if lockers[x] == False: open_lockers.append(x) print open_lockers
[–]HazzyPls0 0 1 point2 points3 points 2 years ago (1 child)
C.
Tried to get a quick result without manually opening and closing each locker, or without simply squaring.
#include <math.h> #include <stdio.h> #include <stdlib.h> int* lockers_open(int n, size_t* size) { int sqrt_n = sqrt( n ); int* arr = malloc( sqrt_n * sizeof(int)); int i = 1, j = 1, k = 0; for(; i < n; j += 2, i += j, k++) { arr[k] = i; } *size = k; return arr; } int main(int argc, char** argv) { int max = (argc >= 2) ? atoi(argv[1]) : 1000; size_t size = 0; int* lockers = lockers_open(max, &size); unsigned i; for(i = 0; i < size; i++) { printf(" %d : %d\n", i + 1, lockers[i]); } free(lockers); return 0; }
[–]luxgladius0 0 0 points1 point2 points 2 years ago (0 children)
Nicely done.
[–]econobeing0 0 1 point2 points3 points 2 years ago* (2 children)
I just did it quick and easy, I'm sure it could be done much more elegantly...
Java:
public static void lockerProblem() { boolean lockers [] = new boolean[1001]; for(int i = 0 ; i < 1001 ; i++) lockers[i] = false; for(int i = 1 ; i < 1001 ; i++) for(int j = i ; j < 1001; j+=i) lockers[j] = !lockers[j]; int openlockers = 0; for(int i = 1 ; i < 1001 ; i++) if(lockers[i]) { openlockers++; System.out.print(i + ", " + (openlockers % 5 == 0 ? "\n" : "")); } System.out.println("\ntotal open = " + openlockers); }
output:1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, total open = 31
[–]nubyw00tz 1 point2 points3 points 2 years ago* (0 children)
I know it's a bit late, but I don't think the first for loop is needed. The default boolean value is false, so creating an array of booleans will automatically all have them false.
[–]wastingmine 0 points1 point2 points 2 years ago (0 children)
i'm thinking... for the second for loop, you can have an int that keeps track of open lockers by saying if lockers[j]==true, count++, else count--. not sure how to efficiently keep track of all of them though.
[–]prophile 1 point2 points3 points 2 years ago (1 child)
Python:
N = 1000 import math opens = [n*n for n in xrange(int(math.sqrt(N)) + 1) if n*n < N] print len(opens), opens
[–]namekuseijin 0 points1 point2 points 2 years ago (0 children)
that's not python, that's pure math from someone with a clue. :)
[–]Err_Eek 1 point2 points3 points 2 years ago (2 children)
I'm open to suggestions on how to shrink this code
a = [] size = 1000 for i in range(size) : a.append(False) for j in range(size) : for i in range(len(a)) : if (i+1)%(j+1) == 0 : a[i] = False if (a[i] == True) else True j = 0 for i in range(len(a)): if (a[i] == True) : print 'locker ', i+1 , ' is open' j += 1 print 'total no of open lockers ', j, 'out of a total of ', len(a)
I get the same results as luxgladius
[–]Ttl 5 points6 points7 points 2 years ago (1 child)
Smaller python version:
a = [False]*1000 for i in xrange(1,1000): for j in xrange(0,1000,i): a[j]=not a[j] [i for i,j in enumerate(a) if j][1:]
[–]Err_Eek 2 points3 points4 points 2 years ago (0 children)
Thanks a lot. I learned 3 or 4 new things in python starting from those 5 lines
[–]iluminumx 1 point2 points3 points 2 years ago (6 children)
C++:
#include "iostream" using namespace std; void toggleAtStep(bool *lockers, int step){ for(int x = step ; x < 1000 ; x += step){ lockers[x-1]= (lockers[x-1] == true) ? false : true; } } int main(){ bool *lockers = new bool[1000]; for(int x = 0 ; x < 1000 ; x++){ lockers[x] = false; } for(int x = 1 ; x <= 1000 ; x++){ toggleAtStep(lockers, x); } for(int x = 1; x <= 1000 ; x++){ if(lockers[x-1] == true){ cout << x << ";"; } } return 0; }
output: 1;4;9;16;25;36;49;64;81;100;121;144;169;196;225;256;289;324;361;400;441;484;529;576;625;676;729;784;841;900;961;
[–]bob1000bob 2 points3 points4 points 2 years ago* (4 children)
I don't know if you are interested, but some style tips that may help you in future are:
using std::cout
[–]juju2112 0 points1 point2 points 2 years ago (2 children)
Can you explain the size_t thing? I don't get it.
Regarding the namespace thing, is that because it consumes more RAM or what?
[–]bob1000bob 1 point2 points3 points 2 years ago (1 child)
A size_t is a typedef (alias) for an unsigned integer type that is guaranteed to be able to describe the size of any object (including arrays) that can be contained in memory. This is important because a 64bit system address a whole lot more than a 32bit system yet a plain int is 32bit on both. Where as a size_t is 32bit on a 32bit system, and 64bit on a 64bit system.
size_t
typedef
int
The namespace is considered good practice, it is very important in large program where namespace collision might happen, for example two functions may share the same name, by using the prefixed version there is no ambiguity. I will admit as adds a lot of mass to the code which would otherwise be avoided but you get used to it and it aids readability once you get used to it.
[–]juju2112 0 points1 point2 points 2 years ago (0 children)
Interesting. I hadn't considered that. Thanks!
[–]bob1000bob 0 points1 point2 points 2 years ago* (0 children)
C++ code
#include <iostream> #include <vector> int main(){ std::vector<bool> lockers(1000, false); for(unsigned i=1; i!=1001; ++i){ for(unsigned j=i; j<1001; j+=i){ lockers.at(j-1)=!lockers.at(j-1); } } std::size_t count=0; for(std::size_t i=0; i!=lockers.size(); ++i){ if(!lockers[i]) continue; std::cout << i+1 << ", "; ++count; } std::cout << "\ncount: " << count << std::endl; }
compile
g++ -std=c++0x -O2 lockers.cpp
stdio
1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, count: 31
[–]Iracus 0 points1 point2 points 2 years ago (0 children)
Python
lockerList = [0]*1000 openList = [] students = 1000 for s in range(students): for x in range(len(lockerList)): if (x+1) % (s+1) == 0: if lockerList[x] == 0: lockerList[x] = 1 else: lockerList[x] = 0 for x in range(len(lockerList)): if lockerList[x] == 1: openList.append(x+1) openLockers = lockerList.count(1) print "Lockers open:", openLockers print "Open locker numbers:", openList
[–]mazzer 0 points1 point2 points 2 years ago (0 children)
Groovy:
def lockers = [] (1..1000).each { stepSize -> (stepSize..1000).step(stepSize, { i -> lockers[i] = !lockers[i]}) } def openLockers = lockers.findIndexValues { it } println "${openLockers.size()}\n$openLockers"
[–]notcleverenough 0 points1 point2 points 2 years ago (0 children)
PHP
foreach(range(1,1000) as $i) $lockers[$i] = false; foreach(range(1,1000) as $i) { for($u = $i; $u < 1000; $u += $i) $lockers[$u] = !$lockers[$u]; } foreach($lockers as $i=>$l) { if($l) $open[] = $i; }
[–]Zamarok 0 points1 point2 points 2 years ago* (0 children)
What a great problem, and a surprising solution. Here's how I did it in Haskell:
lockers = map (flip (,) False) [1..1000] toggles = map (`mapEvery` toggle) [1..1000] where toggle (x, b) = (x, not b) mapEvery n f = mapEvery' n where mapEvery' _ [] = [] mapEvery' 1 (x:xs) = f x : mapEvery' n xs mapEvery' n' (x:xs) = x : mapEvery' (n'-1) xs solution = filter isOpen (applyAll toggles lockers) where isOpen = (True ==) . snd applyAll = foldr (.) id main = print $ map fst solution
[–][deleted] 0 points1 point2 points 2 years ago (4 children)
Here's my complete program in C++. Answer is same as luxgladius.
I'm a beginner, so there are bound to be bad programming practices in the code. It would be great if seasoned programmers could point them out so I don't make same mistakes next time. :)
#include <iostream> using namespace std; int main() { int locker_state[1000]; int std_num = 1; //student's ID int arr_index; //index of array for (int i = 0; i < 1000; i++) locker_state[i] = 0; while (std_num <= 1000) { arr_index = std_num-1; while (arr_index < 1000) { if (locker_state[arr_index] == 1) locker_state[arr_index] = 0; else locker_state[arr_index] = 1; arr_index = arr_index + std_num; } std_num++; } int count = 0; for (int i = 0; i < 1000; i++) { if (locker_state[i] == 1) { cout << "Locker #" << i+1 << " is open.\n"; count++; } } cout << "Total number of lockers open: " << count << endl; system("pause"); return 0; }
[–]juju2112 0 points1 point2 points 2 years ago (3 children)
What's system("pause")? Is that a Windows thing? That might not work on Unix. It's best to try to keep it portable. You could achieve the same thing with getch().
[–][deleted] 0 points1 point2 points 2 years ago (0 children)
I was taught in my CS101 class to use system("pause") to stop the program from terminating. This is so that I could see my program's output.
Just searched StackOverflow. Apparently, system("pause") and getch() are both platform-dependent. A better thing to do would be to just use cin.get() and ask user if they want to end the program.
[–][deleted] 0 points1 point2 points 2 years ago (1 child)
It's often used in basic command line programs to stop the program so you can see the output printed to the console, that way if the program is opened without the console open, it stays open before it ends.
I used it when I started in C++ as well, but it's not a great habit to get into.
Oh yes, I forgot about the disappearing windows console. That makes sense. I'm too used to unix!
[–]phmongeau 0 points1 point2 points 2 years ago (0 children)
Another Python solution:
lockers = [False for i in range(1000)] for student in range(1,1001): lockers = [l if i % student else not l for i,l in enumerate(lockers)] print(sum([1 if i else 0 for i in lockers])) print(', '.join([str(i) for i,l in enumerate(lockers) if l]))
[–]jarjarbinks770 0 0 points1 point2 points 2 years ago* (0 children)
My C++ attempt using vector pairs.Compiled on Win7 x64 with MSVC++ 2010.
http://pastebin.com/rmhEGSsG
Here the simplified version with no arrays, vectors, or pairs.
http://pastebin.com/RwVxi5jU
Just a little shorter version.
http://pastebin.com/y1J45pDs
I think there still some stuff you could do to cut down onprocessing time but its instant already on my computer.
brute-force, but elegant scheme:
http://pastebin.com/WhpJd6iY
I've heard of it before, many years ago. I don't think I ever coded it though.
a surprising answer indeed...
[–]naxir 0 points1 point2 points 2 years ago (0 children)
Another C++ (using a plain ol' array)
#include <iostream> int main() { const unsigned short int SIZE = 1000; unsigned short int Total = 0; bool Lockers[SIZE] = { 0 }; for (int i = 1;i < SIZE;i++) for (int j = i;j < SIZE;j += i) Lockers[j] ^= 1; for (int i = 0;i < SIZE;i++) if (Lockers[i]) { std::cout << i << ';'; Total++; } std::cout << " Total: " << Total << std::endl; return 0; }
edit:
output: $ ./36easy 1;4;9;16;25;36;49;64;81;100;121;144;169;196;225;256;289;324;361;400;441;484;529;576;625;676;729;784;841;900;961; Total: 31
[–]1nvader 0 points1 point2 points 2 years ago (0 children)
Same result in Python here:
a = [False]*1000 for x in range(1,1000): for y in range(0,1000,x): a[y] = not a[y] for r in range(1,1000): if a[r] == True: print(r)
31 lockers are open.
[–]cooper6581 0 points1 point2 points 2 years ago (0 children)
Python (similar to other solutions already posted):
CLOSED = 0 OPEN = 1 lockers = [CLOSED for x in xrange(1000)] for s in xrange(1000): for t in xrange(0,1000,s+1): lockers[t] ^= 1 r = [x for x,l in enumerate(lockers) if l] print 'Lockers %s, total: %d' % (r, len(r))
[cooper@fred 36]$ python easy.py Lockers [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961], total: 31
[–]Reykd 0 points1 point2 points 2 years ago* (2 children)
New to c++ here is my very long attempt:
#include <iostream> using namespace std; bool lockers[1000] = {false};// false = closed void tLockers (int x); void toggle (int x); int printOpen (); int main(int argc, char** argv) { for (int x = 1; x <= 1000; x++) tLockers(x); cout << "\nTotal number of open lockers is: " <<printOpen(); return 0; } void tLockers (int x) //Here student x toggles lockers y. { int y = x-1; while (y < 1000) { toggle(y); y +=x; } } void toggle (int x) //Open closed lockers and close opened ones { if (lockers[x] == false){ lockers[x] = true;} else lockers [x] = false; } int printOpen () //Go through all the lockers and print the open ones { int y = 0; for (int x = 0; x < 1000; x++) { if (lockers[x]) { y++; cout << x+1<<" "; } } return y; }
1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 784 841 900 961 Total number of open lockers is: 31
PD: im certain that there is an easier way to hide all the code than to put four spaces before every single line of code... would anyone be so kind as to inform me of how?
[–]namekuseijin 0 points1 point2 points 2 years ago (1 child)
much to learn, grasshopper. for instance, toggle is merely lockers[x]=!lockers[x].
[–]Reykd 0 points1 point2 points 2 years ago (0 children)
much to learn indeed, good thing to know =]
[–]bigronaldo 0 points1 point2 points 2 years ago (0 children)
C#
public static void Daily36() { bool[] lockers = new bool[1000]; List<int> openLockers = new List<int>(); for (int i = 1; i <= 1000; i++) { for(int x = 1; x <= 1000; x++) { if ((i % x) == 0) { lockers[i-1] = !lockers[i-1]; } } } for (int i = 1; i <= 1000; i++) { if (lockers[i - 1]) { openLockers.Add(i); } } Console.WriteLine(string.Join(",", openLockers)); }
[–]devilsassassin 0 points1 point2 points 2 years ago (0 children)
public static boolean [] Lockers(){ boolean [] lockers = new boolean[1000]; for(int i=0;i<lockers.length;i++){ lockers[i]=false; } for(int i=1;i<=lockers.length;i++){ for(int j=0;j<lockers.length;j++){ int exp =i*j; if(exp<lockers.length){ lockers[exp] =!lockers[exp]; } else{ j=lockers.length; } } } for(int i=0;i<lockers.length;i++){ if(lockers[i]){ System.out.println(i); } } return lockers; }
[–]Should_I_say_this 0 points1 point2 points 2 years ago (0 children)
def factors(a): number=0 for i in range(1,a+1): if a%i==0: number+=1 return number def numberopen(): count=0 lockopen=[] for i in range(1,1001): if factors(i)%2!=0: count+=1 lockopen.append(i) print(count,'lockers open') return lockopen
output:31 lockers open[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961]
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 19382 on app-11 at 2014-09-19 22:22:05.012867+00:00 running d16e201 country code: US.
|
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
|
Suppose I have a file name num.txt as below:
1 2 3 4 56 7 8 9 0
I want to read 3 integers from this file, that is 1 2 3.
I know that struct.unpack might do the trick, but I just cannot get it right.Here is how I did it:
fp = open('num.txt', 'rb')
print struct.unpack('iii', fp.read(12)) #right?
Anyone can help me with this?
PS
This is how I got file num.txt:
fp = open('num.txt', 'wb')
fp.write('1 2 3 4 5\n6 7 8 9 0')
fp.close()
|
Possible Duplicate:
How to clone a Python generator object?
Suppose I have a generator 'stuff_to_try', I can try them one by one but if I had a method that wanted to go through the generator and that method is recursive, I want to let each recursion get a fresh new generator that starts at the first yield rather than where the last recursion left off.
def solve(something):
if exit_condition(something):
return
next_to_try = stuff_to_try.next()
while not if_works(next_to_try):
next_to_try = stuff_to_try.next()
solve(do_something(something))
Of course I can define stuff_to_try inside the recursive function but is there a better way? Is there an equivalent of stuff_to_try.clone().reset() or something?
|
How to convert the following hex string to float (single precision 32-bit) in Python?
"41973333" -> 1.88999996185302734375E1"41995C29" -> 1.91700000762939453125E1"470FC614" -> 3.6806078125E4
>>> import struct
>>> struct.unpack('!f', '41973333'.decode('hex'))[0]
18.899999618530273
>>> struct.unpack('!f', '41995C29'.decode('hex'))[0]
19.170000076293945
>>> struct.unpack('!f', '470FC614'.decode('hex'))[0]
36806.078125
Update: see comment on how to do this in Python 3.
I recommend using the ctypes module which basically lets you work with low level data types. In your case you could say
from ctypes import *
def convert(s):
i = int(s, 16) # convert from hex to a Python int
cp = pointer(c_int(i)) # make this into a c integer
fp = cast(cp, POINTER(c_float)) # cast the int pointer to a float pointer
return fp.contents.value # dereference the pointer, get the float
print convert("41973333") # returns 1.88999996185302734375E1
print convert("41995C29") # returns 1.91700000762939453125E1
print convert("470FC614") # returns 3.6806078125E4
I believe that the
In C if you had an int and wanted to interpret its bits as a float, you'd do roughly the same thing, taking a pointer and then casting and dereferencing it:
int i = 0x41973333;
float f = *((float*)&i);
and that's exactly what the Python code using the
I'm guessing this question relates to this one and you are working with 4 bytes rather than 8 hex digits.
>>> len("\x41\x91\x33\x33")
4
>>> import struct
>>> struct.unpack(">fff","\x41\x97\x33\x33\x41\x99\x5C\x29\x47\x0F\xC6\x14")
(18.899999618530273, 19.170000076293945, 36806.078125)
If you do need to deal with the string of hexdigits rather than the actual bytes, you can use
>>> for hx in ["41973333","41995C29","470FC614"]:
... print(struct.unpack(">f",struct.pack(">i",int(hx,16)))[0])
...
18.8999996185
19.1700000763
36806.078125
Slice up the hex strings into 2-character chunks (bytes), make each chunk into the right byte with int formatting, struct.unpack when done. I.e.:
import struct
testcases = {
"41973333": 1.88999996185302734375E1,
"41995C29": 1.91700000762939453125E1,
"470FC614": 3.6806078125E4,
}
def hex2float(s):
bins = ''.join(chr(int(s[x:x+2], 16)) for x in range(0, len(s), 2))
return struct.unpack('>f', bins)[0]
for s in testcases:
print hex2float(s), testcases[s]
emitting, as desired:
Gentelmen... Behold:
class fl:
def __init__(this, value=0, byte_size=4):
this.value = value
if this.value: # speedy check (before performing any calculations)
Fe=((byte_size*8)-1)//(byte_size+1)+(byte_size>2)*byte_size//2+(byte_size==3)
Fm,Fb,Fie=(((byte_size*8)-(1+Fe)), ~(~0<<Fe-1), (1<<Fe)-1)
FS,FE,FM=((this.value>>((byte_size*8)-1))&1,(this.value>>Fm)&Fie,this.value&~(~0 << Fm))
if FE == Fie: this.value=(float('NaN') if FM!=0 else (float('+inf') if FS else float('-inf')))
else: this.value=((pow(-1,FS)*(2**(FE-Fb-Fm)*((1<<Fm)+FM))) if FE else pow(-1,FS)*(2**(1-Fb-Fm)*FM))
del Fe; del Fm; del Fb; del Fie; del FS; del FE; del FM
else: this.value = 0.0
print fl( 0x41973333 ).value # >>> 18.899999618530273
print fl( 0x41995C29 ).value # >>> 19.170000076293945
print fl( 0x470FC614 ).value # >>> 36806.078125
print fl( 0x00800000 ).value # >>> 1.1754943508222875e-38 (minimum float value)
print fl( 0x7F7FFFFF ).value # >>> 340282346638528859811704183484516925440L (maximum float value)
# looks like I've found a small bug o.o
# the code still works though (the numbers are properly formatted)
# the result SHOULD be: 3.4028234663852886e+38 (rounded)
print fl( 0x3f80000000, 5 ).value # >>> 1.0
sorry for the little ".value" at the end...
credit to PyTony over at DaniWeb for the code.
unlike non-dynamic computing,
though I guess we still have a few bugs to work out. XDD
all is good though for now though...
|
Can anyone tell me the actual reason behind the warning I am getting in this Django middleware, and how can I solve this?
I am getting this message "DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 exception. class, exception.message,"
class GeneralMiddleware(object):
def process_exception(self, request, exception):
if exception.__class__ is SandboxError:
# someone is trying to access a sandbox that he has no
# permission to
return HttpResponseRedirect("/notpermitted/")
exc_type, value, tb = sys.exc_info()
data = traceback.format_tb(
tb, None) + traceback.format_exception_only(
exc_type, value)
msg = (
"Failure when calling method:\n"
u"URL:'%s'\nMethod:'%s'\nException Type:'%s'\n"
u"Error Message '%s'\nFull Message:\n%s"
% (request.get_full_path(), request.method,
exception.__class__, exception.message,
|
I am trying to post to Facebook Group Wall via Graph API. When i make the post, owner of the post is set as my personal id. Would someone know how to make Group has the owner of the post. Below is my current code:
form_fields = {
"message": 'This is message title',
"link": 'http://facebook.com',
"name": 'This is message title',
"access_token": 'token here'
}
form_fields['description'] = 'This is message body'
form_data = urllib.urlencode(form_fields)
response = urlfetch.fetch( url="https://graph.facebook.com/%s/feed" % group_id,
payload=form_data,
method=urlfetch.POST,
deadline=10
)
|
scipy provides a correlation function which will work fine for small input and also if you want non-circular correlation meaning that the signal will not wrap around. note that in mode='full' , the size of the array returned by signal.correlation is the sum of the input signal sizes - 1, so the value from argmax is off by (signal size -1 = 20) from what you seem to expect.
from scipy import signal, fftpack
import numpy
a = numpy.array([0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0, 0, 0, 0, 0])
b = numpy.array([0, 0, 0, 0, 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0])
numpy.argmax(signal.correlate(a,b)) -> 16
numpy.argmax(signal.correlate(b,a)) -> 24
The two different values correspond to whether the shift is in a or b.
If you want circular correlation and for big signal size, you can use the convolution/Fourier transform theorem with the caveat that correlation is very similar to but not identical to convolution.
A = fftpack.fft(a)
B = fftpack.fft(b)
Ar = -A.conjugate()
Br = -B.conjugate()
numpy.argmax(numpy.abs(fftpack.ifft(Ar*B))) -> 4
numpy.argmax(numpy.abs(fftpack.ifft(A*Br))) -> 17
again the two values correspond to whether your interpreting a shift in a or a shift in b.
The negative conjugation is due to convolution flipping one of the functions, but in correlation there is no flipping. You can undo the flipping by either reversing one of the signals and then taking the FFT, or taking the FFT of the signal and then taking the negative conjugate. i.e. the following is true: Ar = -A.conjugate() = fft(a[::-1])
|
"Mistakes are not errors but partially correct solutions with underlying logic." - Alina Tugend
An exercise's submission correctness test (SCT) is code that course creators write to check the correctness of a learner's code submission and guide them to the right solution.
When a learner runs their solution to an exercise, your SCT has access to the variables, functions, and objects within that code at runtime. Course creators can then use these constructs to determine whether or not a learner's submission should pass or fail.
Submission tests run in the same environment as a learner's submitted code.This means that when you write a function in the Submission Correctness Testeditor box in the Course Creation Tool, you are automatically inside asubmission test function and have access to the scope of that function.
Failing or passing a submission is determined by the return value from yourtest function.ReturnBoolean trueto pass a learner's submission,and return afalsevalue to fail a learner's submission.
For example, if you want the learner's submission to always pass, return true.
return true;
If you return false, students will see the error message "Oops, try again." To provide a more helpful error message, return a string that will be displayed as an error.
return "Make sure that you have closed all your parentheses.";
The submission correctness test provides you with access to information regarding the code the learner has written and the status of the environment in which it was run. This information can be accessed and manipulated as follows:
The variablecodecontains the string of the entire contents of the code that the learner entered. For example, if you're expecting the submitted code to have at least one plus (+) sign, you could write the correctness test:
return code.indexOf('+') > -1;
The variableresultcontains the result of evaluating the students' code. It can be of any data type. If you're anticipating the result of a learner's entry to be a number, you could use the test:
return typeof result === "number";
If you're expecting the number two you could simply use:
return result === 2;
This test would work fine if the learner enters the expected code e.g.1 + 2.But what if the learner enters a single number. The submission test would pass it even though it's wrong.We could further strengthen the test by adding the plus check:
return typeof result === "number" && code.indexOf('+') > -1;
That's better and it works. However its not 100% right. You could always write RegExp but then it may not catch all cases. The correct way to do it is to use a proper code analysis tool. Helpers for this type of check will be available in our library soon!
The error object contains the error thrown by a learner's code. If there is no error, it is the null object. This is useful when anticipating learner mistakes.
For example, if you wanted to test whether or not the learner's code threw a reference error, you could use:
if (error instanceof ReferenceError) {
return "Make sure you put quotes around your name."
}
You can also use regular expressions to check for specific strings in learner code. This is fairly rigid as a test, difficult to get just right, and is difficult to read. We don't recommend it, but it is useful in some cases.
For example, it is currently the only way to check if tags are closed in HTML.
if (code.html.match(/\<\/a\>/)===null) {
return 'Did you remember to close the "a" tags?';
}
return true;
In an effort to provide as rich an experience as possible to course creators, we have in addition to providing course creators with access to the aforementioned variables provided a suite of functions to make it easier to access various aspects of the runtime environment.
Say you ask the user to define a function called foo and to call said function. You could write a submission test like this:
return typeof foo === "function" && code.match(/foo\s*\(/) != null;
Although this is a relativaly strong check, it could go wrong in many ways and is unneccessarily complex. To simplify such a check, use the CC.calls() function to test if a function has been defined and invoked within the user's code submission.
return typeof foo === "function" && CC.calls('foo').length > 0;
CCis our helper library's namespace (short for CodeCademy). We maintain the same API for all languages supported by our system unless mentioned otherwise.
CC.calls
A function that takes a function name and returns an array of the arguments that were passed to the function every time it was called in the code.
Student code:
foo(1, 2);
foo('x', 'y');
Then by calling:
CC.calls('foo');
In our submission test would return an array looking like
CC.methods
A function that takes a method name and an object and returns an array of arguments that were passed to the method called on that object.
Student code:
var cow = {};
cow.says = function(sound) { console.log(sound); }
cow.says("Moo");
Then by calling:
CC.methods("says", "cow");
In the SCT, we'd get an array looking like
CC.equals
Takes any number of objects and checks the deep equality of these objects. This is equivalent to calling JSON.stringify on each item and comparing the resulting strings.
CC.equals([1,2], [1,2]); //true
CC.prints
Returns an array of strings printed to the console.
Student Code:
console.log('fooooo');
console.log('baaaar');
CC.prints(); // ['fooooo', 'baaaar']
CC.printed
Given a string, returns a boolean representing whether or not the string was printed to the console.
Student code:
console.log('fooooo');
CC.printed('fooooo'); //true
CC.printed('baaaar'); //false
It should be noted that conditional tests can always be combined via the&&and||operators.
For example, if you wanted to test that the user entered a number or a string, you could use:
return typeof result === "number" || typeof result === "string";
You can provide students with custom error messages from within the submission test by returning a string.
Lets go back to the addition example and further enhance it by giving the user hints about what they did wrong.
if (typeof result !== "number")
return "You should probably use numbers";
if (code.indexOf('+') === -1)
return "Maybe you should use the plus sign for addition"
return true
You can also try to guess what the learner did wrong from the type of error thrown from evaluating her code.
For example if your trying to get her to type in her name and got a reference error then chances are she left out the quotes:
if (error && error instanceof ReferenceError) {
return "Make sure you surround your name with quotes!"
}
if (typeof result === "string") {
return true;
}
return false;
Preview Mode adds an in-browser deubgging console that will show helpful log and error messages. Preview Mode console will show the following:
Errors in the SCT.
In web courses, errors from the learner code.
When SCT is waiting on an async event and when its resolved.
Thoroughly test your submission test functions before publishing your course.
Submission tests run in the same environment as a learner's submitted code. This means that when a student runs his or her code in an exercise, your SCT has access to all variables, functions, and objects within that code at runtime.
You can simply write SCTs to assume that those constructs exist. If the learner failedto use the necessary construct, however, your SCT will have to handle thegenerated exception appropriately (seeHelpful Error Messages). Failure to handle the exception will result in the generic message:Oops, try again.
Failing or passing a learner's submission is determined by thereturnvalue from your SCT. Returntrueto pass a learner's submission, and return afalsevalue to fail a learner's submission.
For example, if you want the learner's submission to always pass, then your SCT can contain the following:
return true
If you simply return false, then students will see the error message:"Oops, try again."To provide a more helpful error message, you can return a string that will be displayed as theerror message. This can be achieved with the following:
return "Make sure to use the .each method in your code."
Of course, these types of SCTs are not very helpful, since they don't really check that the user's code works.You should avoid writing SCTs that only contain the above snippets.In the next section, we'll cover how to access constructs within a learner's submitted code.
The SCT provides you with access to information regarding the learner's code and the status of the environment in which it was run. This information can be accessed and manipulated by utilizing the following:
Thecodevariable contains a string representation of the learner's submission. You can perform checksagainst this variable to determine if the user's code contained the necessary operators.
For example, if the learner were to run the code:
my_sum = 2 + 2
Then the variablecodewould contain the string"mysum = 2 + 2"
If you wanted to make sure that the addition operator+was used, you could simply check that the code contains more than 0 instances of the addition operator,This can be achieved with the following:
return code.include? "+"
Remember,codeis just a string variable, so you can use Ruby's built-in string methods to determine if the student's code solves the exercise.The above code uses Ruby's#include?method to determine how many times the string"+"occurs in the student's code.
You might think to use thecodevariable for checking if a necessary variable was declared in the learner's code, but it might be more appropriate toassume that the variable exists and try calling it. If the learner didn't define the required variable, then your SCTwill trigger aNameErrorexception.
See the sectionHelpful Error Messagesfor a discussion of handling exceptions with Ruby'sbegin/rescue/endconstructs.
The variableresultcontains the result of evaluating the students' code. If you'd like to make sure that the resultof a learner's submission is an integer, you could use the following in your SCT:
return result.is_a? Integer
If you're expecting the evaluation of the student's code to be a specific value, you could then use the following:
return result == 4
Again, this holds for any data type, not just integers.
The problem is that if you only check that the answer is correct, you allow the learner to just simply enterthe answer and hit "run." Unfortunately, your SCT will pass them. Instead, if you want ensure that an operation be used toyield the answer, you can use thecodevariable in conjunction with theresultvariable. This can be seen from the following:
return code.include? "+" && result == 4
The above SCT ensures that the student's code produces the answer 4 and includes an addition operation. However, this is still not perfect. This SCT will pass the user given the following incorrect code:
fooled_you = 100 + 50
4
This passes because it satisfies the fact that the result was the number 4 (from the second statement) and that the code contained at least one use of the addition operator. The correct way to do it is to use a proper code analysis tool. Helpers for this type of check will be available soon!
Theexceptionobject contains the exception thrown by a student's code. If there is no exception, its value isnil. This is useful when anticipating student mistakes.
For example, the following student code generates a SyntaxError exception:
my_name = "Eric Weinstein
In your SCT, you can handle syntax errors with the following:
if error.kind_of? SyntaxError
return "Make sure to use double quotes around your name."
This shows the following output to the learner:
Oops, try again.
Make sure to use double quotes around your name.
This is discussed further in the section Helpful Error Messages .
We've provided you with a suite of functions to make it easier tocheck various aspects of a learner's submission. These functions are contained withincodecademy_lib, also known as theCClibrary.
For Ruby, this library is still under development. We'll incorporate additional helper methods soon!
prints
Returns an array of strings that were printed to the console after running the learner's code.You do not need to prefix
Student Code:
SCT:
printed
A separate
Given a string,
Student code:
SCT:
prints.include? 'fooooo' # true
prints.include? 'baaaar' # false
Note that this
It should be noted that conditional tests can always be combined via the&&and||operators.
For example, if you wanted to test that the user entered an integer or a string, you could use:
return result.is_a? Integer || result.is_a? String
It's important to understand that SCTs are meant not only to check the correctness of a student's code, but to help guide him or her to the right answer(s). Many students get discouraged when the console prints unhelpful or confusing error messages. Hence, it's your job to avoid those obstacles and provide encouraging and useful messages for likely errors.
You can provide students with custom error messages from within the submission test by returning a string.
In the simple case, if the learner's solution doesn't contain required constructs, you can return a string that explains why their solution is incorrect.
For example, let's go back to the addition example and further enhance it by giving the learner hints about what they did wrong.
unless result.is_a? Integer
return "Check to make sure your code results in an integer."
unless code.include? "+"
return "It doesn't look like you're using the addition operator."
return true
Rather than usingif !truein Ruby, it's often cleaner to useunless true. However, this construct should be avoided if the statement includes anelse. In that case,if / elseis the better construction.
It's important to note that errors can appear both in the user's codeandthe SCT.
Errors in the student's code can typically be found in theexceptionvariable, as discussed in theAccessing Student Codesection. You can check for these errors using a simple conditional check and return a messagethat helps the student understand how they generated an error.
Errors in your SCT can result from two situations: a syntax error in your code or an exception generated when trying to use constructs defined in the user's code.
For the first type of SCT error, where your code is flawed, those errors are reported to youvia thepreview mode consolediscussed in theDebugging and Preview Modesection. These errors should be straightforward for you to remedy.
The second type of SCT error, where your SCT uses non-existent constructs in the student's code,generates exceptions that you need to handle using Ruby'sbegin/rescue/endsyntax.
For example, if your exercise asked the user to type in his or her name and the submission generated a syntax error, it's very likely that the student missed a starting or closing quote:
if exception.kind_of? SyntaxError
return "Make sure you surround your name with quotes!"
unless result.is_a? String
return "Make sure your code produces a string value."
return true
Raised when a variable is used in a context but not declared. This exception can be triggered form both the user's code and the SCT.
puts first_name # first_name not declared
The SCT to catch this:
if exception.kind_of? NameError
return "It looks like you tried to use a variable without declaring it first."
If the exercise called for a variablefirst_nameto be defined and the student's code was:
"Oxnard Montalvo"
The following SCT will attempt to use the expected variablefirst_nameonly to see that it doesn't exist, triggering aNameErrorexceptionwithin the SCT.
first_name == 'Ryan' # NameError
The SCT to catch this exception involves wrapping the SCT code in abegin/rescue/endblock:
begin
first_name # NameError
rescue NameError:
return "Did you remember to declare a variable called first_name?"
end
# If they don't trigger an exception, let's pass them.
return true
The learner will then see the following output:
Oops, try again.
Did you remember to declare a variable called first_name?
Raised when the student generates any kind of syntax error. This exception should be caughtusing theexceptionvariable, and error messages should be context-dependent. For instance, if the student is learning how to useif/elsestatements and his or her code raises a syntax error, your SCT might be:
if exception.kind_of? SyntaxError
return "It looks like your if/else syntax isn't quite right."
Raised when the denominator of a division or modulo operation is zero. This exception should becaught using theexceptionvariable.
Student Code:
100 / 0
SCT to catch this:
if exception.kind_of? ZeroDivisionError
return "Dividing by zero isn't allowed!"
Preview Mode adds an in-browser debugging console that will show helpful log and error messages. This mode is activated when you hit Save and then Preview when editing an exercise. You'll then notice a console window at the bottom of the page.
The Preview Mode console will show you the following:
Errors in your SCT generated from syntax and other creator-caused errors.
When the SCT is waiting on an asynchronous event and when it's resolved.
When a student attempts to solve an exercise that has a flawed SCT, the student shouldn't be blocked from progressing through the course. To this end, we've instated logic such that broken SCTs will automatically pass the student.
Please thoroughly test all submission correction tests before publishing your course!
Submission tests run in the same environment as a learner's submitted code. This means that when a learner runs their code in an exercise, your SCT has access to the variables, functions, and objects within that code at runtime.
You can simply write SCTs to assume that those constructs exist. If the learner failedto use the necessary construct, however, your SCT will have to handle thegenerated exception appropriately (seeHelpful Error Messages). Failure to handle the exception will result in the generic message:Oops, try again.
Failing or passing a learner's submission is determined by the return value from your SCT.ReturnTrueto pass a learner's submission,and return aFalsevalue to fail a learner's submission.
For example, if you want the learner's submission to always pass, then your SCT can contain the following:
return True
If you simply return false, then students will see the error message:"Oops, try again."To provide a more helpful error message, you can return a string that will be displayed as theerror message. This can be achieved with the following:
return "Please check that you have closed all of your parentheses."
Of course, these types of SCTs are not very helpful, since they don't really check that the user's code works.You should avoid writing SCTs that only contain the above snippets.In the next section, we'll cover how to access constructs within a learner's submitted code.
The submission correctness test provides you with access to information regarding the learner's code and the status of the environment in which it was run. This information can be accessed and manipulated by utilizing the following in your SCTs:
Thecodevariable contains a string representation of the learner's submission. You can perform checks against this variable to determineif the user's code contained the necessary operators.
For example, if the learner ran the code:
my_sum = 2 + 2
Then the variablecodewould contain the string"mysum = 2 + 2"
If you wanted to make sure that the addition operator+was used, they could simply check that the code contains more than 0 instances of the addition operator.i.e., The code should contain at least one instance of the addition operator.This can be achieved with the following:
return code.count("+") > 0
Remember,codeis just a string variable, so you can use Python's built-in string methods to determine if the learner's code solves the exercise.The above code uses Python'scount()function to determine how many times the string"+"occurs in the learner's code.
You might think to use thecodevariable for checking if a necessary variable was declared in the learner's code, but it might be more appropriate toassume that the variable exists and try calling it. If the learner didn't define the required variable, then your SCTwill trigger aNameErrorexception.
See the sectionHelpful Error Messagesfor a discussion of handling exceptions with Python'stry/exceptconstructs.
The variableresultcontains the result of evaluating the students' code. It can be of any data type. If you'd like to make sure that the resultof a learner's submission is an integer, you could use the following in your SCT:
return type(result) == int
If you're expecting the evaluation of the learner's code to be a specific value, you could then use the following:
return result == 2
Again, this holds for any data type, not just integers.
The problem is that if you only check that the answer is correct, you allow the learner to just simply enterthe answer and hit run. Unfortunately, your SCT will pass them. Instead, if you want ensure that an operation be used toyield the answer, you can use thecodevariable in conjunction with theresultvariable. This can be seen from the following:
return result == 2 and code.count('+') > 0
The above SCT ensures that the learner's code produces the answer 2 and has an addition operation. However, this is still not perfect. This SCT will pass the user given the following incorrect code:
fooled_you = 100 + 50
2
This passes because it satisfies the fact that the result was the number 2 (from the second statement) and that the code contained at least one use of the addition operator. The correct way to do it is to use a proper code analysis tool. Helpers for this type of check will be available soon!
Theerrorobject contains the exception thrown by a learner's code. If there is no error, its value isNone. This is useful when anticipating learner mistakes.
For example, the following learner's code generates a SyntaxError exception:
name = "Joel Kemp
In your SCT, you can handle syntax errors with the following:
if type(error) == SyntaxError:
return "Make sure that you have double quotes around your name."
This shows the following output to the learner:
Oops, try again.
Make sure that you have double quotes around your name.
This is discussed further in the section Helpful Error Messages .
We've provided you with a suite of functions to make it easier tocheck various aspects of a learner's submission. These functions are contained withincodecademy_lib, also known as theCClibrary.
For Python, this library is still in development and we will incorporate additional helper methods soon.
prints
Returns an array of strings that were printed to the console after running the learner's code.
Student Code:
print 'fooooo'
print 'baaaar'
SCT:
CC.prints() # ['fooooo', 'baaaar']
printed
Given a string, the
Student code:
print 'fooooo'
SCT:
CC.printed('fooooo') # True
CC.printed('baaaar') # False
It should be noted that conditional tests can always be combined via theandandoroperators.
For example, if you wanted to test that the user entered an integer or a string, you could use:
return type(result) == int or type(result) == str
It's important to understand that SCTs are meant to guide students to the right answers, in addition to checking the correctness of their code. Many students get discouraged when the console prints uninformative errors. Hence, it's your job to avoid those obstacles and provide encouraging messages for likely errors.
You can provide students with custom error messages from within the submission test by returning a string.
In the simple case, if the learner's solution doesn't contain required constructs, you can return a string that explains why their solution is incorrect.
For example, let's go back to the addition example and further enhance it by giving the learner hints about what they did wrong.
if type(result) != int:
return "Check to make sure that you're using numbers."
if code.count('+') == 0:
return "It doesn't seem like you're using the addition operator."
return True
It's important to note that errors can be generated from both the user's code and the SCT.
Errors in the learner's code can typically be found in theerrorvariable, as discussed in theAccessing Student Codesection. You can check for these errors using a simple conditional check and return a messagethat helps the learner understand how they generated an error.
Errors in your SCT can result from two situations: a syntax error in your code or an exception generated when trying to use constructs defined in the learner's code.
For the first type of SCT error, where your code is flawed, those errors are reported to youvia thepreview mode consolediscussed in theDebugging and Preview Modesection. These errors should be straightforward for you to remedy.
The second type of SCT error, where your SCT uses non-existent constructs in the learner's code,generates exceptions that you need to handle using Python'stry/exceptsyntax.
For example, if your exercise asked the learner to type in their name and their submission generated a syntax error, then it's very likely that the learner missed a starting or closing quote:
if error and type(error) == SyntaxError:
return "Make sure you surround your name with quotes!"
if type(result) == str:
return True
return False
Raised when a variable or function is used in a context but not declared/defined. This exception can be triggered form both the learner's code and the SCT.
name = first_name #first_name not declared
The SCT to catch this:
if type(error) == NameError:
return "You tried using a variable that doesn't exist."
If the exercise called for a variablefirst_nameto be defined and the learner's code was:
"Bob"
The following SCT will attempt to use the expected variablefirst_nameonly to see that it doesn't exist -- triggering aNameErrorexceptionwithin the SCT.
print "Welcome", first_name # NameError
The SCT to catch this exception involves wrapping the SCT code in atry/exceptblock:
try:
print "Welcome", first_name # NameError
except NameError:
return "Make sure that you've defined the variable first_name."
# If they don't trigger an exception, then let's pass them.
return True
The learner will then see the following output:
Oops, try again.
Make sure that you've defined the variable first_name.
Raised when the denominator of a division or modulo operation is zero. This exception should becaught using theerrorvariable.
Student Code:
2 / 0
SCT to catch this:
if type(error) == ZeroDivisionError:
return "Dividing by zero is not allowed."
Preview Mode adds an in-browser debugging console that will show helpful log and error messages. This mode is activated when you hit Save and then Preview when editing an exercise. You'll then notice a console window at the bottom of the page.
The Preview Mode console will show you the following:
Errors in your SCT generated from syntax and other creator-caused errors.
When the SCT is waiting on an async event and when its resolved.
When a learner attempts to solve an exercise that has a flawed SCT, the learner shouldn't be blocked from progressing through the course. To this end, we've enstated that broken SCTs will automatically pass the learner.
Please thoroughly test your submission correction tests before publishing your course.
Submission tests run in the same environment as a learner's submitted code.This means that when you write a function in the Submission Correctness Testeditor box in the Course Creation Tool, you are automatically inside asubmission test function and have access to the scope of that function.
Failing or passing a submission is determined by the return value from yourtest function.ReturnBoolean trueto pass a learner's submission,and return afalsevalue to fail a learner's submission.
For example, if you want the learner's submission to always pass, return true.
return true;
If you return false, students will see the error message "Oops, try again." To provide a more helpful error message, return a string that will be displayed as an error.
return "Make sure that you have closed all your parentheses.";
The submission correctness test provides you with access to information regarding the code the learner has written and the status of the environment in which it was run. This information can be accessed and manipulated as follows:
The variablecodecontains the string of the entire contents of the code that the learner entered. For example, if you're expecting the submitted code to have at least one plus (+) sign, you could write the correctness test:
return code['script.js'].indexOf('+') > -1;
Notice that unlike when accessing code in a JavaScript lesson we have to tell the code descriptor which file we want it to look in. Here We noted that we wanted to look in the file ['script.js'].
You can also use regular expressions to check for specific strings in learner code. This is fairly rigid as a test, difficult to get just right, and is difficult to read. We don't recommend it, but it is useful in some cases.
For example, it is currently the only way to check if tags are closed in HTML.
if (code['script.js'].match(/\<\/a\>/)===null) {
return 'Did you remember to close the "a" tags?';
}
return true;
In an effort to provide as rich an experience as possible to course creators, we have provided a suite of functions to make it easier to access various aspects of the runtime environment.
Say you ask the user to define a function called foo and to call said function. You could write a submission test like this:
return typeof foo === "function" && code.match(/foo\s*\(/) != null;
Although this is a relativaly strong check, it could go wrong in many ways and is unneccessarily complex. To simplify such a check, use the CC.calls() function to test if a function has been defined and invoked within the user's code submission.
return typeof foo === "function" && CC.calls('foo').length > 0;
CCis our helper library's namespace (short for CodeCademy). We maintain the same API for all languages supported by our system unless mentioned otherwise.
CC.calls
A function that takes a function name and returns an array of the arguments that were passed to the function every time it was called in the code.
Student code:
foo(1, 2);
foo('x', 'y');
Then by calling:
CC.calls('foo');
In our submission test would return an array looking like
CC.equals
Takes any number of objects and checks the deep equality of these objects. This is equivalent to calling JSON.stringify on each item and comparing the resulting strings.
CC.equals([1,2], [1,2]); //true
CC.prints
Returns an array of strings printed to the console.
Student Code:
console.log('fooooo');
console.log('baaaar');
CC.prints(); // ['fooooo', 'baaaar']
CC.printed
Given a string, returns a boolean representing whether or not the string was printed to the console.
Student code:
console.log('fooooo');
CC.printed('fooooo'); //true
CC.printed('baaaar'); //false
It should be noted that conditional tests can always be combined via the&&and||operators.
For example, if you wanted to test that the user entered a number or a string, you could use:
return typeof result === "number" || typeof result === "string";
You can provide students with custom error messages from within the submission test by returning a string.
Lets go back to the addition example and further enhance it by giving the user hints about what they did wrong.
if (typeof result !== "number")
return "You should probably use numbers";
if (code.indexOf('+') === -1)
return "Maybe you should use the plus sign for addition"
return true
You can also try to guess what the learner did wrong from the type of error thrown from evaluating her code.
For example if your trying to get her to type in her name and got a reference error then chances are she left out the quotes. You have 2 common options if you have to check a variable value, and so cannot use the $expect.js library to check a DOM element. You can use a try catch statement in anticipation of an error:
try
{
if (typeof sampleVariable === "string") {
return true;
}
catch(err)
{
return "sampleVariable did not exist! Make sure it is being initialized.";
}
This method is more robust and allows you to check any operation you perform. However, if all you are checking is an if statement, then you can use this method as well:
if(typeof sampleVariable == "undefined" || sampleVariable != 4)
return "You did not correctly set sampleVariable to 4. Please make sure your code correctly gives it a value";
This works because if the first check in the if statement finds that sampleVariable is indeed undefined, it will skip the second check and jump directly into the if clause. This behaviour within JavaScript allows us to avoid the second check for a nonexistant variable. Back to top
Preview Mode adds an in-browser debugging console that will show helpful log and error messages. Preview Mode console will show the following:
Errors in the SCT.
Errors from the learner code.
When SCT is waiting on an async event and when its resolved.
Thoroughly test your submission test functions before publishing your course.
|
Thank you, I have added the Bytemark addresses to debug_peer_list in main.cf and the following two are examples of the more verbose logs resulting:
Nov 24 10:29:19 mail2 postfix/smtpd[32718]: 05E9498061: client=nospam2.sh.bytemark.co.uk[89.16.184.149]
Nov 24 10:29:19 mail2 postfix/smtpd[32718]: improper command pipelining after DATA from nospam2.sh.bytemark.co.uk[89.16.184.149]:
Nov 24 10:29:19 mail2 postfix/smtpd[32718]: 05E9498061: reject: DATA from nospam2.sh.bytemark.co.uk[89.16.184.149]: 503 5.5.0 <DATA>: Data command rejected: Improper use of SMTP command pipelining; from=<blackballmedialz.F.7805.2.0@blackballmedia.gtml2.com> to=<snh@tridentgarages.co.uk> proto=ESMTP helo=<nospam2.sh.bytemark.co.uk>
Nov 24 10:29:19 mail2 postfix/smtpd[32718]: lost connection after DATA from nospam2.sh.bytemark.co.uk[89.16.184.149]
Nov 24 10:29:19 mail2 postfix/smtpd[32718]: disconnect from nospam2.sh.bytemark.co.uk[89.16.184.149]
Nov 24 10:29:36 mail2 postfix/smtpd[32718]: connect from nospam2.sh.bytemark.co.uk[89.16.184.149]
Nov 24 10:29:36 mail2 postfix/smtpd[32718]: 94AEF98061: client=nospam2.sh.bytemark.co.uk[89.16.184.149]
Nov 24 10:29:37 mail2 postfix/smtpd[32718]: disconnect from nospam2.sh.bytemark.co.uk[89.16.184.149]
Nov 24 10:29:40 mail2 postfix/smtpd[32718]: connect from nospam3.sh.bytemark.co.uk[89.16.184.150]
Nov 24 10:29:40 mail2 postfix/smtpd[32718]: 37AD398286: client=nospam3.sh.bytemark.co.uk[89.16.184.150]
Nov 24 10:41:34 mail2 postfix/smtpd[516]: 5867698061: client=nospam1.sh.bytemark.co.uk[89.16.184.148]
Nov 24 10:41:34 mail2 postfix/smtpd[516]: improper command pipelining after DATA from nospam1.sh.bytemark.co.uk[89.16.184.148]:
Nov 24 10:41:34 mail2 postfix/smtpd[516]: 5867698061: reject: DATA from nospam1.sh.bytemark.co.uk[89.16.184.148]: 503 5.5.0 <DATA>: Data command rejected: Improper use of SMTP command pipelining; from=<shredonsitelz.F.20956.36.0@shredonsite.gtml2.com> to=<webmaster@tridentgarages.co.uk> proto=ESMTP helo=<nospam1.sh.bytemark.co.uk>
Nov 24 10:41:34 mail2 postfix/smtpd[516]: lost connection after DATA from nospam1.sh.bytemark.co.uk[89.16.184.148]
Nov 24 10:41:34 mail2 postfix/smtpd[516]: disconnect from nospam1.sh.bytemark.co.uk[89.16.184.148]
Nov 24 10:42:39 mail2 postfix/smtpd[516]: connect from nospam2.sh.bytemark.co.uk[89.16.184.149]
Nov 24 10:42:39 mail2 postfix/smtpd[516]: 1772198061: client=nospam2.sh.bytemark.co.uk[89.16.184.149]
Nov 24 10:42:40 mail2 postfix/smtpd[516]: disconnect from nospam2.sh.bytemark.co.uk[89.16.184.149]
Nov 24 10:42:41 mail2 postfix/smtpd[516]: connect from 121.8.187.81.in-addr.arpa[81.187.8.121]
Nov 24 10:42:41 mail2 postfix/smtpd[516]: disconnect from 121.8.187.81.in-addr.arpa[81.187.8.121]
Bytemark are saying that they are seeing a timeout, but our mailserver is never under any significant load (it barely exceeds zero load average). This is an example of what they're seeing in the logs:
2013-11-25 05:46:50 1VjThK-0003f7-F9 == snh@tridentgarages.co.uk
R=hubbed_hosts_abmx T=remote_smtp defer (110): Connection timed out:
SMTP timeout while connected to 212.110.190.52 [212.110.190.52] after
MAIL FROM:<principalitlz.F.35437.125.0@principal.sgml1.co.uk> SIZE=21166
Once again, any suggestions gratefully received!
--
Chris
|
I'm still pretty new to using python to program from scratch so as an exercise I though I'd take a file that I process using SQL an try to duplicate the functionality using Python. It seems that I want to take my (compressed, zip) csv file and create a Dict of it (or maybe a dict of dicts?). When I use dict reader I get the 1st row as a key rather than each column as its own key? E.g.
import csv, sys, zipfile
sys.argv[0] = "/home/tom/Documents/REdata/AllListing1RES.zip"
zip_file = zipfile.ZipFile(sys.argv[0])
items_file = zip_file.open('AllListing1RES.txt', 'rU')
for row in csv.DictReader(items_file,dialect='excel'):
pass
Yields:
>>> for key in row:
print 'key=%s, value=%s' % (key, row[key])
key=MLS_ACCT PARCEL_ID AREA COUNTY STREET_NUM STREET_NAME CITY ZIP STATUS PROP_TYPE LIST_PRICE LIST_DATE DOM DATE_MODIFIED BATHS_HALF BATHS_FULL BEDROOMS ACREAGE YEAR_BUILT YEAR_BUILT_DESC OWNER_NAME SOLD_DATE WITHDRAWN_DATE STATUS_DATE SUBDIVISION PENDING_DATE SOLD_PRICE,
value=492859 28-15-3-009-001.0000 200 JEFF 3828 ORLEANS RD MOUNTAIN BROOK 35243 A SFR 324900 3/3/2011 2 3/4/2011 12:04:11 AM 0 2 3 0 1968 EXIST SPARKS 3/3/2011 11:54:56 PM KNOLLWOOD
So what I'm looking for is a column for MLS_ACCT and a separate one for PARCEL_ID etc so I can then do things like average prices by all items that contain KNOLLWOOD in the SUBDIVISION field With a further sub section by date range, date sold etc.
I know well how to do it with SQL but As I said I'm tying to gain some Python skills here. I have been reading for the last few days but have yet to find any very simple illustrations on this sort of use case. Pointers to said docs would be appreciated. I realize I could use memory resident SQL-lite but again my desire is to get the Python approach learned.I've read some on Numpy and Scipy and have sage loaded but still can't find some useful illustrations since those tools seem focussed on arrays with only numbers as elements and I have a lot of string matching I need to do as well as date range calculations and comparisons.
Eventually I'll need to substitute values in the table (since I have dirty data), I do this now by having a "translate table" which contains all dirty variants and provides a "clean" answer for final use.
|
Say I have a class in SQLAlchemy like
class Note(Base):
__tablename__ = 'notes'
slug = Column('short_title', String, primary_key=True)
date = Column('day', Date, primary_key=True)
contents = Column(Text, nullable=True)
Given only a reference to the Note class, how could a function build the list ['Note.slug', 'Note.date'] predicated on their constituting the corresponding table's primary key?
Furthermore, is there a way to filter class attributes based on column properties? (such as nullable, type, uniqueness, membership in an index, etc)
|
This is very similar to the common programming question: "How many ways can you combine Y types of coins with Z values to make X dollars", i.e. make change for X dollars with Y coin types.
Here's a general solution that could be ported to C++:
I = list of items SORTED from highest to lowest price
N = number of items bought so far
M = money left
S = money to start
function shop(I, N, M, S):
if M < 0: return 0 //we bought something illegally!
if M == 0:
//If we have no money, we've bought all we could.
//Check our condition that num items N = starting money S
return 1 if N == S, else 0
if I is empty:
return 0 //no more item combos, no way to buy things.
else:
newI = I with first element removed
//Every time we want to buy stuff, we have two options:
//1. buy something of highest value and subtract money
//2. Shop ignoring the next highest value item
return shop(newI, N, M, S) + shop(I, N+1, M-(cost of first item), S)
With X dollars, you start off with the call:
shop(I, 0, X, X)
|
I would like to know if it's possible to clear CloudFront's cache,
The file concerned has changed on Amazon S3 but it's not being updated on CloudFront.
I would like to know if it's possible to clear CloudFront's cache,
The file concerned has changed on Amazon S3 but it's not being updated on CloudFront.
I found the answer using Python:
import boto
cf = boto.connect_cloudfront('aws_access_key_id', 'aws_secret_access_key')
cf.create_invalidation_request("distribution_id", ["/path1","/path2"])
Documentation:
Might be useful to know you can also do this right from the AWS Console.
Distribution Settings > Invalidations > Create Invalidation
Then just type in the paths to invalidate in the same format displayed there.
|
In the fewest bytes, generate the dictionary of keypresses for any letter (as described in https://code.google.com/codejam/contest/351101/dashboard#s=p2)
In Python, the dictionary literal itself:
{'a':2,'c':222,'b':22,'e':33,'d':3,'g':4,'f':333,'i':444,'h':44,'k':55,'j':5,'m':6,'l':555,'o':666,'n':66,'q':77,'p':7,'s':7777,'r':777,'u':88,'t':8,'w':9,'v':888,'y':999,'x':99,'z':9999}
is 187 bytes so it needs to be less than that. (The values can be strings or ints, ie you can have 'a':'2' or 'a':2 it's up to you)
NOTE: This is not asking you to solve the referenced GCJ problem, it's just asking you to generate a particular dictionary which is related to that problem.
EDIT: You may solve this in any language which has a dictionary-like type (ie hashmap, associative array etc.)
|
The Flask Mega-Tutorial, Part IX: Pagination
The goal of the tutorial series is to develop a decently featured microblogging application that demonstrating total lack of originality I have decided to call microblog.
Here is an index of all the articles in the series that have been published to date:
Part I: Hello, World!
Part II: Templates
Part III: Web Forms
Part IV: Database
Part V: User Logins
Part VI: Profile Page And Avatars
Part VII: Unit Testing
Part VIII: Followers, Contacts And Friends
Part IX: Pagination (this article)
Part X: Full Text Search
Part XI: Email Support
Part XII: Facelift
Part XIII: Dates and Times
Part XIV: I18n and L10n
Part XV: Ajax
Part XVI: Debugging, Testing and Profiling
Part XVII: Deployment on Linux (even on the Raspberry Pi!)
Part XVIII: Deployment on the Heroku Cloud
Recap
In the previous article in the series we've made all the database changes necessary to support the 'follower' paradigm, where users choose other users to follow.
Today we will build on what we did last time and enable our application to accept and deliver real content to its users. We are saying goodbye to the last of our fake objects today!
Submission of blog posts
Let's start with something simple. The home page should have a form for users to submit new posts.
First we define a single field form object (file app/forms.py):
class PostForm(Form):
post = TextField('post', validators = [Required()])
Next, we add the form to the template (file app/templates/index.html):
<!-- extend base layout -->
{% extends "base.html" %}
{% block content %}
<h1>Hi, {{g.user.nickname}}!</h1>
<form action="" method="post" name="post">
{{form.hidden_tag()}}
<table>
<tr>
<td>Say something:</td>
<td>{{ form.post(size = 30, maxlength = 140) }}</td>
<td>
{% for error in form.errors.post %}
<span style="color: red;">[{{error}}]</span><br>
{% endfor %}
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Post!"></td>
<td></td>
</tr>
</table>
</form>
{% for post in posts %}
<p>
{{post.author.nickname}} says: <b>{{post.body}}</b>
</p>
{% endfor %}
{% endblock %}
Nothing earth shattering so far, as you can see. We are simply adding yet another form, like the ones we've done before.
Last of all, the view function that ties everything together is expanded to handle the form (file app/views.py):
from forms import LoginForm, EditForm, PostForm
from models import User, ROLE_USER, ROLE_ADMIN, Post
@app.route('/', methods = ['GET', 'POST'])
@app.route('/index', methods = ['GET', 'POST'])
@login_required
def index():
form = PostForm()
if form.validate_on_submit():
post = Post(body = form.post.data, timestamp = datetime.utcnow(), author = g.user)
db.session.add(post)
db.session.commit()
flash('Your post is now live!')
return redirect(url_for('index'))
posts = [
{
'author': { 'nickname': 'John' },
'body': 'Beautiful day in Portland!'
},
{
'author': { 'nickname': 'Susan' },
'body': 'The Avengers movie was so cool!'
}
]
return render_template('index.html',
title = 'Home',
form = form,
posts = posts)
Let's review the changes in this function one by one:
We are now importing the PostandPostFormclasses
We accept POST requests in both routes associated with the indexview function, since that is how we will receive submitted posts.
When we arrive at this view function through a form submission we insert a new Postrecord into the database. When we arrive at it via a regular GET request we do as before.
The template now receives an additional argument, the form, so that it can render the text field.
One final comment before we continue. Notice how after we insert a new Post into the detabase we do this:
return redirect(url_for('index'))
We could have easily skipped the redirect and allowed the function to continue down into the template rendering part, and it would have been more efficient. Because really, all the redirect does is return to this same view function to do that, after an extra trip to the client web browser.
So, why the redirect? Consider what happens after the user writes a blog post, submits it and then hits the browser's refresh key. What will the refresh command do? Browsers resend the last issued request as a result of a refresh command.
Without the redirect, the last request is the POST request that submitted the form, so a refresh action will resubmit the form, causing a second Post record that is identical to the first to be written to the database. Not good.
By having the redirect, we force the browser to issue another request after the form submission, the one that grabs the redirected page. This is a simple GET request, so a refresh action will now repeat the GET request instead of submitting the form again.
This simple trick avoids inserting duplicate posts when a user inadvertently refreshes the page after submitting a blog post.
Displaying blog posts
And now we get to the fun part. We are going to grab blog posts from the database and display them.
If you recall from a few articles ago, we created a couple of fake posts and we've been displaying those in our home page for a long time. The fake objects were created explicitly in the index view function as a simply Python list:
posts = [
{
'author': { 'nickname': 'John' },
'body': 'Beautiful day in Portland!'
},
{
'author': { 'nickname': 'Susan' },
'body': 'The Avengers movie was so cool!'
}
]
But in the last article we created the query that allows us to get all the posts from followed users, so now we can simply replace the above with this (file app/views.py):
posts = g.user.followed_posts().all()
And when you run the application you will be seeing blog posts from the database!
The followed_posts method of the User class returns a sqlalchemy query object that is configured to grab the posts we are interested in. Calling all() on this query just retrieves all the posts into a list, so we end up with a structure that is very much alike the fake one we've been using until now. It's so close that the template does not even notice.
At this point feel free to play with the application. You can create a few users, make them follow others, and finally post some messages to see how each user sees its blog post stream.
Pagination
The application is looking better than ever, but we have a problem. We are showing all of the followed posts in the home page. What happens if a user has a thousand followed posts? Or a million? As you can imagine, grabbing and handling such a large list of objects will be extremely inefficient.
Instead, we are going to show this potentially large number of posts in groups, or pages.
Flask-SQLAlchemy comes with very good support for pagination. If for example, we wanted to get the first three followed posts of some user we can do this:
posts = g.user.followed_posts().paginate(1, 3, False).items
The paginate method can be called on any query object. It takes three arguments:
the page number, starting from 1,
the number of items per page,
an error flag. If True, when an out of range page is requested a 404 error will be automatically returned to the client web browser. If False, an empty list will be returned instead of an error.
The return value from paginate is a Pagination object. The items member of this object contains the list of items in the requested page. There are other useful things in the Pagination object that we will see a bit later.
Now let's think about how we can implement pagination in our index view function. We can start by adding a configuration item to our application that determines how many items per page we will display (file config.py):
# pagination
POSTS_PER_PAGE = 3
It is a good idea to have these global knobs that can change the behavior of our application in the configuration file all together, because then we can go to a single place to revise them all.
In the final application we will of course use a much larger number than 3, but for testing it is useful to work with small numbers.
Next, let's decide how the URLs that request different pages will look. We've seen before that Flask routes can take arguments, so we can add a suffix to the URL that indicates the desired page:
http://localhost:5000/ <-- page #1 (default)
http://localhost:5000/index <-- page #1 (default)
http://localhost:5000/index/1 <-- page #1
http://localhost:5000/index/2 <-- page #2
This format of URLs can be easily implemented with an additional route added to our view function (file app/views.py):
from config import POSTS_PER_PAGE
@app.route('/', methods = ['GET', 'POST'])
@app.route('/index', methods = ['GET', 'POST'])
@app.route('/index/<int:page>', methods = ['GET', 'POST'])
@login_required
def index(page = 1):
form = PostForm()
if form.validate_on_submit():
post = Post(body = form.post.data, timestamp = datetime.utcnow(), author = g.user)
db.session.add(post)
db.session.commit()
flash('Your post is now live!')
return redirect(url_for('index'))
posts = g.user.followed_posts().paginate(page, POSTS_PER_PAGE, False).items
return render_template('index.html',
title = 'Home',
form = form,
posts = posts)
Our new route takes the page argument, and declares it as an integer. We also need to add the page argument to the index function, and we have to give it a default value because two of the three routes do not have this argument, so for those the default will always be used.
And now that we have a page number available to us we can easily hook it up to our followed_posts query, along with the POSTS_PER_PAGE configuration constant we defined earlier.
Note how easy these changes are, and how little code is affected each time we make a change. We are trying to write each part of the application without making any assumptions regarding how the other parts work, and this enables us to write modular and robust applications that are easier to test and are less likely to fail or have bugs.
At this point you can try the pagination by entering URLs for the different pages by hand into your browser's address bar. Make sure you have more than three posts available so that you can see more than one page.
Page navigation
We now need to add links that allow users to navigate to the next and/or previous pages, and luckily this is extremely easy to do, Flask-SQLAlchemy does most of the work for us.
We are going to start by making a small change in the view function. In our current version we use the paginate method as follows:
posts = g.user.followed_posts().paginate(page, POSTS_PER_PAGE, False).items
By doing this we are only keeping the items member of the Pagination object returned by paginate. But this object has a number of other very useful things in it, so we will instead keep the whole object (file app/views.py):
posts = g.user.followed_posts().paginate(page, POSTS_PER_PAGE, False)
To compensate for this change, we have to modify the template (file app/templates/index.html):
<!-- posts is a Paginate object -->
{% for post in posts.items %}
<p>
{{post.author.nickname}} says: <b>{{post.body}}</b>
</p>
{% endfor %}
What this change does is make the full Paginate object available to our template. The members of this object that we will use are:
has_next: True if there is at least one more page after the current one
has_prev: True if there is at least one more page before the current one
next_num: page number for the next page
prev_num: page number for the previous page
With these for elements we can produce the following (file app/templates/index.html):
<!-- posts is a Paginate object -->
{% for post in posts.items %}
<p>
{{post.author.nickname}} says: <b>{{post.body}}</b>
</p>
{% endfor %}
{% if posts.has_prev %}<a href="{{ url_for('index', page = posts.prev_num) }}"><< Newer posts</a>{% else %}<< Newer posts{% endif %} |
{% if posts.has_next %}<a href="{{ url_for('index', page = posts.next_num) }}">Older posts >></a>{% else %}Older posts >>{% endif %}
So we have two links. First we have one labeled "Newer posts" that sends us to the previous page (keep in mind we show posts sorted by newest first, so the first page is the one with the newest stuff). Conversely, the "Older posts" points to the next page.
When we are looking at the first page we do not want to show a link to go to the previous page, since there isn't one. This is easy to detect because posts.has_prev will be False. We handle that case simply by showing the same text of the link but without the link itself. The link to the next page is handled in the same way.
Implementing the Post sub-template
Back in the article where we added avatar pictures we defined a sub-template with the HTML rendering of a single post. The reason we created this sub-template was so that we can render posts with a consistent look in multiple pages, without having to duplicate the HTML code.
It is now time to implement this sub-template in our index page. And, as most of the things we are doing today, it is surprisingly simple (file app/templates/index.html):
<!-- posts is a Paginate object -->
{% for post in posts.items %}
{% include 'post.html' %}
{% endfor %}
Amazing, huh? We just discarded our old rendering code and replaced it with an include of the sub-template. Just with this, we get the nicer version of the post that includes the user's avatar.
Here is a screenshot of the index page of our application in its current state:
The user profile page
We are done with the index page for now. However, we have also included posts in the user profile page, not posts from everyone but just from the owner of the profile. To be consistent the user profile page should be changed to match the index page.
The changes are similar to those we made on the index page. Here is a summary of what we need to do:
add an additional route that takes the page number
add a pageargument to the view function, with a default of 1
replace the list of fake posts with the proper database query and pagination
update the template to use the pagination object
Here is the updated view function (file app/views.py):
@app.route('/user/<nickname>')
@app.route('/user/<nickname>/<int:page>')
@login_required
def user(nickname, page = 1):
user = User.query.filter_by(nickname = nickname).first()
if user == None:
flash('User ' + nickname + ' not found.')
return redirect(url_for('index'))
posts = user.posts.paginate(page, POSTS_PER_PAGE, False)
return render_template('user.html',
user = user,
posts = posts)
Note that this function already had an argument (the nickname of the user), so we add the page number as a second argument.
The changes to the template are also pretty simple (file app/templates/user.html):
<!-- posts is a Paginate object -->
{% for post in posts.items %}
{% include 'post.html' %}
{% endfor %}
{% if posts.has_prev %}<a href="{{ url_for('user', nickname = user.nickname, page = posts.prev_num) }}"><< Newer posts</a>{% else %}<< Newer posts{% endif %} |
{% if posts.has_next %}<a href="{{ url_for('user', nickname = user.nickname, page = posts.next_num) }}">Older posts >></a>{% else %}Older posts >>{% endif %}
Final words
Below I'm making available the updated version of the microblog application with all the pagination changes introduced in this article.
Download microblog-0.9.zip.
As always, a database isn't provided so you have to create your own. If you are following this series of articles you know how to do it. If not, then go back to the database article to find out.
As always, I thank you for following my tutorial. I hope to see you again in the next one!
Miguel
|
I've looked through several posts but I haven't quite found any answers that have solved my problem.
Sample XML =
<TextWithNodes><Node id="0"/>TEXT1<Node id="19"/>TEXT2 <Node id="20"/>TEXT3<Node id="212"/></TextWithNodes>
So I understand that usually if I had extracted TextWithNodes as a NodeList I would do something like
nodeList = TextWithNodes[0].getElementsByTagName('Node')
for a in nodeList:
node = a.nodeValue
print node
All I get is None. I've read that you must write a.childNodes.nodeValue but there isn't a child node to the node list since it looks like all the Node Ids are closing tags? If I use a.childNodes I get [].
When I get the node type for a it is type 1 and TEXT_NODE = 3. I'm not sure if that is helpful.
I would like to extract TEXT1, TEXT2, etc.
|
Since there is no pre-built Ubuntu package for uWSGI and the Nginx package is quite outdated, you have to build both from source. uWSGI requires at least a 0.7.x release of Nginx. First of all download and unpack the latest source of uWSGI and the source of Nginx to /usr/local/src/.
I created an isolated Python environment in /opt/example.com with virtualenv. The root of my Django project throughout this example is /opt/example.com/project/.
Getting started with uWSGI
The first step is to compile uWSGI (make) and copy the resulting binary to /usr/sbin/. Now what's left is to setup uWSGI to run your Django application.
You have two choices to configure uWSGI, via an XML file or using Python. I prefer the Python way, but if you would rather use XML you are free to do so.
# wsgi_app.py import sys import os sys.path.append(os.path.abspath(os.path.dirname(__file__))) os.environ['DJANGO_SETTINGS_MODULE'] = 'example.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler()
Normally, I put this file in the root of my Django project so that it is under version control.
Running uWSGI
uWSGI brings its own process manager but the preferred way to run your apps with uWSGI would be to use a process manager like Upstart or daemontools. See "Running Processes" by Dustin Sallings for more alternatives.
This is a simple example script for use with Upstart:
# file: /etc/event.d/uwsgi_example description "uWSGI server for example.com" start on runlevel [2345] stop on runlevel [!2345] respawn exec /usr/sbin/uwsgi \ --home /opt/example.com/ \ --socket /var/run/example.com.sock \ --chmod-socket \ --module wsgi_app \ --pythonpath /opt/example.com/project
The last line is necessary to locate the "wsgi_app" module if it doesn't live on your Python path. Save this to the directory for your Upstart scripts (on Ubuntu 8.04 this is /etc/event.d, on more recent versions /etc/init). The name of this script is now used to start your uWSGI server:
$ start uwsgi_example
Compiling and Installing Nginx
Nginx doesn't support dynamic loading of modules like Apache does, so you have to select those at compile time. I also made some choices regarding file locations but only the last line is required to make it play with uWSGI.
/usr/local/src/nginx:$ ./configure --conf-path=/etc/nginx/nginx.conf \ > --error-log-path=/var/log/nginx/error.log \ > --pid-path=/var/run/nginx.pid \ > --lock-path=/var/lock/nginx.lock \ > --http-log-path=/var/log/nginx/access.log \ > --http-client-body-temp-path=/var/lib/nginx/body \ > --http-proxy-temp-path=/var/lib/nginx/proxy \ > --http-fastcgi-temp-path=/var/lib/nginx/fastcgi \ > --with-http_stub_status_module \ > --with-http_flv_module \ > --with-http_ssl_module \ > --sbin-path=/usr/sbin \ > --add-module=../uwsgi/nginx/
Now we are ready to compile and install:
/usr/local/src/nginx:$ make && checkinstall
I also had to create some directories by hand:
$ mkdir /var/run/nginx \ /var/log/nginx \ /var/lib/nginx \ /var/lib/nginx/body \ /var/lib/nginx/proxy \ /var/lib/nginx/fastcgi
The location part for your Django application in your nginx.conf should look something like:
location / { uwsgi_pass unix:///var/run/example.com.sock; include uwsgi_params; }
The uwsgi_params file came with the source of uWSGI and should be in /usr/local/src/uwsgi/nginx. It must be copied over to /etc/nginx or wherever your Nginx configuration lives.
Closing Words
In my opinion uWSGI offers a simple and uncomplicated way to run your WSGI application. It seems very fast and stable while keeping memory consumption very low.
If you have any questions, feel free to comment.
|
Cooking with Python
07/11/2002
by Robin Parma, Alex Martelli, Scott David Daniels, Ben Wolfson, Nick Perkins, Anurag Uniya, Tim Keating, Rael Dornfest and Jeremy Hylton, authors of the Python Cookbook
1. Simple Tests Using Exceptions
Usually Python is straightforward, but there are a few unexpected exceptions.
Credits: Robin Parma
Problem
You want to know if the contents of a string represent an integer, which is not quite the same thing as checking whether the string contains only digits.
Solution
# try/except is generally the best approach to such problems:
def IsInt(str):
"""Is the given string an integer?"""
try:int(str)
except ValueError:return 0
else:return 1
Discussion
Use exceptions to perform simple tests that are otherwise laborious. If you want to know if the contents of a string represent an integer, just try to convert it. That's what IsInt() does. The try/except mechanism catches the exception raised when the string cannot be converted to an int, turning it into a harmless return 0. The else clause, which runs only when no exception is raised in the try clause, gives a return 1 when the string is OK.
Don't be misled by the word "exception," or by what is considered good style in different programming languages. Relying on exceptions and try/except is a useful Pythonic idiom.
2. Constants in Python
Liberal Python lets you rebind any variable; yet, there is an instance where you can protect your variables.
Credits: Alex Martelli
Problem
You need to define module-level variables that client-code cannot accidentally rebind, such as "named constants."
Solution
# Needs Python 2.1 or better. Put in const.py...:
class _Constants:
class ConstError(TypeError): pass
def __setattr__(self, name, value):
if self.__dict__.has_key(name):
raise self.ConstError, "Can't rebind const(%s)"%name
self.__dict__[name ] = value
def __delattr__(self, name):
if self.__dict__.has_key(name):
raise self.ConstError, "Can't unbind const(%s)"%name
raise NameError, name
import sys
sys.modules[__name__] = _Constants()
# now any client-code can:
import const
# and bind an attribute ONCE:
const.magic =23
# but NOT re-bind it:
# const.magic =88 # would raise const.ConstError
Discussion
In Python, any variable can be re-bound at will. Modules don't let you define special methods, such as an instance's __setattr__, to stop attribute re-binding. An easy solution (in Python 2.1 and up) is to use an instance as "module."
Python 2.1 and up no longer forces entries in sys.modules to be module objects. You can install an instance object there and take advantage of its attribute-access special methods while still having client-code get at it with import somename. You might see this as a more Pythonic "Singleton"-ish idiom (but also see "Singleton? We don't need no stinkin' Singleton: the Borg non-pattern"). Note that this recipe ensures a constant binding for a given name, not an object's immutability, which is quite a different issue.
|
I'm in the process of publishing a small sample which illustrates precisely what you're asking about: how to use App Engine service account credentials to access Google Cloud Storage (specifically, to list a formatted Google Cloud Storage bucket). When available, this will be part of the https://code.google.com/p/google-api-python-client/ repo but, in the meantime, here's the code:
import httplib2
import logging
import os
import pickle
import re
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from oauth2client.appengine import AppAssertionCredentials
# Constants for the XSL stylesheet and the Google Cloud Storage URI.
XSL = '\n<?xml-stylesheet href="/listing.xsl" type="text/xsl"?>\n';
URI = 'http://commondatastorage.googleapis.com'
# Obtain service account credentials and authorize HTTP connection.
credentials = AppAssertionCredentials(
scope='https://www.googleapis.com/auth/devstorage.read_write')
http = credentials.authorize(httplib2.Http(memcache))
class MainHandler(webapp.RequestHandler):
def get(self):
try:
# Derive desired bucket name from path after domain name.
bucket = self.request.path
if bucket[-1] == '/':
# Trim final slash, if necessary.
bucket = bucket[:-1]
# Send HTTP request to Google Cloud Storage to obtain bucket listing.
resp, content = http.request(URI + bucket, "GET")
if resp.status != 200:
# If error getting bucket listing, raise exception.
err = 'Error: ' + str(resp.status) + ', bucket: ' + bucket + \
', response: ' + str(content)
raise Exception(err)
# Edit returned bucket listing XML to insert style sheet for nice
# formatting and send results to client.
content = re.sub('(<ListBucketResult)', XSL + '\\1', content)
self.response.headers['Content-Type'] = 'text/xml'
self.response.out.write(content)
except Exception as e:
self.response.set_status(404)
self.response.out.write(str(e))
def main():
application = webapp.WSGIApplication(
[
('.*', MainHandler),
],
debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()
This code depends on an XSLT style sheet. You can comment out references to XSL to eliminate that dependency or include the following file in your project (with name listing.xsl):
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ama="http://doc.s3.amazonaws.com/2006-03-01">
<xsl:template match="/">
<html>
<body>
<h2><a href="http://developer.google.com/storage">Google Cloud Storage</a> Con
tent Listing for Bucket
<xsl:value-of select="ama:ListBucketResult/ama:Name"/></h2>
<table border="1" cellpadding="5">
<tr bgcolor="#9acd32">
<th>Object Name</th>
<th>Modification Time</th>
<th>ETag</th>
<th>Size</th>
<th>Storage Class</th>
</tr>
<xsl:for-each select="ama:ListBucketResult/ama:Contents">
<tr>
<td><xsl:value-of select="ama:Key"/></td>
<td><xsl:value-of select="ama:LastModified"/></td>
<td><xsl:value-of select="ama:ETag"/></td>
<td><xsl:value-of select="ama:Size"/></td>
<td><xsl:value-of select="ama:StorageClass"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
|
#0 Re : -1 » splitter un fichier selon un pattern Regex » Hier à 18:22
pingouinux
Réponses : 3
Bonjour,
Voici une proposition en python.
cat decoupage.py
#! /usr/bin/python
import sys, re
rec=re.compile('(.*?\n\n){2}',re.S)
with open(sys.argv[1],'r') as f :
fic=f.read()
n=0
while True :
k=rec.search(fic)
if(k) :
n+=1
with open('fichier%d.txt'%n,'w') as g :
g.write(fic[:k.start(0)])
g.write(k.group(0))
fic=fic[k.end(0):]
else :
if fic :
n+=1
with open('fichier%d.txt'%n,'w') as g :
g.write(fic)
break
À appeler ainsi
./decoupage.py fichier_original
#1 Re : -1 » splitter un fichier selon un pattern Regex » Hier à 21:51
pingouinux
Réponses : 3
J'ai un peu simplifié, et ajouté des commentaires.
#! /usr/bin/python
# -*- coding: utf-8 -*-
import sys, re
# Compilation d'une expression régulière :
# Recherche de 2 occurrences consécutives de : la plus petite chaîne de caractères
# (pouvant contenir des '\n'), et suivie d'au moins 2 '\n' consécutifs.
rec=re.compile('(.*?\n\n+){2}',re.S)
# Lecture du fichier donné en argument du script
with open(sys.argv[1],'r') as f :
fic=f.read()
n=0
while True : # Boucle infinie
k=rec.search(fic)
if(k) : # L'expression régulière est-elle trouvée ?
n+=1 # Numéro du fichier créé
with open('fichier%d.txt'%n,'w') as g :
g.write(k.group(0)) # Écriture de la chaîne trouvée
fic=fic[k.end(0):] # fic = fin du fichier
else :
if fic : # Reste-t-il quelque chose à écrire ?
n+=1 # Numéro du fichier créé
with open('fichier%d.txt'%n,'w') as g : g.write(fic)
break # Sortie de la boucle
#2 Re : -1 » [Résolu] Bash: rendre un test insensible à la casse » Hier à 12:26
pingouinux
Réponses : 6
Bonjour,
Je n'ai pas trouvé plus simple.
#!/bin/bash
shopt -s dotglob nocasematch
read -p 'Entrer un nom de fichier : ' nom
oui_non="n'existe pas"
for i in *; do
if [[ "$nom" == "$i" ]]; then
oui_non="existe"
break
fi
done
echo -e "Le fichier $nom $oui_non"
#3 Re : -1 » [Résolu] Bash: rendre un test insensible à la casse » Hier à 13:25
pingouinux
Réponses : 6
Le grep est une excellente idée, mais il faut faire ainsi :
#!/bin/bash
read -p 'Entrer un nom de fichier : ' nom
sortie=$(ls | grep -i "^$nom$")
if [ -e "$sortie" ]; then
echo -e "Le fichier $nom existe"
else
echo -e "Le fichier $nom n'existe pas"
fi
Édité : Beaucoup plus simple
#!/bin/bash
read -p 'Entrer un nom de fichier : ' nom
ls | grep -i "^$nom$" && echo -e "Le fichier $nom existe" || echo -e "Le fichier $nom n'existe pas"
#4 Re : -1 » [RESOLU] Comment revenir à mon menu principal ? » Hier à 08:44
#5 Re : -1 » [RESOLU] Comment revenir à mon menu principal ? » Hier à 08:55
pingouinux
Réponses : 3
Bonjour,
for f in *; do echo mv "$f" "${f#*-}"; done
Enlever le echo si c'est bon.
Ajouté : La commande sans echo ne doit être exécutée qu'une seule fois, sinon elle tronquera de nouveau le nom des fichiers
#10 Re : -1 » Raccourci dossier par défaut (Images). » Le 17/09/2014, à 04:50
#11 Re : -1 » Raccourci dossier par défaut (Images). » Le 18/09/2014, à 19:06
#12 Re : -1 » Raccourci dossier par défaut (Images). » Le 18/09/2014, à 19:09
#13 Re : -1 » [résolu] tree comment exclure des fichiers? » Le 17/09/2014, à 19:34
#14 Re : -1 » [résolu] tree comment exclure des fichiers? » Le 17/09/2014, à 20:13
#15 Re : -1 » [résolu] tree comment exclure des fichiers? » Le 18/09/2014, à 06:57
pingouinux
Réponses : 19
Bonjour,
Existe-t-il une commande qui permettrait de faire la même chose pour un grand nombre de fichier pdf ?
Oui, il est possible de faire une boucle. Il faudrait que tu précises le nom des paires de fichiers de départ et celui des fichiers générés.
#17 Re : -1 » [RÉSOLU] Thunderbird et sa ligne de commande » Le 15/09/2014, à 11:05
pingouinux
Réponses : 19
Ceci a l'air de marcher :
r=;for v in "$@"; do r="$r$v,"; done
thunderbird -compose "attachment='${r%?}'"
Ajouté :
Et ceci aussi
r=;for v in "$@"; do r="$r$v,"; done
r='-compose "attachment='\'${r%?}\''"'
eval thunderbird "$r"
#18 Re : -1 » [RÉSOLU] Thunderbird et sa ligne de commande » Le 18/09/2014, à 09:26
#21 Re : -1 » Interprête s'il vous plaît ! » Le 16/09/2014, à 14:17
#22 Re : -1 » affichage effacement sur console » Le 15/09/2014, à 12:38
pingouinux
Réponses : 8
Bonjour,
Je m'étais fait un script pour voir l'évolution de la copie avec dd, et en voici une adaptation pour ton cas.
#! /bin/bash
# BS = Taille d'un bloc
BS=$((1024*1024))
# Taille de /dev/sdb
size=$(sudo fdisk -l /dev/sdb | awk '/^Disk .* bytes/{print $5}')
n=0
while true
do
echo dd if=/dev/zero of=/dev/sdb bs=$BS count=1 skip=$n seek=$n 2>/dev/null
if (((++n)*BS<size)); then
printf "\r%8d blocs de %d octets (%3.0f %%)" $n $BS $((100*n*BS/size))
else
LC_ALL=C \
printf "\r %8.2f blocs de %d octets (%3.0f %%)" $(bc -l <<<"$size/$BS") $BS 100
break
fi
done
echo
dd est appelé une fois par bloc. Tel qu'il est, le script n'écrit rien sur la partition. Si le décompte se fait correctement, tu pourras enlever le echo devant dd.
|
I have the following relational schema (say MySQL, it's really in my head):
Login, Customer, Friendship, Address, Child, School
such that
Login(username, password)
Customer(id, firstName, lastName)
Friendship(customer_id, customer_id) //many to many
Address(customer_id, street, city, state, zip)
Child(id, firstName, lastName, customer_id, school_id)//each customer may have many children
School(id, name, city, state, zip)// there are many children per school
I want to rewrite the schema as a Google App Engine High Replication Datastore (HRD) schema: Does anyone know how to do that?
Here is as far as I got:
class Login(db.Model):
username = db.StringProperty()
password = db.StringProperty()
class Customer(db.Model):
first_name = db.StringProperty()
last_name = db.StringProperty()
class Address(db.Model):
# what goes here?
class Friendship(db.Model):
# what goes here?
class Child(db.Model):
# what goes here?
class School(db.Model):
# what goes here?
I am using python 2.7.
|
Secure Your Wireless with IPsec
Pages: 1, 2
Racoon Likes to Keep Secrets
Instead of manually changing the shared secrets in your /etc/ipsec.conf file, you can keep one shared secret and use the IKE protocol to negotiate a key. Racoon speaks IKE (ISAKMP/Oakley), which is a key management protocol.
I installed Racoon from the ports tree. Here are the configuration files from both my laptop and the gateway. The only difference between the two files is that I instruct the gateway to listen on only one address (it has two NICs). Here is the diff, if you are interested:
--- racoon.conf.laptop Wed Sep 15 19:26:03 2004
+++ racoon.conf.gateway Wed Sep 15 19:31:46 2004
@@ -33,6 +33,8 @@
#isakmp 202.249.11.124 [500];
#admin [7002]; # administrative's port by kmpstat.
#strict_address; # required all addresses must be bound.
+
+ isakmp 10.0.0.1;
}
# Specification of default various timer.
The configuration file tells Racoon the main things it needs to know. One of the items is the preshared key file. Look for this directive:
# search this file for pre_shared_key with various ID key.
path pre_shared_key "/usr/local/etc/racoon/psk.txt" ;
From man racoon.conf:
Pre-shared key File Pre-shared key file defines a pair of the identifier and the shared secret key which are used at Pre-shared key authentication method in phase 1. The pair in each lines are separated by some number of blanks and/or tab characters like hosts(5). Key can be included any blanks because all of the words after 2nd column are interpreted as a secret key. Lines start with #' are ignored. Keys which start with ' are hexa-decimal strings. Note that the file must be owned by the user ID running racoon(8) (usually the privileged user), and must not be accessi- ble by others.
Here is the /usr/local/etc/racoon/psk.txt file on my laptop:
10.0.0.1 MySecretValue
Here is the file from the wireless gateway:
10.0.0.10 MySecretValue
With these values, Racoon on my laptop knows that when it talks to 10.0.0.1 (the gateway) it should use the shared key MySecretValue. Similarly, the Racoon running on the gateway knows to use the same shared key when speaking to 10.0.0.10 (my laptop).
To start Racoon, issue this command:
/usr/local/etc/rc.d/racoon.sh start
If you're running a recent version of FreeBSD (for example, 4.10-RELEASE), add this entry in /etc/rc.conf:
racoon_enable="YES"
Ensure that Racoon is running on both the laptop and the gateway. Then remove the SAD entries from both machines, and Racoon should negotiate a new set of keys.
# setkey -c
flush;
^D
If that doesn't work, try running Racoon in the foreground (after first stopping the one running in the background):
/usr/local/sbin/racoon -F
It should just work.
Fun with Keys: Understanding What Happens
I thought it might be interesting to clear out the SAD entries and see what happens when it comes time to negotiate new keys. I started a ping running and ran tcpdump while I issued this command:
# setkey -F
As you can see, the ping missed a few steps. That is understandable.
[dan@laptop:~] $ ping -A 192.168.0.18
PING xeon.unixathome.org (192.168.0.18): 56 data bytes
64 bytes from 192.168.0.18: icmp_seq=0 ttl=63 time=4.880 ms
64 bytes from 192.168.0.18: icmp_seq=1 ttl=63 time=4.847 ms
64 bytes from 192.168.0.18: icmp_seq=2 ttl=63 time=5.126 ms
64 bytes from 192.168.0.18: icmp_seq=3 ttl=63 time=5.209 ms
64 bytes from 192.168.0.18: icmp_seq=6 ttl=63 time=5.468 ms
64 bytes from 192.168.0.18: icmp_seq=7 ttl=63 time=4.838 ms
64 bytes from 192.168.0.18: icmp_seq=8 ttl=63 time=5.270 ms
^C
--- xeon.unixathome.org ping statistics ---
9 packets transmitted, 7 packets received, 22% packet loss
round-trip min/avg/max/stddev = 4.838/5.091/5.468/0.226 ms
[dan@laptop:~] $
Two pings went missing and never reached the machine on the other side of the gateway. Here is some of the tcpdump traffic:
16:36:34.517794 10.0.0.10 > 10.0.0.1: ESP(spi=0x02dc8063,seq=0x1d)
16:36:34.867830 10.0.0.10 > 10.0.0.1: ESP(spi=0x02dc8063,seq=0x1e)
16:36:34.873592 10.0.0.1 > 10.0.0.10: ESP(spi=0x0751ce23,seq=0x1d)
16:36:35.737921 10.0.0.10.500 > 10.0.0.1.500: isakmp: phase 2/others
? inf[E]: [encrypted hash]
16:36:35.904270 10.0.0.10.500 > 10.0.0.1.500: isakmp: phase 2/others
? oakley-quick[E]: [encrypted hash]
16:36:36.604941 10.0.0.1.500 > 10.0.0.10.500: isakmp: phase 2/others
? oakley-quick[E]: [encrypted hash]
16:36:36.605565 10.0.0.10.500 > 10.0.0.1.500: isakmp: phase 2/others
? oakley-quick[E]: [encrypted hash]
16:36:36.887859 10.0.0.10 > 10.0.0.1: ESP(spi=0x01f4fcea,seq=0x1)
16:36:37.897889 10.0.0.10 > 10.0.0.1: ESP(spi=0x01f4fcea,seq=0x2)
The lines that contain isakmp represent the two Racoon daemons negotiating a new key.
As an experiment, I turned off IPsec on my laptop by commenting out the ipsec_enable line in /etc/rc.conf. Then I rebooted. Interestingly, I still received an IP address from my DHCP server on the other side of the wireless gateway. However, I could not get through the gateway. Even simple pings to the gateway went unanswered. At this time, the firewall on the wireless gateway allowed all traffic to pass. Therefore, the gateway rejected the traffic because it did not use IPsec.
To make IPsec work again, I did this while the ping was still running:
[root@laptop:/home/dan] # setkey -f /etc/ipsec.conf
[root@laptop:/home/dan] # tcpdump -ni wi0 tcpdump: listening on wi0
17:21:20.168434 10.0.0.10.500 > 10.0.0.1.500: isakmp: phase 2/others
? oakley-quick[E]: [encrypted hash]
17:21:46.426485 10.0.0.10.500 > 10.0.0.1.500: isakmp: phase 2/others
? oakley-quick[E]: [encrypted hash]
17:21:47.112010 10.0.0.1.500 > 10.0.0.10.500: isakmp: phase 2/others
? oakley-quick[E]: [encrypted hash]
17:21:47.113115 10.0.0.10.500 > 10.0.0.1.500: isakmp: phase 2/others
? oakley-quick[E]: [encrypted hash]
17:21:47.375549 10.0.0.10 > 10.0.0.1: ESP(spi=0x02c19c7a,seq=0x1)
17:21:48.385549 10.0.0.10 > 10.0.0.1: ESP(spi=0x02c19c7a,seq=0x2)
17:21:48.390088 10.0.0.1 > 10.0.0.10: ESP(spi=0x041e48fb,seq=0x1)
17:21:49.395564 10.0.0.10 > 10.0.0.1: ESP(spi=0x02c19c7a,seq=0x3)
17:21:49.399754 10.0.0.1 > 10.0.0.10: ESP(spi=0x041e48fb,seq=0x2)
The first line populates the SPD1 database, based upon the data within the file /etc/ipsec.conf. From there, Racoon must negotiate a new key. It took some time (about 26 seconds), but Racoon eventually succeeded. Immediately thereafter, the pings resumed.
1Actually, the command populates only the SAD because the file in question contains only add commands. I commented out the spdadd commands.
DHCP Server
I mentioned above that I could still receive an IP address from my DHCP server that was running on my gateway. I had not previously mentioned it, but I think it might be useful to you. Here are the basics; the rest you should be able to piece together yourself.
Installing dhcpd
To install the dhcp server, I did this:
# cd /usr/ports/net/isc-dhcp3-server
# make install clean
Starting at boot time
This will install /usr/local/etc/rc.d/isc-dhcpd.sh. Remember to add dhcpd_enable="YES" to /etc/rc.conf, or the script will not start the server. I also added dhcpd_ifaces="dc0" so that dhcpd would listen only on the one NIC--the one attached to the same hub as the WAP.
The configuration file
The port installs /usr/local/etc/dhcpd.conf. It is full of examples, but here is what I'm using, slightly altered to protect the obvious:
default-lease-time 600;
max-lease-time 7200;
authoritative;
ddns-update-style none;
option domain-name "example.org";
#
# this points to my local DNS server on the other
# side of the wireless gateway
#
option domain-name-servers 192.168.0.101;
default-lease-time 86400;
max-lease-time 86400;
# This is a very basic subnet declaration.
subnet 10.0.0.0 netmask 255.255.255.0 {
option routers 10.0.0.1;
range 10.0.0.192 10.0.0.207; # this is 10.0.0.200/27 => (28)
host laptop.example.org {
option dhcp-client-identifier "laptop.example.org";
fixed-address laptop.example.org;
}
}
That fixed-address relates to the following entry in /etc/dhclient.conf:
send dhcp-client-identifier "laptop.example.org";
This allows the laptop to tell the DHCP server who it is, which I use to assign a specific IP address. Note: this method is convenient, but it is not necessarily secure. If you're like me, sometimes using wireless with your laptop and sometimes connecting via wire, then you might want to give it a different IP address depending on where it is. I do that by having two DHCP servers. I'm sure someone will suggest another method.
Is That Enough?
Now you have your wireless laptop connected to your LAN, with encrypted and secured traffic. Nobody else can use your gateway unless they guess the secret key. That's not easy. The key will change from time to time, so even if someone guesses a key, there's a new one coming along soon. The only thing you have to secure is the preshared secret. Don't use what I've supplied. Come up with something odd, even some random values. Pick some text from IRC. That should work.
Are you being paranoid enough? I think for one of my next tasks I will look for any unusual traffic coming on the gateway, from any IP other than my laptop. There are whole books written on intrusion detection, and that topic is well beyond what I can cover here.
Enjoy.
Dan Langille runs a consulting group in Ottawa, Canada, and lives in a house ruled by felines.
Return to the BSD DevCenter.
Comments on this article
SAD or SPD
2004-11-01 15:14:00 tugrul [View]
SAD or SPD
2004-11-01 16:16:41 danlangille [View]
WiFi Bandits
2004-10-26 03:03:21 [View]
2004-10-21 22:25:19 wensy [View]
Wireless+IPSec with Windows laptops?
2004-11-01 16:19:06 danlangille [View]
|
I have harvested data, its not particularly clean data, and this has been bulk uploaded into the DataStore. However I am getting the following issue when trying to simply loop through all the records. I don't much care about validation at this point as all I want to do is perform a bulk operation but GAE appears not to let me even loop through the data records. I want to get at the bottom of this. To my knowledge all records have data in the field for the country and I could switch of validation, but can someone explain why this is happening and GAE is being sensitive. Thanks
result = Company.all()
my_count = result.count()
if result:
for r in result:
self.response.out.write("hello")
The data model has these properties:
class Company(db.Model):
companyurl = db.LinkProperty(required=True)
companyname = db.StringProperty(required=True)
companydesc = db.TextProperty(required=True)
companyaddress = db.PostalAddressProperty(required=False)
companypostcode = db.StringProperty(required=False)
companyemail = db.EmailProperty(required=True)
companycountry = db.StringProperty(required=True)
The error message is below
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/_webapp25.py", line 701, in __call__
handler.get(*groups)
File "/base/data/home/apps/XXX/1.358667163009710608/showcompanies.py", line 99, in get
for r in result:
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/db/__init__.py", line 2312, in next
return self.__model_class.from_entity(self.__iterator.next())
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/db/__init__.py", line 1441, in from_entity
return cls(None, _from_entity=entity, **entity_values)
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/db/__init__.py", line 973, in __init__
prop.__set__(self, value)
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/db/__init__.py", line 613, in __set__
value = self.validate(value)
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/db/__init__.py", line 2815, in validate
value = super(StringProperty, self).validate(value)
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/db/__init__.py", line 640, in validate
raise BadValueError('Property %s is required' % self.name)
BadValueError: Property companycountry is required
|
web.py 0.2 tutorial
Installation
Vous connaissez Python et vous voulez construire un site web. Web.py fournit le code pour faire cela d'une manière simple.
Si vous voulez faire l’ensemble de ce tutoriel vous devrez installer Python, web.py, flup, psycopg2 et Postgres (ou une autre base de données avec son driver pour Python, par exemple : MySQL et mysqldb). Pour plus de détails voir le site de webpy.org.
Si vous avez un projet web.py existant, regardez la page de upgrade pour plus d’informations sur la migration vers la nouvelle version.
Gestion des URLs
La partie la plus importante pour chaque site web est la structure des URLs. Les URLs ne sont pas seulement ce que les visiteurs regarde et partage avec d’autres amis, mais ils sont aussi un modèle mental qui indique comment un Site Web fonctionne. (Dans les sites populaires comme del.icio.us, les URLs font partie de l’interface de l’utilisateur). Pour cela Web.py facilite la création et la gestion des URL.
Pour commencer l’application web.py , Créez un nouveau fichier et appelez le code.py par exemple et écrivez ceci dedans:
import web
Ceci importera le module web.py.
Maintenant on implémente la structure de nos URLs, on commence par quelque chose de simple, ajoutez cela :
urls = ( '/', 'index' )
La première partie est l’expression régulière qui représente un chemin. Par exemple : ‘/’, ‘/aide/faq’, ‘/article/(\d+)’, etc. Le \d+ représente une séquence de chiffres. Les parenthèses (..) servent à capturer les éléments retournés pour plus tard. La deuxième partie est le nom d’une classe à laquelle envoyer la requête, comme view, welcomes.hello (qui utilise la classe hello du module welcomes), ou bien get_\1. \1 est remplacé par la première capture de l’expression régulière. Toutes captures restantes seront passées à la fonction.
La ligne ('/', 'index') dis qu’on a besoin de l’URL ‘/’ (i.e la page d’accueil) qui sera prit en charge par la classe nommé ‘index’.
Maintenant on écrit le code de la classe index:
class index:
def GET(self):
print " Bonjour, monde !"
Comme vous avez pu le deviner, GET est appelé par web.py lorsque quelqu’un appelle la méthode HTTP GET sur votre URL ‘/’ (c’est-à-dire quand ils la visitent avec un navigateur web). La dernière ligne renvoie le texte brut “Bonjour, monde !” au visiteur.
Tous est bon maintenant, on aura besoin que de finir en ajoutant la ligne qui démarre l’application web
if __name__ == "__main__": web.run(urls, globals())
Ceci dit à web.py de lancer votre application avec urls en regardant toutes les classes présentes dans le fichier.
Pour lancer le serveur web faisant tourner votre application tapez dans une invite de commande:
$ python code.pyLaunching server: http://0.0.0.0:8080/
Maintenant si vous visitez http://0.0.0.0:8080/ avec un navigateur web, vous devriez voir apparaître “Bonjour, monde !”.
Note: vous pouvez spécifier le port en le passant comme paramètre
$ python code.py 1234
Puis visiter la page : http://0.0.0.0:1234/
(La suite à accomplir...)
|
If Kerouac wrote JavaScript (and Dr Johnson wrote CoffeeScript)
(New Book “If Hemingway wrote JavaScript” out in September 2014.Pre-order your copy here:http://www.amazon.com/Hemingway-Wrote-JavaScript-Angus-Croll/dp/1593275854)
Last summer I introduced the concept of literary JavaScript with If Hemingway wrote JavaScript in which five well known authors wrote a JavaScript utility to generate the Fibonacci sequence. In May I presented their efforts at JSConf 2013, and to mark the occasion I asked an additional six authors (as well as the irrepressible Hemingway) to solve factorial(n) as only they could. Here’s what they sent me…
Jack Kerouac
“All of JavaScript is a foreign country”
/*...the only numbers for me are the mad ones, take forty-three like a steam engine with a talky caboose at the end*/ n = 43, /*and that lanky fellow in a cocked fedora*/ r = 1 /*then back to our number, our mad number, mad to become one*/ while (n > 1) /*mad to descend*/ n--, /*mad to multiply*/ r = r * n /*and at the end, you see the blue center-light pop, and everybody goes 1.4050061177528801e+51...*/
r
Kerouac is renowned for his spontaneous, stream-of-consciousness approach to writing, supposedly delivering some works at a single sitting. Since planning is alien to Kerouac’s process, he has no use for functions. His solution will only return the factorial of 43. If you want the factorial of another number, you’ll need to rewrite it.
Notice how comments are virtually indistinguishable from code; to Kerouac it’s all the same – one long, rhapsodic outpouring.
Samuel Johnson
“When a man is tired of JAVA-SCRIPT, he is tired of LIFE”
# In which various NUMBERS are summon'd by
# means of ELECTRONICK CONJURY
factorial = (n) ->
# All argument is against it; yet all belief is for it
return 1 unless n
# Ingenious sophistry to prove the palp'bly OBVIOUS
return 1 if n is 1
# Recursion (n.)
# a program that calls 'pon itself in the manner of
# a dog returning unto its VOMIT
return n * factorial n - 1
When I opened Johnson’s completed assignment, I found a short note from the good doctor, explaining why he had chosen to use CoffeeScript: “Sir, the funcktion key-word is an ALBATROSS and the curly brace is worthless FILIGREE. I desire a clean and artickulate script for the dockumenting of my varied MUSINGS”.
And indeed Johnson’s solution radiates sparse elegance, albeit liberally peppered with his own pithy witticisms: he expresses his incredulity that factorial(0) is 1, is amused that it should require an entire statement to ascertain that factorial(1) is indeed 1, and finishes with a sardonic definition of recursion lifted, presumably, from his own dictionary.
Johnson’s solution lies at the intersection of art and parody – a gentle self-mocking blended with uncluttered expression and genuine beauty. A doff of the tricorn to you, Doctor.
James Joyce
“Writing in JavaScript is the most ingenious torture ever devised for sins committed in previous lives”
function hacktorial(integette) {
var nonthings = [undefined, null, false, 0, '', NaN];
var resultution = 1;
if (integette == 0) {
//behold the strangerous zeroine!
resultution = 1;
} else {
while (integette > 1)
//caligulate by multicapables
resultution = resultution * integette--;
}
with(resultution) {
var duodismal = Function('return this').call(toString(12));
var disemvowel = Function("n","return n?parseInt(n,12):'0'")
return [
disemvowel(duodismal.slice(0,-1)),
'shillings and',
disemvowel(duodismal[duodismal.length-1]), 'pence'
].join(' ');
}
//klikkaklakkaklaskaklopatzklatschabattacreppycrottygraddahappluddyappladdypkonpkot!
}
OK, where do we start? Joyce is not content with merely solving the problem at hand, he is compelled to turn it into a raucous adventure on the high seas of verbal deviancy.
He continues the Joycean tradition of generating contrived yet intuitive portmanteau words (most abundantly present in Finnegans Wake). Here’s a mini glossary for the Joyce-less among us:
hacktorial–the function is a hack on factorial
integette–indicating that if you don’t use a small integer it’s all ruined
nonthings–for reasons best known to Joyce, our function begins with a declaration of falsey values
resultation–the result of the computation
strangerous–both strange and dangerous
zeroine–our heroine, value 0
caligulate–to calculate, presumably with a liberal dose of tyranny
multicapables–items capable of being multiplied
duodismal–the bleakness that is the duodecimal system (i.e. base 12)disemvowel–to remove all vowels, or in this case all letters
By the time he’s half way through, the problem is already solved, but Joyce insists on converting the result into the currency of the time: shillings and pence. As with much of Joyce’s work, there’s a degree of method to this madness, since the factorial of every number over 3 is divisible by 12 – which also happens to be the number of pennies in a shilling.
Here’s what we get:
hacktorial(3) //"0 shillings and 6 pence"
hacktorial(4) //"2 shillings and 0 pence"
hacktorial(7) //"420 shillings and 0 pence"
hacktorial(21) //"4257578514309120000 shillings and 0 pence"
Richard Feynman
“I never pay attention to anything by experts. I program everything myself.”
//using Ramanujan's approximation
function fractorail(n){
with(Math) {
var r = sqrt(PI)*pow(n/E,n);
r *= pow(8*pow(n, 3) + 4*(n*n) + n + 1/30, 1/6);
return r;
}
}
Although better known as a maverick scientist, Feynman’s work is characterized by the daring originality and eccentric brilliance that is the hallmark of the greatest authors. His factorial solution is no exception.
Feynman chooses to distance himself from conventional strategies and instead uses a little known approximation which allows him to calculate the factorial of integers and non-integers alike. His boyish delight at this discovery is evident from the playful name he assigns to the function. He also tosses in a delicious with, just to prove the pedants wrong.
Here’s a few factorial’s, Feynman style. Don’t worry about the alleged “rounding errors”, if you’re at all familiar with JavaScript, they’ll likely be a source of comfort to you.
fractorail(3); //6.00005
fractorail(1.1); //1.04671
fractorail(5.2); //169.40628
Arthur Conan Doyle
“You know my methods. Apply them”
"use strict";
//In solving a problem of this sort, the grand thing is to be able to reason backwards...
//some things are easier known than explained!
var caseHistory = new Object({2:2, 6:3});
function unfactorial(evidence){
//first, humility!
if (evidence === 1) {
return "Watson, I am at a loss!"
}
//second, logical precedence!
if(caseHistory[evidence]){
//elementary!
return caseHistory[evidence];
}
//third, eliminate the impossible!
if(evidence === 0 || evidence % 24 !== 0) {
return "charlatans!";
}
//fourth, deduction!
var theDeduction, enumarator = evidence, denominator = 1;
while(enumarator % denominator === 0) {
enumarator = enumarator/denominator++;
if (enumarator === denominator) {
theDeduction = enumarator;
}
}
theDeduction = theDeduction || "impostors";
//What one man can invent another can discover!
caseHistory[evidence] = theDeduction;
//What remains, however improbable, must be the truth!
return theDeduction;
}
Conan Doyle is best known as the author of the Sherlock Holmes mysteries and he was clearly in full deer-stalker and magnifying glass mode when solving the case of the hidden factorial.
Or, rather, unfactorial. Because Holmes lives by deduction and his methodology is to work backwards towards the source of the deed – the well worn, predictable process of the factorial holds no mystery for him. Instead Holmes opts to trace those fiendish numbers that seed existing factorial results.
As expected, Holmes' process is precise and meticulously ordered – clearly he was an early adopter of the imperative approach. Notice he also directs his utility to run in strict mode – he’ll tolerate no sloppiness. He starts with a dose of humility – even the master sleuth cannot be certain which number has a factorial of 1 – but he quickly gains his stride, so that by the end of the exercise he imperiously derides those who would supply false arguments as charlatans and impostors. Case closed Watson.
Jane Austen
“A programmer, especially if she has the misfortune of knowing anything, should conceal it as well as she can”
factorial = (function() {
//I declare...
var ledger = {};
return function reckoning(quantity) {
if (isNaN(quantity)) {
console.log("I have not the pleasure of understanding you");
return;
}
//It is a truth universally acknowledged that two values
//can only be adjudged truly agreeable by means of ===
if (quantity === 0) {
return 1;
}
//Mr Crockford teaches that we be wary of inherited property...
if (ledger.hasOwnProperty(quantity)) {
return ledger[quantity];
}
//Pray persist until an answer is furnished
return ledger[quantity] = quantity * reckoning(quantity - 1);
};
})();
Jane Austen’s solution demonstrates two pleasing characteristics for which she is justly famous. First there’s her attention to craft and structural integrity, reflected here in the neat packaging of her code – she invokes the module pattern, hiding away the historical data (or ledger) within the folds of the super structure. Second is her playful, even subversive, send-up of the powers that be and their ridiculous conventions.
At first glance Austen’s code appears to be submissive, yielding to every overbearing commandment and pious proclamation set forth by the more pedantic leaders in our community. Yet a closer reading reveals a rich undertone of parody. There are several clues to Austen’s real intent: checking if the argument is a number pokes fun at edge-case mania, her over-embellished commentary suitably ridicules those who insist that == is the devils work, and finally the satirical fawning over the nice Mr Crockford is used as an amusing justification for the all-too-common misuse of hasOwnProperty.
Austen is on top of her game here, simultaneously gaining approval from the purveyors of code dogma, while winking furiously at those who can see beyond the artifice and discern the subtext that ridicules those she purports to follow.
Ernest Hemingway
“When you stop writing JavaScript for fun you may as well be dead”
//Economy.
function factorial(n) {
return n < 2 ? 1: factorial(n-1)*n;
}
Enough said.
What have we learned?
The greatness of the best novelists, poets and play-writes lies in their readiness to stake out new ground, to pioneer new techniques in writing and in doing so lay the tracks for those who follow.
All the best writers in English have been flagrant flouters of prescriptive rules – Steven Pinker
As with the best writers, when a good developer breaks a rule, they don’t do so arbitrarily, but because a dubious constraint has formed a barrier to their means of expression. Patterns that were once viewed as dangerous and radical – immediately invoked functions, callbacks and modules – are, thanks to the risk takers, now part of the JavaScript mainstream. The message is clear: the progress of the JavaScript language depends on the willingness of its best developers to take risks, to play, and so discover new patterns and idioms that benefit the community at large.
|
smo
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
mwoe effectivement y s arrete direct y cree pas les fichiers et sort... je regarde
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
smo
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
ola
c'est corrige pour le fichier de config, maj dans le git ok
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
smo
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
ola hizo
bah je vois pas quoi faire de plus, je capte pas ton pb tu es le seul, ce fichier là meme s il y est je veux dire il est vide je vois pas ce que ca changera le soucis c est pourquoi ton dhcp ne cree pas ce fichier surtout Oo
tests si tu veux en virant le rm du resolv.conf dans fichier export_dist.sh et dis moi
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
Hizoka
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
non je suis pas seul
ok je teste.
Hors ligne
Lenslarque
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
C'est ok pour moi pour le su, merci
Pour le resolv.conf j'ai laissé mon "fix" donc je ne sais pas
Hors ligne
Hizoka
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
etrange...
j'ai tout virer (dans le fichier export_dist.sh) ce que tu fais sur le fichier resolv.conf et j'ai ajouté :
echo "nameserver 8.8.8.8" > "${DISTDIR}"/chroot/etc/resolv.conf
mais malgre ca, pas de fichier ?!
et je vois que tu supprime le hosts ?
dommage ca veut dire qu'on peut pas le modifier non plus ?
Dernière modification par Hizoka (Le 31/10/2012, à 19:56)
Hors ligne
kezako_06
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
@ smo
Merci pour la mise à jour qui a solutionné le problème de ./config/ubukey qui est bien créé. Toutefois le second bug persiste, après l'extraction de l'iso, je reste bloqué à "Preparing chroot, please wait..." qui s'affiche indéfiniment, idem en relançant le programme. Le test a été effectué avec une quantal desktop d'origine. J'ai l'impression qu'il ne reconnaît pas l'environnement chrooté ou quelque chose de ce genre, parce qu'il extrait l'iso autant de fois que le programme est relancé dans un dossier /distrib donné...
EDIT : à l'instar de Fedora, Ubuntu est doté d'un gestionnaire de volume logique (LVM) lors de l'installation depuis "Quantal". Peut-être une piste à creuser ?
Dernière modification par kezako_06 (Le 31/10/2012, à 21:29)
Hors ligne
smo
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
ola
bah alors la franchement je vois hizoka tu fais ca avec une kde ? faudra que j test et le hosts si j le laisse et que tu boot sur un autyre pc ca peut poser soucis donc woe j le vire c est pas logique de le laisser a moins que j me plante mais j pense pas
kezako, ok pour la maj, de rien
alors apres par contre je capte pas ton pb, tu fais quoi exactement? tu cree un distrib , tu charges un iso ou tu lui en indiques un ? si oui lequel ? et comment ca y te reextrait l iso autant de fois que tu relances le soft ?? details un peu plus si possible
ensuite apres avoir lancé le chroot , regardes dans le dossier de la distrib t as un dossier logs et un fichier chrootlog.log, postes le
thx
edit: un truc possible c est qu il n arrive pas a recup certains fichiers de mon serveur que j ai reinstalle et que j ai pas encore reconfigure, vu que nous on a deja tous les fichiers je m en rend pt etre pas compte je regarderai des que possible (pas trop chez moi en ce moment)
Dernière modification par smo (Le 01/11/2012, à 09:24)
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
kezako_06
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
ola
bah alors la franchement je vois hizoka tu fais ca avec une kde ? faudra que j test et le hosts si j le laisse et que tu boot sur un autyre pc ca peut poser soucis donc woe j le vire c est pas logique de le laisser a moins que j me plante mais j pense pas
kezako, ok pour la maj, de rien
alors apres par contre je capte pas ton pb, tu fais quoi exactement? tu cree un distrib , tu charges un iso ou tu lui en indiques un ? si oui lequel ? et comment ca y te reextrait l iso autant de fois que tu relances le soft ?? details un peu plus si possible
ensuite apres avoir lancé le chroot , regardes dans le dossier de la distrib t as un dossier logs et un fichier chrootlog.log, postes le
thx
edit: un truc possible c est qu il n arrive pas a recup certains fichiers de mon serveur que j ai reinstalle et que j ai pas encore reconfigure, vu que nous on a deja tous les fichiers je m en rend pt etre pas compte je regarderai des que possible (pas trop chez moi en ce moment)
Bonjour smo,
Pour mes distributions j'utilise des isos précédemment téléchargées, j'ai fait le test avec des "quantal" version desktop et gnobuntu pour le même résultat : "Preparing chroot, please wait..." et aucun fichier log ou chrootlog.log n'est présent. Ce qui me fait dire que l'iso est clonée à l'infini c'est que je me suis retrouvé avec 1.607.697 fichiers dans un seul dossier de travail de /distribs. Une iso de base comportant environ 150.000 fichiers à l'origine, j'ai bien dû essayer de chrooter près d'une dizaine de fois... J'en déduis donc qu'il ne reconnaît pas l'iso préalablement extraite avant le chroot. Par ailleurs, impossible de supprimer totalement un dossier de travail depuis la fonction "supprimer" d'ubukey : la distro disparaît du listing ubukey, mais nautilus prouve simultanément le contraire... Après avoir fait le ménage manuellement d'abord, puis avec Bleachbit, rebooté, etc... les mêmes opérations ont produit les mêmes effets : impossible de chrooter !
Hors ligne
smo
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
hummm very strange !!!
alors ce que tu fais
refais en une et posts ici le .config/ubukey/logs/log (de tete hein dans dossiers logs en tout cas) ca m fera voir tout ce qu il y a eu dans la console et regarde ensuite, apres creation ce que tu as dans le dossier chroot de ta distrib please
et donc ca t fait pareil avec une distrib quantal officielle ??
thx
Dernière modification par smo (Le 01/11/2012, à 11:30)
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
Lenslarque
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
Salut à tous
Smo je confirme depuis la dernière màj le réseau c'est pire, le fichier est maintenant un lien symbolique sur un fichier qui n'existe pas, sans copier/coller le chemin est un peu long à écrire, mais en gros il pointe sur un chemin de la machine hôte donc il connaît pas.
Sinon tu sais pourquoi je ne peux plus mettre à jour mon kernel ?
Hors ligne
Hizoka
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
le hosts si j le laisse et que tu boot sur un autyre pc ca peut poser soucis donc woe j le vire c est pas logique de le laisser a moins que j me plante mais j pense pas
Perso je l'utilise pour bloquer les pubs et autres saloperies...
la seule chose à modifier c'est cette ligne :
127.0.0.1 localhost hizo-computer
faut remplacer le $HOSTNAME, y aurait pas moyen d'integrer ca ?
genre dans un fichier de boot (rc.local...)
Lenslarque => ca me rassure, ca vient pas de moi
Hors ligne
Lenslarque
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
Lenslarque => ca me rassure, ca vient pas de moi
Toutefois le hosts ne pose pas de problème, c'est juste le resolv.conf, tu peux me dire si tu peux faire un dist-upgrade dans ta distrib (dans ubukey) une fois que tu as mis un resolv.conf correct bien sûr.
Hors ligne
Hizoka
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
non non pas de soucis avec le host, j'ai juste vu ca
dans mon chroot, j'ai pas de soucis de maj, la connexion est ok, car mon resolv.conf est bien là...
par contre aucune maj du noyau... dist-upgrade marche mais bon...
Hors ligne
Lenslarque
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
non non pas de soucis avec le host, j'ai juste vu ca
dans mon chroot, j'ai pas de soucis de maj, la connexion est ok, car mon resolv.conf est bien là...
par contre aucune maj du noyau... dist-upgrade marche mais bon...
Ok oui c'est bien ça, pas de màj du noyau, tu me rassures aussi :-)
Hors ligne
smo
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
Ola
J rentre chez moi suis dans l métro a l autre bout de paris , j avoue pas pris le temps de tester le lien resolv.conf
Vais corriger ça dans quelques minutes mais j parie que ça changera pas ton pb hizo t as essaye en.supprimant le rm du export_dis.sh???
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
smo
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
ola
bon j ai fait une modif je test voir ce que ca donne..
piur le hosts hizo tu sais que tu peux faire tes propres scripts perso qui seront inclus dans le chroot hei a toi e n faire un qui modifie le rc.local par exemple et posts le nous apres... on fera a terme une base de scripts en ligne
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
smo
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
ola
bon j ai fait la modif, je test...
hizo. cree toi un script perso pour modifier le rc.local par exemple c est fait pour et proposes le nous apres si tu veux modifier ton hosts
edit: git mis a jour, lien ok qui pointe bien sur ../run/resolvconf/resolv.conf comme le live-cd d origine.. peut pas mieux faire là
pas besoin de rentrer dans chroot refais juste un iso avec bouton export si tu veux tester hizo
lenslarque aucune idee pour maj kernel perso pas de soucis sur les dist-upgrade.. ca t fait quoi ?
Dernière modification par smo (Le 02/11/2012, à 00:24)
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
smo
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
woe bah j sais pas une fois boote ca marche pas, j fais sudo dhclient eth0 dans qemu par exemple et ca marche j vois pas trop l rapport avec ubukey là ca fait des annees que j ai pas touche cette partie ca a tjrs fonctionné Oo ....
Dernière modification par smo (Le 02/11/2012, à 00:35)
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
Hizoka
Hors ligne
smo
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
ola
mwoe doit y avoir un bug dans un paquet al j vois pas d autre solution...
t as un bouton scripts ou plugins dans ubukey en haut tu verras.. tu fais nouveau y t fera un squelette et voila
apres tu l auras automatiquement dans le gestionnaire de plugins ubukey dans le chroot
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
Hizoka
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
je testerai avec une version sans modif de paquet.
Quand je fais nouveau, il me crée rien du tout...
Hors ligne
smo
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
ah oui pt etre que j lance gedit moi de tete me rappel plus si j passai par xdg....
mais bon sinon tu mets tes scripts dans addons/custom du dossier de distributions
edit: si j passe par xdg-open pourtant ca devrait t lancer kate ou kedit j sais pas ce que t as
def create_plug(self):
print _("creating new plugin...")
plug = open(os.path.join(self.main_dist_path,'addons/custom/new.sh'), "w")
plug.write ('''#!/bin/bash
###########
#
# Note:
# -----
# please always use "xterm -e" and/or zenity
# to start/show your scripts
#
###########
#
# Please add a description here, it will be viewable in the
# ubukey addons manager under the chroot !
DESCRIPTION=""
############
#
# Your code here...
''')
plug.close()
self.optwin.hide()
nfile = os.path.join(self.main_dist_path,'addons/custom/new.sh')
try:
(pid,t,r,s) = gobject.spawn_async(['/usr/bin/xdg-open', nfile],flags=gobject.SPAWN_DO_NOT_REAP_CHILD,standard_output = True, standard_error = True)
except:
return
data=(nfile)
gobject.child_watch_add(pid, self.task_done,data)
Dernière modification par smo (Le 02/11/2012, à 10:02)
ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr
ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408
tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com)
ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588
Hors ligne
Hizoka
Re : logiciel creation/remasterisation/clonage de distributions base ubuntu
edit: si j passe par xdg-open pourtant ca devrait t lancer kate ou kedit j sais pas ce que t as
Oui oui mais quelle est la commande exact que tu fais ?
creating new plugin...
Traceback (most recent call last):
File "ubukey.py", line 230, in create_plug
self.distribs.create_plug()
File "/home/hizoka/Scripts_et_logiciels/logiciels/ubukey/Ubukey/lib/distribs.py", line 159, in create_plug
plug = open(os.path.join(self.main_dist_path,'addons/custom/new.sh'), "w")
IOError: [Errno 2] Aucun fichier ou dossier de ce type: '/home/hizoka/Scripts_et_logiciels/iso/Non_save/smo/addons/custom/new.sh'
A la base il n'y avait pas de dossier custom, et encore moins de fichier new.sh
Hors ligne
|
michel2652
(pas résolu, mais...) mise à jour depuis dépots plf
Bonsoir,
Je viens d'installer Breezy sur un poste, tout s'est bien passé, mais pour installer différents paquets libres et non libres, j'ai eu quelques petits problèmes...
Après avoir modifié mon sources.list pour les PLF et les backports, des mises à jour (dont w32codecs) me sont proposées.
J'accepte les mises à jour dont;
w32codecs (20050412+breezy0.0.1)
mais lors du paramétrage, je reste bloqué
Paramétrage de w32codecs (20050412+breezy0.0.1) ...
--19:24:58-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
=> `windows-all-20050412.zip'
Résolution de www1.mplayerhq.hu... 192.190.173.45
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse...
Au bout d'un "certain temps" , je ferme ma session, me relogue, et essaye d'ouvrir synaptic pour desinstaller ce w32codecs:
E: dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem.
Je relance un terminal ;
michel@ubuntu-pc2:~$ sudo dpkg --configure -a
Password:
Paramétrage de w32codecs (20050412+breezy0.0.1) ...
--19:41:54-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
=> `windows-all-20050412.zip'
Résolution de www1.mplayerhq.hu... 192.190.173.45
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse...
Qu'elle est la manip à faire pour pouvoir de nouveau utiliser apt-get ou synaptic ?
A+
Dernière modification par michel2652 (Le 14/11/2005, à 15:09)
coink
Re : (pas résolu, mais...) mise à jour depuis dépots plf
essaie de le désinstaller avec synaptic. Ensuite ajoute à ton sources.list si ce n'est pas déjà fait
deb http://antesis.freecontrib.org/mirrors/ubuntu/plf/ breezy free non-free
deb-src http://antesis.freecontrib.org/mirrors/ubuntu/plf/ breezy free non-free
puis dans synaptic, tu met a jour, tu recherches les w32codecs, et tu vas dans les propriété du paquet.
Là tu vas dans l'onglet "versions" et tu choisi celle qui correspond au repository antesis.
Tu peux maintenant mettre à jour. Et normalement ça devrai marcher.
Par contre dès que tu vas faire un apt-get upgrade, il va vouloir te réinstaller le paquet w32codecs qui échouait car théoriquement il est plus récent. Donc un conseil, utilises toujours synaptic. Et pour éviter que synaptic t'embete il vaut mieux bloquer la version de ce paquet. Pour ce faire tu sélectionne le paquet, puis dans le menu "paquet" tu coche "bloquer la version"
J'espère que ça va t'aider et que ça va marcher.
bishop
Re : (pas résolu, mais...) mise à jour depuis dépots plf
Bonsoir
Le serveur PLF est mort (pour l' instant), voir:
http://wiki.ubuntu-fr.org/doc/plf-fr
Les nouveaux dépôts sont:
## FTP mirror from http://free.fr (french ISP)
deb ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/plf/ breezy free non-free
deb-src ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/plf/ breezy free non-free
Hors ligne
bishop
Re : (pas résolu, mais...) mise à jour depuis dépots plf
Bonsoir
Le serveur PLF est mort (pour l' instant), voir:
http://wiki.ubuntu-fr.org/doc/plf-fr
Les nouveaux dépôts sont:
## FTP mirror from http://free.fr (french ISP)
deb ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/plf/ breezy free non-free
deb-src ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/plf/ breezy free non-free
Hors ligne
michel2652
Re : (pas résolu, mais...) mise à jour depuis dépots plf
Merci bien, coink et bishop, mais le problème est que je n'ai plus accès à synaptic, j'ai ce message:
Impossible d'obtenir un verrou exclusif
Ceci signifie habituellement qu'une autre application de gestion des paquets est en cours d'exécution (comme, par exemple, apt-get ou aptitude). Veuillez d'abord fermer cette application.
J"avais déjà modifié mon sources.list :
# UBUNTU
deb http://fr.archive.ubuntu.com/ubuntu breezy main restricted
# SECURITE
deb http://security.ubuntu.com/ubuntu breezy-security main restricted
deb http://security.ubuntu.com/ubuntu breezy-security universe
# MISE A JOUR
deb http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
# BACKPORTS
deb http://archive.ubuntu.com/ubuntu breezy-backports main universe multiverse restricted
deb http://ubuntu-backports.mirrormax.net/ breezy-backports-staging main universe multiverse restricted
deb http://ubuntu-backports.mirrormax.net/ breezy-extras main universe multiverse restricted
deb http://ubuntu-backports.mirrormax.net/ breezy-extras-staging main universe multiverse restricted
# UNIVERSE / MULTIVERSE
deb http://fr.archive.ubuntu.com/ubuntu/ breezy universe
deb http://fr.archive.ubuntu.com/ubuntu/ breezy multiverse
# PLF
deb ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/plf/ breezy free non-free
deb-src ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/plf/ breezy free non-free
Je ne vois pas comment me sortir de cette situation, d'autant plus que ;
michel@ubuntu-pc2:~$ sudo dpkg --configure -a
Paramétrage de w32codecs (20050412+breezy0.0.1) ...
--20:45:41-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
=> `windows-all-20050412.zip'
Résolution de www1.mplayerhq.hu... 192.190.173.45
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion terminée par expiration du délai d'attente) de l'en-tête.
Nouvel essai.
--21:01:23-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai: 2) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion ré-initialisée par le correspondant) de l'en-tête.
Nouvel essai.
--21:06:17-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai: 3) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion terminée par expiration du délai d'attente) de l'en-tête.
Nouvel essai.
--21:21:20-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai: 4) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion ré-initialisée par le correspondant) de l'en-tête.
Nouvel essai.
--21:25:54-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai: 5) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion terminée par expiration du délai d'attente) de l'en-tête.
Nouvel essai.
--21:40:59-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai: 6) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion ré-initialisée par le correspondant) de l'en-tête.
Nouvel essai.
--21:45:28-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai: 7) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion ré-initialisée par le correspondant) de l'en-tête.
Nouvel essai.
--21:49:56-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai: 8) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion ré-initialisée par le correspondant) de l'en-tête.
Nouvel essai.
--21:54:24-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai: 9) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion ré-initialisée par le correspondant) de l'en-tête.
Nouvel essai.
--22:00:26-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai:10) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion ré-initialisée par le correspondant) de l'en-tête.
Nouvel essai.
--22:04:55-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai:11) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion terminée par expiration du délai d'attente) de l'en-tête.
Nouvel essai.
--22:20:26-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai:12) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion terminée par expiration du délai d'attente) de l'en-tête.
Nouvel essai.
--22:35:39-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai:13) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion ré-initialisée par le correspondant) de l'en-tête.
Nouvel essai.
--22:40:17-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai:14) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse...
impossible de débloquer.... :(:(
Des que j'essaie d'utiliser apt-get j'ai ce msg:
E: dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem.
A+
Dernière modification par michel2652 (Le 13/11/2005, à 23:53)
bishop
Re : (pas résolu, mais...) mise à jour depuis dépots plf
Je ne sais pas... essaie:
Commente tes dépôts:
# PLF
#deb ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/plf/ breezy free non-free
#deb-src ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/plf/ breezy free non-free
et copie les nouveaux:
## FTP mirror from http://free.fr (french ISP)
deb ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/plf/ breezy free non-free
deb-src ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/plf/ breezy free non-free
Redémarre ton système, choisis le mode Rescue (ou je ne sais plus quoi "le second mode")
et quand tu as le prompt:
$ sudo dpkg-reconfigure synaptic
ou
# dpkg-reconfigure synaptic
si le prompt est root
à tout hasard, ça ne coûte rien d' essayer.
Dernière modification par bishop (Le 14/11/2005, à 00:16)
Hors ligne
michel2652
Re : (pas résolu, mais...) mise à jour depuis dépots plf
Bon ben, j'ai essayé la manip, bishop, mais sans résultat
Ce n'est pas très grave, je venais juste de faire l'install sur ce Pc, je réinstallerai demain après-midi.
Mais c'est dommage, j'aurai aimé comprendre ce qui c'est passé
Allez, j'en ai assez pour ce soir
Merci
:):):rolleyes:
A+
bishop
Re : (pas résolu, mais...) mise à jour depuis dépots plf
Patiente un peu avant de réinstaller, ce problème n' est pas bien grave...je crois.
Attend des réponses de membres plus compétents que je ne le suis.
Fais une recherche sur ce site, tu n' es pas le premier à connaître ce problème.
Et puis tu devrais essayer la commande que te renvoie le message:
E: dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem.
c' est à dire: $ sudo dpkg --configure -a
Dernière modification par bishop (Le 14/11/2005, à 02:41)
Hors ligne
michel2652
Re : (pas résolu, mais...) mise à jour depuis dépots plf
J'ai de suite fait la commande
E: dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem.
voir plus haut
Je ne vois pas comment me sortir de cette situation, d'autant plus que ;
Code:
michel@ubuntu-pc2:~$ sudo dpkg --configure -a
Paramétrage de w32codecs (20050412+breezy0.0.1) ...
--20:45:41-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
=> `windows-all-20050412.zip'
Résolution de www1.mplayerhq.hu... 192.190.173.45
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion terminée par expiration du délai d'attente) de l'en-tête.
Nouvel essai.
--21:01:23-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai: 2) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion ré-initialisée par le correspondant) de l'en-tête.
Nouvel essai.
--21:06:17-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai: 3) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion terminée par expiration du délai d'attente) de l'en-tête.
Nouvel essai.
--21:21:20-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai: 4) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion ré-initialisée par le correspondant) de l'en-tête.
Nouvel essai.
--21:25:54-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai: 5) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion terminée par expiration du délai d'attente) de l'en-tête.
Nouvel essai.
--21:40:59-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai: 6) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion ré-initialisée par le correspondant) de l'en-tête.
Nouvel essai.
--21:45:28-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai: 7) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion ré-initialisée par le correspondant) de l'en-tête.
Nouvel essai.
--21:49:56-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai: 8) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion ré-initialisée par le correspondant) de l'en-tête.
Nouvel essai.
--21:54:24-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai: 9) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion ré-initialisée par le correspondant) de l'en-tête.
Nouvel essai.
--22:00:26-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai:10) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion ré-initialisée par le correspondant) de l'en-tête.
Nouvel essai.
--22:04:55-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai:11) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion terminée par expiration du délai d'attente) de l'en-tête.
Nouvel essai.
--22:20:26-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai:12) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion terminée par expiration du délai d'attente) de l'en-tête.
Nouvel essai.
--22:35:39-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai:13) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse... ERREUR de lecture (Connexion ré-initialisée par le correspondant) de l'en-tête.
Nouvel essai.
--22:40:17-- http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
(essai:14) => `windows-all-20050412.zip'
Connecting to www1.mplayerhq.hu|192.190.173.45|:80... connecté.
requête HTTP transmise, en attente de la réponse...
impossible de débloquer....
J'avais vu passer 1 post avec le même sujet, impossible de le retrouver.
Lorsque je dis ce n'est pas très grave, c'est que j'ai fait l'install avec le CD, et au lancement, au lieu de lancer les mises è jour proposées, j'ai modifié mon sources list avec les PLF et Backports (ceux du moment car les adresses de ces dépots venaient de changer), et j'ai installé les; " image 686 smp", numlockx, divers gstream, divers codecs dont w32codecs, et patatrac....
D'habitude je suis prudent avec les backports, je les décommentes en cas de besoin. Là, ils étaient décommentés
Je pars bosser....
Je viens de retrouver ce fameux post,
http://forum.ubuntu-fr.org/viewtopic.php?id=15211
on dirait que c'est un problème de disponibilité du site
A+
Dernière modification par michel2652 (Le 14/11/2005, à 06:52)
michel2652
Re : (pas résolu, mais...) mise à jour depuis dépots plf
Re Bonjour,
J'ai regardé tous les posts(je crois...) relatant le même problème sur le forum, lu le man dpkg et cherché dans le wiki, fait un tour sur Debian.org, Lea et Linuxfr.org, et je n'ai rien trouvé qui me permette d'avancer.
Je patiente un peu avant d'agir à la WInDzzz, au cas ou quelqu'un aurait la soluce dan sl'après-midi.
A+
mr_pouit
Re : (pas résolu, mais...) mise à jour depuis dépots plf
Re Bonjour,
J'ai regardé tous les posts(je crois...) relatant le même problème sur le forum, lu le man dpkg et cherché dans le wiki, fait un tour sur Debian.org, Lea et Linuxfr.org, et je n'ai rien trouvé qui me permette d'avancer.
Je patiente un peu avant d'agir à la WInDzzz, au cas ou quelqu'un aurait la soluce dan sl'après-midi.
A+
pas besoin de tout réinstaller
normalement, le paquet décompressé est disponible dans /var/lib/dpkg/w32-codecs/ (c'est peut-être pas le chemin exact, mais en gros c'est ça)
Dans ce dossier, tu cherches le fichier qui s'appelle postinst (pour post installation ). Tu l'édites, et tu remplaces www1.blabla par www2.blabla, tu enregistres, tu relances sudo dpkg --configure -a, et normalement ça devrait marcher.
ou sinon, essaie de télécharger http://www2.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip et de le mettre dans /tmp, et normalement dpkg devrait le trouver tout seul
Dernière modification par mr_pouit (Le 14/11/2005, à 14:40)
Hors ligne
michel2652
Re : (pas résolu, mais...) mise à jour depuis dépots plf
Arghhhh....:lol::lol::mad::mad:
1/2 heure d'avance sur ta réponse, mr pouic...
normalement, le paquet décompressé est disponible dans /var/lib/dpkg/w32-codecs/
(c'est peut-être pas le chemin exact, mais en gros c'est ça)
Dans ce dossier, tu cherches le fichier qui s'appelle postinst (pour post installation lol ).
Tu l'édites, et tu remplaces www1.blabla par www2.blabla, tu enregistres,
tu relances sudo dpkg --configure -a, et normalement ça devrait marcher.
Je ne le trouvais pas ce w32codecs, (je ne savais pas pour "postinst") c'est ca le problème, j'ai fait une recherche par Raccourcis--->Recherche de Fichiers et à la main, nada...
ou sinon, essaie de télécharger http://www2.mplayerhq.hu/MPlayer/releas … 050412.zip
et de le mettre dans /tmp, et normalement dpkg devrait le trouver tout seul
Et ça, j'ai fait aussi, mais dpkg --configure -a connectait quand même à
http://www1.mplayerhq.hu/MPlayer/releases/codecs/windows-all-20050412.zip
Merci du coup de main, mais c'est réinstallé (mon home est sur un autre disk que /boot, /, swap) .
Allez, A+:(:(:):D:D:D
Un petit Pas résolu, mais...
Dernière modification par michel2652 (Le 14/11/2005, à 15:12)
mr_pouit
Re : (pas résolu, mais...) mise à jour depuis dépots plf
Arghhhh....:lol::lol::mad::mad:
1/2 heure d'avance sur ta réponse, mr pouic...
normalement, le paquet décompressé est disponible dans /var/lib/dpkg/w32-codecs/
(c'est peut-être pas le chemin exact, mais en gros c'est ça)
Dans ce dossier, tu cherches le fichier qui s'appelle postinst (pour post installation lol ).
Tu l'édites, et tu remplaces www1.blabla par www2.blabla, tu enregistres,
tu relances sudo dpkg --configure -a, et normalement ça devrait marcher.
Je ne le trouvais pas ce w32codecs, (je ne savais pas pour "postinst") c'est ca le problème, j'ai fait une recherche par Raccourcis--->Recherche de Fichiers et à la main, nada...
Allez, A+:(:(:):D:D:D
Un petit Pas résolu, mais...
tant pis
pour le w32-codecs, il semblerait qu'en fait ce soit /var/lib/dpkg/info/w32codecs.postint en fait
Hors ligne
michel2652
Re : (pas résolu, mais...) mise à jour depuis dépots plf
pour le w32-codecs, il semblerait qu'en fait ce soit /var/lib/dpkg/info/w32codecs.postint en fait lol
Tant pis, mais merci pour tout à vous tous : coink, bishop, mr_pouit et les autres
A+
PS : Vraiment SUPER ce Forum, je m'en rends compte tous les jours. C'est par l'entraide qu'on progresse, merci à tous.
|
Is it possible to create Windows executable files for Python and C/C++ code within the Eclipse workbench? If yes, then how can this be done?
Not sure I understand what you're asking as you're mixing Python/C++ in your question...
If you want to embed Python in some library, Google for 'embed python in c++'
If you just want to package Python to run Python code with extension modules, search for py2exe or cx-Freeze (personally, I like cx-Freeze better).
I don't think any of this is PyDev/Eclipse dependent (this should be IDE agnostic).
In addition to Fabio's answer:
In terms of C/C++, if you compile it on windows, eclipse does create yourprog.exe file automaticaly in order to be executed (in case if you have your main function written in C/C++). Look for your executable in bin folder of your project.
In terms of compiler: I use Cygwin. It simulates Linux environment. It contains (not by default though) g++ compiler, which, because of cygwin, compiles it in binary that can be launched in Windows (i.e. .exe file). I am not sure exactly about whether Linux binary is then converted to Windows binary or it is directly compiled for windows, but I know that this .exe file alone works if you run it.
Let me know if you need help installing Cygwin.
This is how I create .exe files from eclipse, in windows. Is not within the eclipse workbench but it might help you. To avoid problems, I would recommend to download everything for 32 bit even if you use 64 bit computer.
Install python 2.6
Install Eclipse
Install py2exe
In eclipse go to Help > Install new software and install pydev plugin from http://pydev.org/updates/
In windows preferences point the python interpreter to the location of your python.exe in your computer (C:/Python26)
you might need to add py2exe to the libraries
create a python module called setup.py with a code similar to this one:
from distutils.core import setup
import py2exe
setup(windows=['H:/yourworkspace/YourPythonProject/src/yourprogram.py'])
open windows console and type python H:/yourworkspace/YourPythonProject/src/setup.py py2exe
this will create a .exe located in C:/Python26/dist folder. It should work if you double click it but you cannot take it to a computer without python or any of the libraries that you´ve used. To do that, you can use Inno Setup.
It's very easy to use, basically it will ask for the location of the .exe, the dlls and folders that you want to add (I don't know about this so I add most of the things inside my C:/Python26/dist and it works). Inno setup will create an script and generate a .exe that you can install in any computer. You might need to edit the [Icons] part of the script, I had problems with that before to add an icon to the application.
That should hopefully work,
good luck.
|
`class MyWidget(Widget):`
Your root widget is MyWidget which inherits from a Widget and not from one of the layouts and therefore does not control the size of it's children As mentioned here, "The size_hint is a tupple of values used by layouts to manage the size of their children".
Your root widget does take up the entire space of the window. You can test this by adding a Rectangle to the canvas of MyWidget like so ::
with self.canvas.before:
Color(1,0,0,1)
Rectangle(pos=self.pos, size=self.size)
You should get familiar with canvas, canvas.before and canvas.after. They are basically groups of instructions, the before group is drawn before the canvas instructions of the widget and after group after.
One key thing different in Kivy though is that widget's sizing/layout is delayed till next frame, so if you just add the above snippet to your code like so::
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy.graphics import *
class MyWidget(Widget):
def __init__(self, **kwargs):
# I'd make sure to pass of kwargs through to the super
# as there are widgets's that process their initial
# arguments through.
super(MyWidget, self).__init__(**kwargs)
grid_layout = GridLayout(cols=3)
grid_layout.add_widget(Button(text='A'))
grid_layout.add_widget(Button(text='B'))
grid_layout.add_widget(Label(text='text'))
grid_layout.add_widget(Label(text='other'))
grid_layout.add_widget(Button(text='text'))
self.add_widget(grid_layout)
with self.canvas.before:
Color(1,0,0,1)
Rectangle(pos=self.pos, size=self.size)
class MyApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
MyApp().run()
This would only display a red rectangle at the initial position and size of your widget, which at the time would be it's default pos and size a.k.a (0, 0) and (100, 100) respectively.
To make the red rect adhere to the size of the widget we should bind it's size to the size of the widget, like so::
...
grid_layout.add_widget(Button(text='text'))
self.add_widget(grid_layout)
with self.canvas.before:
Color(1,0,0,1)
self.rect = Rectangle(pos=self.pos, size=self.size)
self.bind(size=self.update_rect)
def update_rect(self, instance, value):
self.rect.pos = self.pos
self.rect.size = self.size
class MyApp(App):
def build(self):
...
As the output of the above code above will show, your widget is taking up the size of the entire window. However, this doesn't solve your issue and the child layout still remains at it's original pos & of it's original size. This is cause widgets don't control the size of their children as stated above.
You have two choices here, either update the size & pos of your widget's child/children like you update rect(would quickly get complicated with multiple children) or use one of the Layouts as your root widget.
This could also be done in kv like so::
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
Builder.load_string('''
# this is the rule for MyWidget that defines
# what MyWidget looks like i.e.drawing
# instructions and widgets etc
<MyWidget>:
canvas.before:
Color:
rgba: 1, 0, 0, 1
Rectangle:
# this implicitly binds the size of the
# rect to the size of the widget
size: self.size
# self here still refers to the widget as Rectangle is only a
# graphics instruction and not a widget
pos: self.pos
GridLayout:
cols: 3
# root here refers to the `MyWidget`, bind the size of the
# GridLayout to the size of your root widget
size: root.size
Button:
text: 'A'
Button:
text: 'B'
Label:
text: 'text'
Label:
text: 'other'
Button:
text: 'text'
''')
class MyWidget(Widget):
pass
class MyApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
MyApp().run()
The example above binds the size of the child to the size of it's parent widget. I'd still recommend using a layout as your root widget, and don't be hesitant of nesting layouts.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.