text
stringlengths 256
65.5k
|
|---|
I have an array like the following:
people = [{'node': 'john', 'dist': 3},
{'node': 'mary', 'dist': 5},
{'node': 'alex', 'dist': 4}]
I want to compute the minimum of all the 'dist' keys. For instance, in the above example, the answer would be 3.
I wrote the following code:
min = 99999
for e in people:
if e[dist] < min:
min = e[dist]
print "minimum is " + str(min)
I am wondering if there is a better way to accomplish this task.
|
I am trying to create a piece of code in Python 3 which allows the user to choose between several options. I have tried this several ways but none of them seem the right method to do so.
Example Attempt:
usr_input = input("Input: ")
while (usr_input != '1') | (usr_input != '2'):
if usr_input == '1':
search()
elif usr_input == '2':
sys.exit()
The problem with this is that the script hangs after entering an incorrect command.
Can anyone give me the correct way to do this?
|
jduv
pb mises à jour
Bonjour à tous,
je débarque sous Kubuntu et même sous linux aprés un trés rapide passage chez mandriva.
Donc j'ai installé Kubuntu depuis un cd télécharger en Juillet.
L'installation semble s'être déroulée correctement au niveau matériel (dual boot avec Win XP pro) pas de soucis sauf un.
Aprés le démarrage sous kubuntu un icone me prévient que 87 mises à jour sont disponibles donc je tente et la 1 sur 2 me répond échec et donc ne s'installe pas.
J'ai donc essayé de taper
sudo apt-get upgrade
que j'ai trouver sur ce forum ce qui me renvoi :
E: Dépendances manquantes. Essayez d'utiliser l'option -f.
ce que je fait et qui retourne toute une série d'erreurs puis
E: Impossible de récupérer quelques archives, peut-être devrez-vous lancer apt-get update
ce que je fait mais je n'ai apparement pas les droits nécessaires
E: Impossible d'ouvrir le fichier verrou /var/lib/apt/lists/lock - open (13 Permission non accordée)
E: Impossible de verrouiller le répertoire de liste
il faut surement être root mais je n'ai encore jamais donné de mot de passe pour root ??. donc je ne saurais pas quoi répondre si je fait un su root
Je ne sais pas vraiment si je suis clair, j'ai peut être raté une étape d'install ou alors mes ressources de paquetages sont fausses (ci dessous le contenue de mon sources.list)
Que faut il que je fasse ? pour corriger cela
Merci d'avance
deb http://fr.archive.ubuntu.com/ubuntu/ dapper main restricted
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 http://fr.archive.ubuntu.com/ubuntu/ dapper universe
# 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 univer
Ubuntu studio 10.10 64 bits
Config assemblage perso : Tour ATX / carte mère : MSI790GX-G65 / Proc : AMD phenom II / RAM : 4 Go corsair DDR3 / Carte graphique : Nvidia 9500 GT / Ecran : IIYAMA Prolite E2710HDS / Clavier : Logitech K300 / Souris : Trust MI-7760Cp / Webcam : Logitech C905 / Enceintes : Altec Lansing MX5021
Hors ligne
Gounlaf
Re : pb mises à jour
le mot de pass pour le mod root est celui que tu utilise pour te connecter (enfin, si tu es le seul utilisateur de ton ordinateur)
E: Impossible d'ouvrir le fichier verrou /var/lib/apt/lists/lock - open (13 Permission non accordée)
E: Impossible de verrouiller le répertoire de liste
Ca, c'est surement que tu a le Gestionnaire de Paquet synaptic qui est lancé quand tu essaye la commande.
-- Gounlaf - c3x : Intégration html & css - Portfolio de Gounlaf --
Hors ligne
ZiOns
Re : pb mises à jour
Salut
+1 pour les réponses de Gounlaf :
sudo est une commande qui donne à ton utilisateur les droits root (su root n'existe pas sous Ubuntu, cf ici)
pour ton erreur ça peut être aussi le gestionnaire de mise à jour qui est ouvert (en clair entre synaptic, apt-get et le gestionnaire de mise-à-jour il ne peut y en avoir qu'un de lancé à la fois).
Ton sources.list me semble bon : si tu n'as rien installé de plus tu n'as besoin que de ces dépôts. Essaie d'enlever les "fr." dans ton sources.list puis
sudo apt-get update
sudo apt-get upgrade
Ou, via synaptic : Recharger > Tout mettre à jour
Dernière modification par ZiOns (Le 16/08/2006, à 16:21)
Hors ligne
jduv
Re : pb mises à jour
Ok et merci pour vos réponses
J'ai enlevé les fr. de mon sources.list
Mais lorsque j'utilise adept manager pour installer un logiciel (Gimp par exemple) j'ai toujours un certain nombre de téléchargement qui n'aboutissent pas et donc l'installation n'est pas compléte.
Me manque t'il des dépôts ??
GNU nano 1.3.10 Fichier : /etc/apt/sources.list
deb http://archive.ubuntu.com/ubuntu/ dapper main restricted
deb-src http://archive.ubuntu.com/ubuntu/ dapper main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://archive.ubuntu.com/ubuntu/ dapper-updates main restricted
deb-src http://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 http://fr.archive.ubuntu.com/ubuntu/ dapper universe
# 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
Ubuntu studio 10.10 64 bits
Config assemblage perso : Tour ATX / carte mère : MSI790GX-G65 / Proc : AMD phenom II / RAM : 4 Go corsair DDR3 / Carte graphique : Nvidia 9500 GT / Ecran : IIYAMA Prolite E2710HDS / Clavier : Logitech K300 / Souris : Trust MI-7760Cp / Webcam : Logitech C905 / Enceintes : Altec Lansing MX5021
Hors ligne
jduv
Re : pb mises à jour
Ok
aprés que l'install de gimp via adept échouée j'ai fait un apt-get -f upgrade qui à récupéré les dépendances manquantes et à première vue Gimp semble maintenant installé (à vérifier)
Que ce passe t'il pourquoi via adept cela ne marche pas directement ?:|
Merci
Ubuntu studio 10.10 64 bits
Config assemblage perso : Tour ATX / carte mère : MSI790GX-G65 / Proc : AMD phenom II / RAM : 4 Go corsair DDR3 / Carte graphique : Nvidia 9500 GT / Ecran : IIYAMA Prolite E2710HDS / Clavier : Logitech K300 / Souris : Trust MI-7760Cp / Webcam : Logitech C905 / Enceintes : Altec Lansing MX5021
Hors ligne
ecologeek
Re : pb mises à jour
utilise synaptic plus rustique mais plus efficace, et il t'explique les problèmes si tu affiches le terminal
Hors ligne
Mornagest
Re : pb mises à jour
Tu n'as pas décommenté les dépôts universe et multiverse, or c'est eux qui contiennent les paquets pour les applications non-basiques (comme Gimp par exemple, je pense).
Retire les # des lignes qui commencent par deb (celles avec deb-src c'est pour avoir les sources, pour la compilation-programmation, à toi de voir si ça te branche ) et relance sudo apt-get update
Hors ligne
jduv
Re : pb mises à jour
Ok merci pour vos réponses
Ubuntu studio 10.10 64 bits
Config assemblage perso : Tour ATX / carte mère : MSI790GX-G65 / Proc : AMD phenom II / RAM : 4 Go corsair DDR3 / Carte graphique : Nvidia 9500 GT / Ecran : IIYAMA Prolite E2710HDS / Clavier : Logitech K300 / Souris : Trust MI-7760Cp / Webcam : Logitech C905 / Enceintes : Altec Lansing MX5021
Hors ligne
|
I have an app that has two models in it. The first is called scenario. The second is called solutions. There is a M2M between scenarios and solutions. You can have any number of solutions belonging to scenarios and visa versa. Pretty straightforward.
The trick is, everything is filtered on the user. So I don't want to see the solutions or scenarios that other's have when I'm working.
I've written a view that is a CreateView. It adds a filtered list of solutions to the context. Once it's in the context, I loop it in the template to get the id. I add that to the form.
The problem I'm having is in the form_valid method.
How do I add the selected items to the save, so that they are added to the scenario?
Here's my view:
class ScenarioCreate(CreateView):
success_url = reverse_lazy('scenario_list')
template_name = "gps/create_scenario_form.html"
model = Scenario
form_class = ScenarioCreateForm
def get_context_data(self, **kwargs):
context = super(ScenarioCreate, self).get_context_data(**kwargs)
context['solution_list'] = Solution.objects.filter(user=self.request.user)
return context
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.solutions = form.cleaned_data['solutions'] # <= what goes here?
self.object.save()
form.save_m2m()
return HttpResponseRedirect(self.get_success_url())
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(ScenarioCreate, self).dispatch(*args, **kwargs)
I had assumed that cleaned_data would magically solve my set issue.
I have two questions.
How do I get that save to work?
Am I think about adding to the context correctly, or is there a better way?
All help appreciated.
UPDATE: Adding ScenarioCreateForm
class ScenarioCreateForm(ModelForm):
class Meta:
model = Scenario
exclude = ('user', 'created')
|
Wireless access is all the rage. Wireless this, wireless that. Hot spots are turning up everywhere. Many are free. Many have absolutely no security. There are several in my neighborhood. I have no idea who is running them, but at least one is wide open.
This article will show you one method for locking down your wireless network so that nobody but you can use it. This approach will take you beyond WEP and MAC address filtering, both of which are a good start but have known exploits. This article expands upon the IPsec foundation and demonstrates an easy method for securing your Wireless Access Point (WAP).
I will be using FreeBSD 4.10-Stable for this excursion. Please keep your hands and legs within the vehicle at all times. In case of emergency, please follow the directions of your crew. They know what to do.
While writing this article, I have assumed the following:
Related Reading
Wireless is practically wide open for anyone with a laptop, a wireless card, and the appropriate set of tools. WEP is defeatable. MAC addresses are sniffable and spoofable. In short, you need the next level: IPsec.
If wireless is so risky, why use it?
Convenience.
Wireless is convenient. There are no cables to run. Anyone can pop down to the local Future Shop, buy a wireless access point, plug it in, turn it on, and start surfing the 802.11 information superhighway. Does this sound familiar? It should. I did it and I wrote about it. I did the right thing. I filtered by MAC address. I turned on WEP. Then I turned off WEP when I had trouble. Yes, I was vulnerable, but no one compromised my system ... as far as I know.
Since writing that article nearly 18 months ago, I have moved to a new house. I've gone through the same process I did last time, setting up a new rack and running some cables through the walls. This time I convinced myself that I would set up a secure wireless network. It took me a few hours, but I finally figured it out.
To answer the original question of this section and to tie it in with my recent move, I use wireless so I don't have to run cables. I want to use the laptop in the living room, the dining room, or on the front step. (I'm actually typing this into my Windows XP workstation sitting at my desk in the basement, SSH'd into the new Antec box.) As I work wirelessly, I want to keep people off my private network and keep prying eyes away from my communications. I can do that with IPsec.
Also in my mind is my neighbor, I don't know who, but somebody running a WAP nearby, totally unsecured. I know how easy it would be for me to use that internet connection. I don't want someone using mine.
IPsec is short for IP security. It is a set of protocols for securely exchanging packets at the IP layer. VPNs frequently use it. We can use the same approach to secure our wireless network.
IPsec uses shared secrets to encrypt data. It also uses security policies to decide what types of traffic to encrypt between which hosts.
This section outlines some of the details that are specific to IPsec on FreeBSD. Regardless of the operating system you wish to use, you will need an IPsec-enabled kernel. On FreeBSD, add the following directives to your kernel configuration file, and then compile a new kernel:
options IPSEC #IP security
options IPSEC_ESP #IP security (crypto; define w/ IPSEC)
options IPSEC_DEBUG #debug for IP security
I haven't actually used the features of IPSEC_DEBUG, but it's there if I need it.
Note: If you are running 5.x, use FAST_IPSEC instead of the directives mentioned above. Also remove INET6, as FAST_IPSEC does not support it.
Add the following directive to /etc/rc.conf to set up your IPsec database at boot time:
ipsec_enable="YES"
That directive will load your IPsec configuration directives from /etc/ipsec.conf. (You can configure the actual filename using ipsec_file="/your/file/here". I will give you examples for that file later in this article.)
I'm a big believer in starting small and working one's way toward a goal. For my testing, I first tried IPsec over my wired network, then moved it over to the wireless network. You may find this strategy useful too. It allows you to concentrate on the IPsec portion of the problem, make it work, and then concern yourself with any wireless issues. After you have IPsec running properly, you can remove the wire and start using 802.11 instead.
For this testing, I created a new gateway and put two NICs into the box. This box does NAT (Network Address Translation) using ipnat and will use ipf as a firewall. It's easier to manage with the entire wireless network in a separate subnet. If necessary, I can disconnect the entire subnet by unplugging a single cable or powering off the WAP.
Your NAT box will want to do some forwarding of packets. I recommend the use of ipf and ipnat. I also use ipmon. I have these entries in /etc/rc.conf:
gateway_enable="YES" ipfilter_enable="YES" ipnat_enable="YES ipmon_enable="YES"
Firewall and NAT rules are beyond the scope of this article, but those two links should give you a running start.
IPsec can create a point-to-point tunnel between two hosts. Being encrypted, the data will be safe from prying eyes, and the gateway won't accept modified packets, since they lack an authentic signature. IPsec can also secure traffic between two networks or a network and a gateway. Other configuration options are available, but I will concentrate on just network, not point to point.
The key point to realize is that IPsec cannot exist on its own. You need to have IPsec at both ends of the communication. You cannot just slap IPsec onto your laptop and expect it to work wherever you go. This is why I have decided to create a wireless gateway through which all my wireless traffic will flow.
The following diagram (created with Xfig) illustrates my wireless network. My laptop sits at 10.0.0.10 and communicates over wireless (802.11) to my WAP. The WAP connects to a dedicated gateway box (via a hub) which sits between the WAP and my LAN.
Figure 1. Wireless network
Any traffic coming in over the wireless network must pass through the WAP and then the wireless gateway. This gateway has two NICs (one at 10.0.0.1, the other at 192.168.0.55). These are conventional, wired NICS. There is no Wifi in this gateway, but there certainly could be. I have chosen to use a WAP instead. The WAP plugs into a hub, and 10.0.0.1 on the gateway plugs into the same HUB. The other NIC plugs into the main LAN.
IPsec uses a database to decide how to treat traffic. The database contains the rules on what traffic to encrypt and how to encrypt it. The two main types of rules are policy and association. The Security Policy Database (SPD) determines what traffic IPsec should handle. The Security Association Database (SAD) specifies how to encrypt that traffic.
The main tool for manipulating the database is setkey(8). I will show you one way to use that tool later. Usually, you place these rules in /etc/ipsec.conf.
These rules cause the encryption of all traffic between the network (10.0.0.0/24) and the gateway (10.0.0.1). We will use ESP (Encapsulating Security Payload) as found in RFC 2406. This ensures that nobody can read your data.
add 10.0.0.1 10.0.0.10 esp 691 -E rijndael-cbc "1234567890123456";
add 10.0.0.10 10.0.0.1 esp 693 -E rijndael-cbc "1234567890123456";
spdadd 10.0.0.0/24 0.0.0.0/0 any -P out ipsec esp/tunnel/10.0.0.10-10.0.0.1/require;
spdadd 0.0.0.0/0 10.0.0.0/24 any -P in ipsec esp/tunnel/10.0.0.1-10.0.0.10/require;
The first two rules (add) are SAD entries. The next two rules (spdadd) are SPD entries.
The add items set up the encryption keys for communication between the two computers. Be sure to use different keys; however, if you use IKE you won't need keys. The values shown are just to keep things easy. The spdadd items set up the actual tunnel between the two computers. In brief, the above directives mean:
10.0.0.1 and 10.0.0.10, use the index 691, the encryption algorithm known as rijndael-cbc, and use a shared secret of "1234567890123456".10.0.0.10 and 10.0.0.1, use the index 693, the same encryption algorithm, and the same shared secret.10.0.0.0/24) and everywhere else (0.0.0.0) must go (require) through a tunnel.0.0.0.0) and the network (10.0.0.0/24) must come (require) from a tunnel.
The rules for the gateway are very similar to the laptop rules and also are slightly symmetric.
add 10.0.0.1 10.0.0.10 esp 691 -E rijndael-cbc "1234567890123456";
add 10.0.0.10 10.0.0.1 esp 693 -E rijndael-cbc "1234567890123456";
spdadd 10.0.0.0/24 0.0.0.0/0 any -P in ipsec esp/tunnel/10.0.0.10-10.0.0.1/require;
spdadd 0.0.0.0/0 10.0.0.0/24 any -P out ipsec esp/tunnel/10.0.0.1-10.0.0.10/require;
You can add these rules manually using setkey -c and then copy and paste the rules from above (after making adjustments so they refer to your IP addresses, not mine). To exit, press Ctrl-D. When testing, I actually keep it running and copy and paste the commands directly. I use these commands to clear out existing database entries before adding new ones.
flush;
spdflush;
The flush command clears out the SAD entries, while spdflush clears out the SPD entries.
In the policy statements (spdadd), the second line above states that all traffic from 10.0.0.0/24 to anywhere requires ESP. The fourth line states that all traffic from anywhere to 10.0.0.0/24 also requires ESP. Combined, these two directives ensure that all traffic from anywhere to anywhere on this network must use ESP.
While I tested these rules, I kept them on a local web site. That made it easier to copy and paste the rules from the browser. I'm not suggesting that you publicly publish your rules. This is just a debugging tool. Mind you, the only parts you need to keep secret are the keys (in my example, 1234567890123456).
If you place your rules in /etc/ipsec.conf and have ipsec_enable="YES" in your /etc/rc.conf, the system will load them at boot-up.
When loading the rules, you'll need to coordinate them. I sat at the gateway console with my laptop beside me. That way, if I messed up the rules, I could reset them without moving. The provided rules worked for me. They should work for you too. If they don't, go back to square one and verify your rules. Ensure that the subnet and the IP addresses are what they should be.
After you implement these rules, the gateway will reject all non-ESP traffic. Furthermore, anyone attempting to communicate with the gateway must have the shared secrets. If you change the secret, nothing will pass the gateway.
By this point, you have IPsec on both machines and you have set the IPsec database rules. Traffic is flowing. Now you want to confirm the encapsulation, so nothing should appear in plain text. Here is how I did that.
On my wireless gateway, the dc0 device has an IP address of 10.0.0.1. All traffic from the laptop will come in on that NIC. I issued this command to view that traffic:
# tcpdump -ni dc0 not esp tcpdump: listening on dc0 13:40:25.651640 0.0.0.0.68 > 255.255.255.255.67: xid:0xebd53d39 [|bootp] [tos 0x10] 13:40:25.656090 10.0.0.1.67 > 10.0.0.10.68: xid:0xebd53d39 Y:10.0.0.10 S:10.0.0.1 [|bootp] [tos 0x10]
The above shows dhclient starting on the laptop. A bit of ARP traffic follows. If all you see via tcpdump is stuff like this, then you're good to go.
13:42:18.225304 arp who-has 10.0.0.1 tell 10.0.0.10
13:42:18.225450 arp reply 10.0.0.1 is-at 0:32:91:32:91:32
If all you see is arp, then you're good to go.
You should see what the IPsec traffic looks like. Have a look. Shorten the above command to this:
# tcpdump -ni dc0
tcpdump: listening on dc0
13:44:34.371866 10.0.0.10 > 10.0.0.1: ESP(spi=0x000002b5,seq=0xfe)
13:44:34.385237 10.0.0.1 > 10.0.0.10: ESP(spi=0x000002b3,seq=0xec)
(frag 368:1480@0+)
13:44:34.385339 10.0.0.1 > 10.0.0.10: esp (frag 368:48@1480)
13:44:34.387672 10.0.0.1 > 10.0.0.10: ESP(spi=0x000002b3,seq=0xed)
(frag 369:1480@0+)
13:44:34.387775 10.0.0.1 > 10.0.0.10: esp (frag 369:48@1480)
13:44:34.390066 10.0.0.1 > 10.0.0.10: ESP(spi=0x000002b3,seq=0xee)
(frag 370:1480@0+)
13:44:34.390165 10.0.0.1 > 10.0.0.10: esp (frag 370:48@1480)
13:44:34.390996 10.0.0.1 > 10.0.0.10: ESP(spi=0x000002b3,seq=0xef)
13:44:34.393155 10.0.0.1 > 10.0.0.10: ESP(spi=0x000002b3,seq=0xf0)
(frag 372:1480@0+)
13:44:34.393260 10.0.0.1 > 10.0.0.10: esp (frag 372:48@1480)
13:44:34.394641 10.0.0.10 > 10.0.0.1: ESP(spi=0x000002b5,seq=0xff)
13:44:34.396986 10.0.0.10 > 10.0.0.1: ESP(spi=0x000002b5,seq=0x100)
13:44:34.398044 10.0.0.1 > 10.0.0.10: ESP(spi=0x000002b3,seq=0xf1)
(frag 373:1480@0+)
13:44:34.398142 10.0.0.1 > 10.0.0.10: esp (frag 373:48@1480)
The above tcpdump is of HTTP traffic as my laptop accessed my development copy of FreshPorts.
Here is how a ping looks:
13:45:39.886113 10.0.0.10 > 10.0.0.1: ESP(spi=0x000002b5,seq=0x118)
13:45:39.887436 10.0.0.1 > 10.0.0.10: ESP(spi=0x000002b3,seq=0x10a)
13:45:40.898972 10.0.0.10 > 10.0.0.1: ESP(spi=0x000002b5,seq=0x119)
13:45:40.900134 10.0.0.1 > 10.0.0.10: ESP(spi=0x000002b3,seq=0x10b)
13:45:41.908735 10.0.0.10 > 10.0.0.1: ESP(spi=0x000002b5,seq=0x11a)
13:45:41.909912 10.0.0.1 > 10.0.0.10: ESP(spi=0x000002b3,seq=0x10c)
Note: this is all ESP. The following is an example of traffic that does not use IPsec:
$ sudo tcpdump -ni fxp1
tcpdump: listening on fxp1
13:47:39.130953 192.168.0.21.22 > 192.168.0.99.3077: P 903783889:903783933(44)
ack 4184487194 win 58400 (DF) [tos 0x10]
13:47:39.151794 192.168.0.99.1763 > 66.197.0.145.6665: . ack 305831024 win 64160 (DF)
13:47:39.252127 192.168.0.99.3077 > 192.168.0.21.22: . ack 44 win 64028 (DF)
13:47:39.621526 192.168.0.18 > 203.118.144.45: icmp: echo request
There you go. All good. Nothing passes through the gateway unless it matches the rules. The shared secret is the key to this security. This would be more secure if the secret changed occasionally, though.
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.
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.
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.
To install the dhcp server, I did this:
# cd /usr/ports/net/isc-dhcp3-server
# make install clean
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 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.
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.
Copyright © 2009 O'Reilly Media, Inc.
|
when I use
from django.contrib.gis.db import models
I get error:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
from django.contrib.gis.db import models
File "C:\Python27\lib\site-packages\django\contrib\gis\db\models\__init__.py"
, line 2, in <module>
from django.db.models import *
File "C:\Python27\lib\site-packages\django\db\__init__.py", line 11, in <module>
if DEFAULT_DB_ALIAS not in settings.DATABASES:
File "C:\Python27\lib\site-packages\django\utils\functional.py", line 184,
in inner
self._setup()
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 40,
in _setup
raise ImportError("Settings cannot be imported, because environment
variable %s
is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable
DJANGO_SETTINGS_MODULE is undefined.
how to fix it??
When use
from django.db import models
the django work without problems
|
I'm implementing basic sorting algorithms to learn them, and coding, better. Criticisms and possible optimizations welcome.
import unittest
import random
def merge_sort(seq):
"""Accepts a mutable sequence. Utilizes merge_sort to sort in place, return
a sorted sequence"""
if len(seq) == 1:
return seq
else:
#recursion: break sequence down into chunks of 1
mid = len(seq)/2
left = merge_sort(seq[:mid])
right = merge_sort(seq[mid:])
i, j, k = 0, 0, 0 #i= left counter, j= right counter, k= master counter
#run until left or right is out
while i < len(left) and j < len(right):
#if current left val is < current right val; assign to master list
if left[i] < right[j]:
seq[k] = left[i]
i += 1; k += 1
#else assign right to master
else:
seq[k] = right[j]
j += 1; k += 1
#handle remaining items in remaining list
remaining = left if i < j else right
r = i if remaining == left else j
while r < len(remaining):
seq[k] = remaining[r]
r += 1; k += 1
return seq
class test_mergesort(unittest.TestCase):
def test_mergesort(self):
test = [random.randrange(0, 10000) for _ in range(2000)]
self.assertEqual(merge_sort(test), sorted(test))
if __name__ == '__main__':
unittest.main()
|
You could include the conditional inside the XPath itself, and tell the XPath to select the "PhoneNum" attribute, so that phoneNodeList only contains the interesting values (multiline to prevent horizontal scrolling):
xPath = "/Record/Case/CaseFormsLoad/PartyLoad/Party/PartyPhones/Phone" & _
"[@ConfidentialFlag=""True""]/@PhoneNum"
I would avoid the string concatenations by populating an array with the attribute values:
Dim values(1 To phoneNodeList.Length)
For i = 1 To phoneNodeList.Length
values(i) = phoneNodeList(i).Text
Next
And then ReturnData can be assigned like this:
ReturnData = Join(values, VbCrLf)
This eliminates the trailing newline, and separates getting the data from outputting the result.
Resulting code:
ReturnData = ""
Dim xPath
xPath = "/Record/Case/CaseFormsLoad/PartyLoad/Party/PartyPhones/Phone[@ConfidentialFlag=""True""]/@PhoneNum"
Dim phoneNodeList
Set phoneNodeList = XmlDoc.SelectNodes(xPath)
If phoneNodeList.Length = 0 Then Exit Function 'Sub?
Dim values(1 To phoneNodeList.Length)
For i = 1 To phoneNodeList.Length
values(i) = phoneNodeList(i).Text
Next
ReturnData = Join(values, VbCrLf)
EDIT
If the above cannot be factored into its own function, and must not Exit, then you can revert the condition and wrap the remainder in the If block:
If phoneNodeList.Length > 0 Then
Dim values(1 To phoneNodeList.Length)
For i = 1 To phoneNodeList.Length
values(i) = phoneNodeList(i).Text
Next
ReturnData = Join(values, VbCrLf)
End If
|
But normal python logging is still swallowed. Print-statements are visible, but logger.warn('...') is not.
I use this logging set up in my library which I want to use from twisted:
import logging
logger=logging.getLogger(os.path.basename(sys.argv[0]))
class Foo:
def foo(self):
logger.warn('...')
I don't want to change my library to use twisted logging, since the library is already used in a lot of projects which don't use twisted.
If I google for this problem, I only find solutions which pipe the twisted logs in to the python logging.
How can I view see the logging of my library (without changing it)?
|
I tried to use sqlaclhemy joined table inheritance and had a strange occurrence.
class CommonObject(Base):
__tablename__ = "objects"
id = Column("objid", Integer, primary_key=True)
objname = Column(String(32))
...
class GoodsPlacement(Container, Loadable, Dumpable):
__tablename__ = "goods_placements"
id = Column("objid", Integer, ForeignKey("containers.objid"), primary_key=True)
...
class Departure(CommonObject):
__tablename__ = "departures"
id = Column(Integer, ForeignKey("objects.objid"), primary_key=True)
content_id = Column(Integer, ForeignKey("goods_placements.objid"))
content = relationship("GoodsPlacement",
primaryjoin="Departure.content_id==GoodsPlacement.id",
foreign_keys=[content_id],
lazy='joined',
backref="departures")
...
When I write query:
session.query(GoodsPlacement).filter(~GoodsPlacement.departures.any(Departure.status_id < 2))
it generates me something like this:
SELECT
objects.objid AS objects_objid,
goods_placements.objid AS goods_placements_objid,
objects.objname AS objects_objname
FROM objects
JOIN goods_placements ON objects.objid = goods_placements.objid
WHERE NOT (EXISTS (
SELECT 1
FROM (
SELECT
objects.objid AS objects_objid,
objects.objname AS objects_objname,
departures.id AS departures_id,
departures.content_id AS departures_content_id,
departures.status_id AS departures_status_id
FROM objects
JOIN departures ON objects.objid = departures.id)
AS anon_1, objects
WHERE anon_1.departures_content_id = objects.objid
AND anon_1.departures_status_id < :status_id_1)
)
And this doesn't work because objects in exist clause overrides outer objects. As workaround I used exists from sqlexpression directly,
session.query(GoodsPlacement).filter(~exists([1],
and_("departures.status_id<2",
"departures.content_id=goods_placements.objid"),
from_obj="departures"))
but it strongly depends from column and table names.
How I can specify alias for object table in exists statement?
Debian wheezy, python-2.7.3rc2, sqlaclhemy 0.7.7-1
|
I would like to show how I would do to pass an input to the HTML. I usually use python to send request to the page where I need to input the data. Before doing that you need to know if you need to supply web-cookies or not, if yes, copy the cookie, if you need to be logged in otherwise not, just check that. Once that is done, you need to know the field names for the input area as you will be using them to POST or GET data using your script. Here is sample usage.
import urllib
import urllib2
import string
headers = {'Cookie': 'You cookies if you need'}
values = {'form_name':'sample text', 'submit':''}
data = urllib.urlencode(values)
req = urllib2.Request('website where you making request to',data,headers)
opener1 = urllib2.build_opener()
page1=opener1.open(req)
#OPTIONAL
htmlfile=page1.read()
fout = open('MYHTMLFILE.html', "wb")
fout.write(htmlfile)
fout.close()
|
The inspect module might help you. Here's some code from a plugin manager class I wrote that might serve as an example.
def load_plugin_file(self, pathname):
'''Return plugin classes in a plugin file.'''
name, ext = os.path.splitext(os.path.basename(pathname))
f = file(pathname, 'r')
module = imp.load_module(name, f, pathname,
('.py', 'r', imp.PY_SOURCE))
f.close()
plugins = []
for dummy, member in inspect.getmembers(module, inspect.isclass):
if issubclass(member, Plugin):
p = member(*self.plugin_arguments,
**self.plugin_keyword_arguments)
if self.compatible_version(p.required_application_version):
plugins.append(p)
return plugins
The other way to do it might be to use the builtin functions globals, issubclass, and isinstance.
|
I tried debugging this on my own, but to no avail. Here's the problem -
I have a MacBook Pro 13" OS X 10.7.3 with Python 2.7 (no other version installed)
I recently installed MAMP from their website. It's a good way to test out site building. But today, when I tried installing a python package using easy_install, it just doesn't accept the request. Here's the error -
nitin:~ nitinthewiz$ easy_install virtualenv
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 553, in <module>
main()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 535, in main
known_paths = addusersitepackages(known_paths)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 268, in addusersitepackages
user_site = getusersitepackages()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 243, in getusersitepackages
user_base = getuserbase() # this will also set USER_BASE
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py", line 233, in getuserbase
USER_BASE = get_config_var('userbase')
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.py", line 535, in get_config_var
return get_config_vars().get(name)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.py", line 434, in get_config_vars
_init_posix(_CONFIG_VARS)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.py", line 287, in _init_posix
raise IOError(msg)
IOError: invalid Python installation: unable to open /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config/Makefile (No such file or directory)
I checked out the folder at /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config/ and guess what, it's Empty!
The reason I mentioned MAMP in the beginning was because I realized that MAMP has it's own python 2.6 installation within itself and I thought maybe it's interfering with my python 2.7. But it seems that's now the case because when I type python into the terminal, it refers to my python 2.7 as you can see from the path above.
Can anyone help? I was hoping to begin playing around with python after a long time today but this error is making me go crazy! Also, I play around with a lot of things in python and have a lot of packages installed. I have not been able to find a command to list all the packages installed under easy_install.
Can anyone help with either of my problems??
|
Le Viking
Miro refuse de se lancer :-(
Salut à tous,
Je rencontre un pb avec Miro, logiciel qui a par ailleurs l'air alléchant. Je l'ai installé via Synaptic, en rajoutant la ligne "ad hoc" dans les dépà´ts et l'icà´ne apparaà®t bien dans mon menu d'applications, mais rien ne se passe quand j'essaie de le lancer.
J'ai fait un sudo miro dans un terminal, et ça donne ça :
/usr/lib/firefox
Traceback (most recent call last):
File "/usr/bin/miro.real", line 24, in <module>
import gtcache
File "/var/lib/python-support/python2.5/miro/gtcache.py", line 22, in <module>
import config
File "/var/lib/python-support/python2.5/miro/config.py", line 25, in <module>
import eventloop
File "/var/lib/python-support/python2.5/miro/eventloop.py", line 320, in <module>
_eventLoop = EventLoop()
File "/var/lib/python-support/python2.5/miro/eventloop.py", line 211, in __init__
self.wakeSender, self.wakeReceiver = util.makeDummySocketPair()
File "/var/lib/python-support/python2.5/miro/util.py", line 332, in makeDummySocketPair
dummy_server.bind( ('127.0.0.1', 0) )
File "<string>", line 1, in bind
socket.error: (99, 'Cannot assign requested address')
Y 'a manifestement un pb, mais je ne comprends pas lequel... Des idées ? Merci !
Emmanuel
Hors ligne
buntuking
Re : Miro refuse de se lancer :-(
Bonjour;
Tu viens de me rappeler ce logiciel !:D
Pour installer Miro , il y a deux problème !
1- Miro version "1" gutsy sur le site http://www.getmiro.com
dépendance libpango 1.18.3 alors qu'il y a seulement la version libpango 1.18.2 sur Gutsy
Donc abandonner cette version !
2- Via Synaptic Miro version 0.9.8.1
Marche très bien mais il y a un bug java à réparer comme ceci :
Bug java :( /usr/bin/python2.5: symbol lookup error: /usr/lib/jvm/java-6-sun-1.6.0.03/jre/plugin/i386/ns7/libjavaplugin_oji.so: undefined symbol: PR_NewMonitor )
-Désinstaller complètement Miro via synatic
-Enlever tout dépà´t se réfèrent à "miro" dans la source.list
-Supprimer le fichier caché ".miro" du dossier utilisateur
puis installer icedtea-java7-plugin via synatic
Puis faire :
sudo update-alternatives --config java
On vous demande de choisir entre 3 alternatives :
-----------------------------------------------
Il y a 3 alternatives fournissant « java ».
Sélection Alternative
-----------------------------------------------
1 /usr/bin/gij-4.2
2 /usr/lib/jvm/java-6-sun/jre/bin/java
*+ 3 /usr/lib/jvm/java-7-icedtea/jre/bin/java
Appuyez sur Entrée pour conserver la valeur par défaut[*] ou choisissez le numéro sélectionné :
------------------------------------------
choisir 3
Maintenant vous pouvez installer miro version 0.9.8.1 via synaptic
Fin !
Taper sur la console : miro et çà fonctionne bien
buntuking
Re : Miro refuse de se lancer :-(
Autre chose :
Miro ne dépend pas de VLC pour lire les vidéos mais de libxine !
Il faut pas oublier d'installer le paquet libxine1-ffmpeg
Le Viking
Re : Miro refuse de se lancer :-(
Salut Buntuking, t'es vraiment un roi ;-)
J'ai pas le temps de mettre en oeuvre tout de suite la manip que tu m'indiques (because pause déjeuner rapide), mais je m'y colle dès ce soir, yesss !
Un grand merci !
Emmanuel
Hors ligne
jouclar
Re : Miro refuse de se lancer :-(
ça marche pour moi
Merci buntuking
Le Viking n'oublie pas de mettre RESOLU pour les autres
Ubuntu 9.04
Hors ligne
Le Viking
Re : Miro refuse de se lancer :-(
Ben mince... Finalement, pour moi, ça marche pas ! J'ai toujours le même message d'erreur. Je comprends plus là :-(
Emmanuel
Hors ligne
buntuking
Re : Miro refuse de se lancer :-(
A essayer sur console :
sudo ifconfig lo up
puis miro
laurentb
Re : Miro refuse de se lancer :-(
Salut,
j'ai miro 1.0 depuis le dépôt officiel miro, sous Gutsy Studio 7.10 32 bits.
Aucun soucis dans les mises à jour, le fonctionnement et l'installation.
Laurent, équipe lprod.org
Laurent Bellegarde, professeur de SVT, 64 Bayonne, France
GNU/Linux a l'ecole : www.abuledu.org
lprod.org, Montage audio et vidéo libre
Lugs : www.euskalug.org, www.abul.org
Hors ligne
buntuking
Re : Miro refuse de se lancer :-(
j'ai miro 1.0 depuis le dépà´t officiel miro, sous Gutsy Studio 7.10 32 bits.
Aucun soucis dans les mises à jour, le fonctionnement et l'installation.
Salut
Peux-tu me donner ta version du paquet libpango , en regardant avec synaptic ?
Parce que moi cela coince avec la version 1 pourtant j'ai le fichier sources.list d'origine , je n'ai jamais rien ajouté !
dépendance libpango supérieur ou égale à 1.18.3
voici le fichier "control" du paquet Package: miro
Version: 1.0-2
Architecture: i386
Maintainer: Will Guaraldi <will.guaraldi@pculture.org>
Installed-Size: 3180
Depends: libatk1.0-0 (>= 1.13.2), libboost-python1.34.1, libc6 (>= 2.6-1), libcairo2 (>= 1.4.0), libfontconfig1 (>= 2.4.0), libgcc1 (>= 1:4.2.1), libglib2.0-0 (>= 2.14.0), libgtk2.0-0 (>= 2.12.0), libnspr4-0d (>= 1.8.0.10), libpango1.0-0 (>= 1.18.3), libstdc++6 (>= 4.2.1), libx11-6, libxcomposite1 (>= 1:0.3-1), libxcursor1 (>> 1.1.2), libxdamage1 (>= 1:1.1), libxext6, libxfixes3 (>= 1:4.0.1), libxi6, libxine1 (>= 1.1.4), libxinerama1, libxrandr2 (>= 2:1.2.0), libxrender1, python2.5, python (>= 2.5), python (<< 2.6), python-support (>= 0.3.4), python-gtk2, python-gnome2, python-gnome2-extras (>= 2.14.0-2), python-glade2, miro-data (>= 1.0), imagemagick, libxine1-plugins
Epy
Re : Miro refuse de se lancer :-(
Nickel ça fonctionne !
Merci buntuking!
Hors ligne
t0b0z
Re : Miro refuse de se lancer :-(
J'ai bien installé icedtea-java7-plugin et j'ai bien exécuté la commande "sudo ifconfig lo up", malgré tout j'ai toujours la même erreur aka "Bug java" (miro 0.9.8.1)...
Je suis sous Ubuntu 7.10.
Merci d'avance pour votre aide, je voudrais vraiment faire fonctionner ce logiciel...
christophe.67, essaye ça ça devrait passer je pense:
1) vérifie que tu as bien installé java-7-icedtea, si c'est le cas la commande suivante devrait te le lister de cette façon:
$ sudo update-java-alternatives -l
java-6-sun 63 /usr/lib/jvm/java-6-sun
java-7-icedtea 1060 /usr/lib/jvm/java-7-icedtea
2) Si c'est la cas, active cette version:
sudo update-java-alternatives --set java-7-icedtea
Voilou, en espérant que ça puisse t'aider.
++ la communauté : D
pfrenk
Re : Miro refuse de se lancer :-(
pour moi, la manip avec icedtea-java7-plugin a bien marché (merci Buntuking), c'est-a-dire
que miro accepte de se lancer. Par contre, il est inutilisable:
le son est parfait, mais la vidéo me donne 1 image toutes les 5 secondes,
même pour une vidéo sur mon disque dur !! (sur un Compaq n800v) et de plus
la souris devient aussi inutilisable (mouvement du pointeur décalé de + de 10 secondes)
Avec vlc, c'est parfait.
qui aurait une idée ?
2ème pb: avec quel dépot obtient-on la version 1.0 ?
après avoir trouvé des adresses farfelues via google, j'ai essayé:
deb http://ubuntu.osuosl.org/ubuntu gutsy main universe multiverse
qui semble correct (au moins, "apt-get update" marche)
mais synaptic continue à me proposer la version 0.9.8.1
Hors ligne
squal38
Re : Miro refuse de se lancer :-(
Bonjour,
j'ai suivi toutes les manips ci-dessus mais j'ai toujours le message:
/usr/bin/python2.5: symbol lookup error: /usr/lib/j2se/1.4/jre/plugin/i386/mozilla/libjavaplugin_oji.so: undefined symbol: PR_NewMonitor
quand je tente d'utiliser la version fournie via synaptic sans ajouter de dépot...
Miro se lance puis plante au bout de quelques secondes
Quelqu'un à une autre suggestion ?
Hors ligne
Epy
Re : Miro refuse de se lancer :-(
Tu as fait la manip qui est indiquée plus haut ? Ca ressemble au meme problème de Java
(J'ai moi aussi installé miro depuis les dépots normaux)
Hors ligne
squal38
Re : Miro refuse de se lancer :-(
Oui, j'ai installer la version icedtea de java, j'ai fait le "java-update-alternative" mais rien n'y fait.
En fait, je ne comprend pas bien le lien avec Mozilla : quand je lance Miro dans une console, la première chose qui apparait c'est "/usr/lib/firefox" et vue l'erreur qu'il m'affiche, il semble qu'il va chercher java dans un répertoire Mozilla. Je ne sais pas si il y a un lien...
Hors ligne
Epy
Re : Miro refuse de se lancer :-(
Il utilise le moteur de Firefox pour sa page d'accueil si je ne me trompe pas (le message en cas d'absence de réseau est le même que celui de Firefox)
C'est en le lançant depuis la ligne de commandes (miro) que tu as ce message d'erreur?
Hors ligne
squal38
Re : Miro refuse de se lancer :-(
oui, sinon pas de message, il se ferme tout simplement
Hors ligne
papillon41
Re : Miro refuse de se lancer :-(
Bonjour,
Même problème :
/usr/bin/python2.5: symbol lookup error: /usr/lib/jvm/java-6-sun-1.6.0.03/jre/plugin/i386/ns7/libjavaplugin_oji.so: undefined symbol: PR_NewMonitor
WARNING downloader: connection closed -- quitting
INFO Shutting down downloaders...
Même remède : Installation de "icedtea-java7-plugin" avec "Synaptic" puis :
sudo update-java-alternatives --set java-7-icedtea
Alors : guéri
Hors ligne
squal38
Re : Miro refuse de se lancer :-(
Il faut que j'essaie à nouveau mais la dernière fois ça ne fonctionnait toujours pas...
Hors ligne
squal38
Re : Miro refuse de se lancer :-(
J'ai réessayé mais ça ne fonctionne toujours pas... En plus, la dernière version de miro pose un problème de dépendance avec libxine1...
Du coup, je vais attendre la prochaine mise à jour ;-)
Hors ligne
greg42
Re : Miro refuse de se lancer :-(
Lorsque je veux installer miro, j'ai le message suivant dans Synaptic:
miro:
Dépend : libxine1 (<1.1.8) mais 1.1.10-1~gutsy1 doit être installé
alors que j'ai installé les paquets libxine 1.1.10-1 ...
Je suis content de voir que je ne suis pas le seul à avoir ce bug.
apparemment, il n'y a pas de solution immédiate, il faut attendre la mise à jour, alors ?
armons-nous de patience, donc.
A plus
Hors ligne
|
Download
FREE PDF
The NetBeans Platform is a generic framework for commercial and open-source desktop Swing applications.
It provides the “plumbing” (such as the code for managing windows, connecting actions to menu items, and updating applications at runtime) that you would otherwise need to write yourself. The NetBeans Platform provides all of these out of the box on top of a reliable, flexible, and well tested modular architecture.
In this refcard, you are introduced to the key concerns of the NetBeans Platform, so that you can save years of work when developing robust and extensible applications.
To get started with the NetBeans Platform:
Tool How to Get Started
NetBeans IDE Download the “Java SE” distribution of NetBeans IDE (which is the smallest NetBeans IDE distribution providing the NetBeans Platform Toolkit, consisting of NetBeans Platform templates and samples) via either the Ant or Maven build systems.
Command-line Maven Use the Maven archetypes for NetBeans Platform development. GroupId: org.codehaus.mojo.archetypes ArtifactId: netbeans-platform-app-archetype nbm-archetype
Command-line Ant Download the NetBeans Platform ZIP file, which includes a build harness. The build harness includes a long list of Ant targets for compiling, running, testing, and packaging NetBeans Platform applications.
Other IDEs Use command-line Maven to set up a Maven-based NetBeans Platform application and then open the POM file into any IDE that supports Maven, e.g., IntelliJ IDEA or Eclipse.
The following are the main features of the NetBeans Platform, showing you the benefits of using it rather than your homegrown Swing framework.
Tool How to Get Started
Module System Since your application can use either standard NetBeans Platform modules or OSGi bundles, you’ll be able to integrate third-party modules or develop your own. The modular nature of a NetBeans Platform application gives you the power to meet complex requirements by combining several small, simple, and easily tested modules. Powerful versioning support helps give you confidence that your modules will work together, while strict control over the public APIs your modules expose will help you create a more flexible application that’s easier to maintain.
Lifecycle Management Just as application servers such as GlassFish provide lifecycle services to Web applications, the NetBeans runtime container provides lifecycle services to Swing applications. Application servers understand how to compose Web modules, EJB modules, and so on, into a single Web application, just as the NetBeans runtime container understands how to compose NetBeans modules into a single Swing application.
End users of the application benefit from pluggable applications because these enable them to install modules into their running applications. NetBeans modules can be installed, uninstalled, activated, and deactivated at runtime, thanks to the runtime container. End users of the application benefit because they are able to install modules into their running applications via an update center, since NetBeans modules can be installed, uninstalled, activated, and deactivated at runtime.
Service Infrastructure The NetBeans Platform provides an infrastructure for registering and retrieving service implementations, enabling you to minimize direct dependencies between individual modules and enabling a loosely coupled architecture (high cohesion and low coupling).
File System Unified API providing stream-oriented access to flat and hierarchical structures, such as disk-based files on local or remote servers, memory-based files, and even XML documents.
Window System Most serious applications need more than one window. Coding good interaction between multiple windows is not a trivial task. The NetBeans window system lets you maximize/minimize, dock/undock, and drag-and-drop windows, without you providing any code at all.
Standardized UI Toolkit Swing is the standard UI toolkit and is the basis of all NetBeans Platform applications. Related benefits include the ability to change the look and feel easily, the portability of Swing across all operating systems, and the easy incorporation of many free and commercial third-party Swing components.
Generic Presentation Layer With the NetBeans Platform, you're not constrained by one of the typical pain points in Swing: the JTree model is completely different from the JList model, even though they present the same data. Switching between them means rewriting the model. The NetBeans Nodes API provides a generic model for presenting your data. The NetBeans Explorer & Property Sheet API provides several advanced Swing components for displaying nodes.
Advanced Swing Components In addition to a window system, the NetBeans Platform provides many other UI-related components, such as a property sheet, a palette, complex Swing components for presenting data, a Plugin Manager, and an Output window.
JavaHelp Integration The JavaHelp API is an integral part of the NetBeans Platform. You can create help sets in each of your modules, and the NetBeans Platform will automatically resolve them into a single helpset. You can also bind help topics to UI components to create a contextsensitive help system for your application.
The NetBeans Platform consists of a large set of modules. You do not need all of them. In fact, you only need six. None of these six provide any UI at all, meaning that you can create server or console applications on the NetBeans Platform since UI is not mandatory in any way at all.
Complete list of NetBeans Platform modules:
Module Description
boot.jar
core.jar
org-openide-filesystems.jar
org-openide-modules.jar
org-openide-util.jar
org-openide-util-lookup.jar
Provides the runtime container, consisting of the startup sequence, the module system, the filesystem, the service infrastructure, and utility classes.
org-netbeans-core.jar
org-netbeans-core-ui.jar
(Optional) Provides the basic UI components provided by the NetBeans Platform, together with related infrastructure.
org-netbeans-core-netigso.jar
org-netbeans-core-osgi.jar
org-netbeans-libs-felix.jar
org-netbeans-libs-osgi.jar
(Optional) Provides integration with the OSGi containers Felix and Equinox.
org-netbeans-core-output2.jar
org-openide-io.jar
org-netbeans-core-io-ui.jar
(Optional) Provides an Output window for displaying processing messages. It also exposes an API that you can use to write to the window and change text colors.
org-netbeans-core-multiview.jar
(Optional) Provides a framework for multitab windows, such as used by the Matisse GUI Builder in NetBeans IDE.
org-openide-windows.jar
org-netbeans-core-windows.jar
(Optional) Provides the API for accessing the window system.
org-netbeans-modules-autoupdateservices.
jar
org-netbeans-modules-autoupdate-ui.
jar
(Optional) Provides the Plugin Manager together with the functionality for accessing and processing update centers where NetBeans modules are stored.
org-netbeans-modules-favorites.jar
(Optional) Provides a customizable window, which can be used as a filechooser, enabling the user to select and open folders and files.
org-openide-actions.jar
(Optional) Provides a number of configurable system actions, such as “Cut”, “Copy”, and “Paste”.
org-openide-loaders.jar
(Optional) Provides the API for connecting data loaders to specific MIME types.
org-openide-nodes.jar
org-openide-explorer.jar
(Optional) Provides the API for modeling business objects and displaying them to the user.
org-netbeans-modules-javahelp.jar
(Optional) Provides the JavaHelp runtime library and enables JavaHelp sets from different modules to be merged into a single helpset.
org-netbeans-modules-editormimelookup.
jar
org-netbeans-modules-editormimelookup-
impl.jar
(Optional) Provides an API for discovery and creation of MIME-specific settings and services.
org-netbeans-modules-masterfs.jar
(Optional) Provides a central wrapper file system for your application.
org-netbeans-modules-options-api.jar
(Optional) Provides an Options window for user customizations and an API for extending it.
org-netbeans-api-progress.jar
org-netbeans-modules-progress-ui.jar
org-openide-execution.jar
org-netbeans-core-execution.jar
(Optional) Provides support for asynchronous long-running tasks and integration for long-running tasks with the NetBeans Platform’s progress bar.
org-netbeans-modules-queries.jar
(Optional) Provides an API for getting information about files and an SPI for creating your own queries.
org-netbeans-modules-sendopts.jar
(Optional) Provides an API and SPI for registering your own handlers for accessing the command line.
org-netbeans-modules-settings.jar
(Optional) Provides an API for saving module-specific settings in a user-defined format.
org-openide-awt.jar
(Optional) Provides many helper classes for displaying UI elements such as notifications.
org-openide-dialogs.jar
(Optional) Provides an API for displaying standard and customized dialogs.
org-openide-text.jar
(Optional) Provides an extension to the java.swing text API.
org-netbeans-api-visual.jar
(Optional) Provides a widget library for modeling and displaying visual representations of data.
org-netbeans-spi-quicksearch.jar
(Optional) Provides the infrastructure for integrating items into the Quick Search field.
org-netbeans-swing-plaf.jar
org-netbeans-swing-tabcontrol.jar
(Optional) Provides the look and feel and the display of tabs and a wrapper for the Swing Layout Extensions library.
The NetBeans Platform provides a large set of APIs. You do not need to know or use all of them, just those that make sense in your specific context. Below are the main API groupings, together with the most important information related to the grouping, such as their most important configuration attributes and API classes.
A module is a JAR file with special attributes in its manifest file. This is a typical NetBeans module manifest file:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.1
Created-By: 11.3-b02 (Sun Microsystems Inc.)
OpenIDE-Module-Public-Packages: -
OpenIDE-Module-Module-Dependencies: org.openide.util > 7.31.1.1
OpenIDE-Module-Java-Dependencies: Java > 1.5
OpenIDE-Module-Implementation-Version: 091216
AutoUpdate-Show-In-Client: true
OpenIDE-Module: org.demo.hello
OpenIDE-Module-Layer: org/demo/hello/layer.xml
OpenIDE-Module-Localizing-Bundle: org/demo/hello/Bundle.properties
OpenIDE-Module-Specification-Version: 1.0
OpenIDE-Module-Requires: org.openide.modules.ModuleFormat1
These are the most important NetBeans-related manifest attributes:
Attribute Defines
OpenIDE-Module Identifier of a module, provides a unique name. The only required entry in the manifest.
OpenIDE-Module-Public-Packages By default, all packages in a module are hidden from all other modules. Via this attribute, you expose packages to external modules.
OpenIDE-Module-Layer (Optional) Defines contributions to application’s virtual filesystem.
OpenIDE-Module-Friends (Optional) By default, all modules in the application can access all public packages. Via this attribute, you can limit access to public packages to specific modules.
OpenIDE-Module-Localizing-Bundle (Optional) Permits module display metadata to be localized.
OpenIDE-Module-Module-Dependencies
OpenIDE-Module-Java-Dependencies
(Optional) Modules can request general or specific versions of other modules, Java packages, or Java itself.
OpenIDE-Module-Provides
OpenIDE-Module-Requires
(Optional) Modules can specify dependencies without naming the exact module to depend on. A module may “provide” one or more “tokens”, strings in the format of a Java package or class name.
OpenIDE-Module-Specification-Version
OpenIDE-Module-Implementation-Version
(Optional) Modules can indicate two types pieces of versioning.
AutoUpdate-Show-In-Client (Optional) Whether the module is shown in the Plugin Manager.
The window system handles the display of JPanel-like components and integrates them with the NetBeans Platform. The main classes are listed below.
Type Description
TopComponent A JPanel that provides a new window in your application. The window comes with many features for free, i.e., without any coding, such as maximize/minimize and dock/undock.
Mode A container in which TopComponents are docked. You do not need to subclass this class to use it. Instead, it is configured in an XML file.
TopComponentGroup A group of windows, which should behave in concert. Windows within a group can be opened or closed together. As with Modes, these are defined in an XML file, not by subclassing TopComponentGroup.
WindowManager Controls all the windows, modes, and window groups. You can ask a WindowManager for its windows, modes, and groups. You can also use it as a JFrame and then set the title bar and anything else that you would do with JFrames.
A mode (that is, a window position) is defined in an XML file, which is contributed to the central registry via entries in the layer.xml file.
The NetBeans Platform provides a set of default modes, the most important of which are as follows:
Type Description
editor main area of application (not necessarily a text editor)
explorer left vertical area, e.g., for Projects window
properties right vertical area, e.g., for Properties window
navigator left lower vertical area, e.g., for Navigator window
output horizontal area at base of application
palette right vertical area, e.g., for items to drag onto a window
leftSlidingSide minimized state in left sidebar
rightSlidingSide minimized state in right sidebar
bottomSlidingSide minimized state in bottom status area
TopComponents are registered in the system as follows:
@TopComponent.Description(preferredID = “DemoTopComponent”,
iconBase=”SET/PATH/TO/ICON/HERE”,
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = “editor”, openAtStartup = true)
@TopComponent.OpenActionRegistration(displayName = “#CTL_DemoAction”,
preferredID = “DemoTopComponent”)
public final class DemoTopComponent extends TopComponent {
//
}
At compile time, the annotations above are converted to entries in a generated layer file, in the “build” folder.
How do I... Description
Find a specific
TopComponent?
WindowManager.getDefault().findTopComponent(“id”)
Find a specific mode?
WindowManager.getDefault().findMode(“id”)
Once you have found a mode, you can use
Find a specific TopComponent Group? WindowManager.getDefault().findTopComponentGroup(“id”)
Ensure that the application is fully started up? WindowManager.getDefault().invokeWhenUIReady(My Runnable())
Get the active TopComponent? WindowManager.getDefault().getRegistry().getActivated()
Get a set of opened TopComponents? WindowManager.getDefault().getRegistry(). getOpened()
Get the main frame of the application WindowManager.getDefault().getMainWindow()
For all the details, see: http://bits.netbeans.org/dev/javadoc/orgopenide- windows/org/openide/windows/doc-files/api.html
Lookup is a data structure for loosely coupled communication. It is similar to but more powerful than the ServiceLoader class in JDK 6 (for example, Lookup supports event notifications). This enables you to load objects into the context of your application, but also into the context of NetBeans UI components, such as windows and nodes. These are the most important Lookups to be aware of:
Type Description
Global lookup, provides selection management The Lookup that gives you access to the currently selected UI component, most commonly the focused Node.Lookup lkp = Utilities.actionsGlobalContext();
Local lookup, provides lookup
of NetBeans objects such as
TopComponents, Nodes, and
DataObjects.
The local context of a specific NetBeans Platform UI object.//For Windows:Lookup lkp = myTopComponent.getLookup();//For Nodes:Lookup lkp = myNode.getLookup();
Default lookup The application’s context, comparable to the JDK 6
ServiceLoader class, provided via the META-INF/services
folder.
Lookup lkp = Lookup.getDefault();
These are typical tasks related to Lookup and how to code them:
How do I... Description
Register a service? Annotate a service provider with the @ServiceProvider class annotation, at compile time the META-INF/services folder is created, registering the implementation.
Find the default service implementation?
MyServices = Lookup.getDefault().
lookup(MyService.class)
Find all service implementations?
Collection<? extends MyService> coll = Lookup.
getDefault().lookupAll(MyService.class)
Listen to changes in a Lookup?
Tip: Keep a reference to the result object, otherwise it will be garbage collected.
Lookup.Result lkpResult = theLookup.
lookupResult(MyObject.class);
lkpResult.addLookupListener(
new LookupListener() {
@Override
public void resultChanged(LookupEvent e)(
Result res = (Result) e.getSource();
Collection<? extends MyObject>
coll = res.allInstance();
//iterate through the collection
}
);
Create a Lookup for an object?
//Lookup for single object:
Lookup lkp = Lookups.singleton( myObject );
//Lookup for multiple objects:
Lookup lkp = Lookups.fixed(myObject, other);
//Lookup for dynamic content:
InstanceContent ic = new InstanceContent();
Lookup lkp = new AbstractLookup(ic);
ic.add(myObject);
Merge Lookups?
Lookup commonlkp = new ProxyLookup(
dataObjectLookup, nodeLookup,
dynamicLookup);
Provide a Lookup for my TopComponent?
//In the constructor of TopComponent:
associateLookup(myLookup);
Provide a Lookup for a subclass of Node?
new AbstractNode(myKids, myLookup);
new BeanNode(myDomainObj, myKids, myLookup);
new DataNode(myDataObject, myKids,
myLookup);
Provide a Lookup for any other component?
For all the details, see: http://wiki.netbeans.org/NetBeansDeveloperFAQ#Lookup</p>
The central registry is organized as a virtual file system accessible by all the modules in a NetBeans Platform application. NetBeans Platform APIs, such as the Window System API, make available extension points enabling you to declaratively register your components. A module’s contributions to the system are provided by specialized XML files, called “layer files”, normally named “layer.xml”.
Below are the most important extension points provided out of the box by the NetBeans APIs, represented by folders in a layer file:
Actions, Menu, Toolbars, OptionsDialog, Services, Shortcuts, TaskList,and Windows2.
The NetBeans Platform helps you to register items correctly in the file system by letting you annotate your classes instead of requiring you to manually type XML tags in the layer.xml file by hand. The current list of annotations (in the NetBeans Platform, as well as NetBeans IDE) are listed below:
@ActionID, @ActionReference, @ActionReferences, @ActionRegistration,@AntBasedProjectRegistration, @CompositeCategoryProvider.Registration,@ConvertAsJavaBean, @ConvertAsProperties, @EditorActionRegistration,@HelpSetRegistration, @LookupMerger.Registration,@LookupProvider.Registration, @MimeLocation, @MimeRegistration,@MimeRegistrations, @NbBundle.Messages, @NodeFactory.Registration,@OptionsPanelController.ContainerRegistration,@OptionsPanelController.SubRegistration,@OptionsPanelController.TopLevelRegistration,@ProjectServiceProvider, @ServiceProvider, @ServiceProviders,@ServicesTabNodeRegistration, @TopComponent.OpenActionRegistration,@TopComponent.Registration
The registry makes use of the FileSystem API to access the registered data.
The FileSystem API provides stream-oriented access to flat and hierarchical structures, such as disk-based files on local or remote servers, memory-based files, and even XML documents.
Items within the folders in the layer.xml file are not java.io.Files, but org.openide.filesystems.FileObjects. The differences between them are as follows:
java.io.File org.openide.filesystems.FileObject
Create with a constructor Get from the FileSystem.
Can represent something that doesn’t exist, such as new File(“some/place/that/doesnt/exist”) Represents something that already exists.
Cannot listen to changes FileChangeListener listens to changes to FileObject, as well as anything beneath the FileObject.
Represents a file on disk Not necessarily a file on disk, could be in a database, FTP server, virtual, or anywhere else.
No attributes Can have attributes, which are key-value pairs associated with a FileObject.
Converting between common data types:
How do I... Description
Get a java.io.File for a FileObject?
FileUtil.toFile(FileObject fo)
Get a FileObject for a File?
FileUtil.toFileObject(File f)
Get a DataObject for a FileObject?
DataObject.find (FileObject fo)
Get a FileObject for a DataObject?
theDataObject.getPrimaryFile()
Get a Node for a DataObject?
theDataObject.getNodeDelegate()
Get a DataObject for a Node?
DataObject dob = n.getLookup().lookup
(DataObject.class);
if (dob != null) {
//do something
}
Get a reference to the central registry?
//Get the root:
FileUtil.getConfigRoot()
//Get a specific folder:
FileUtil.getConfigFile(“path/to/my/
folder”)
The NetBeans Platform provides custom URLs:
jar For representing entries inside JARs and ZIPs, including the root directory entry.
nbres A resource loaded from a NetBeans module, e.g. nbres:/org/netbeans/modules/foo/resources/foo.dtd.
nbresloc Same, but transparently localized and branded according to the usual conventions, e.g. nbresloc:/org/netbeans/modules/foo/resources/foo.html loads the same as nbres:/org/netbeans/modules/foo/ resources/foo_nb_ ja.html.
nbinst Loads installation files using InstalledFileLocator in installation directories, e.g. nbinst:///modules/ext/some-lib.jar may load the same thing as file:/ opt/netbeans/ide/modules/ext/some-lib.jar.
For all the details, see: http://bits.netbeans.org/dev/javadoc/org-openide-filesystems
Actions are functions invoked when the user presses a menu item, toolbar button, or keyboard shortcut.
When porting your existing application to the NetBeans Platform, you do not need to change the code in your standard JDK actions (AbstractAction, ActionListener, etc).
Instead, you need to register them via class-level annotations which, when the module is compiled, will result in entries generated in the module’s layer file.
Below is shown how an action is registered:
@ActionID(category = “File”,
id = “org.demo.project.actions.DemoAction”)
@ActionRegistration(iconBase = “org/demo/resources/icon.png”,
displayName = “#CTL_DemoAction”)
@ActionReferences({
@ActionReference(path = “Menu/File”, position = 0),
@ActionReference(path = “Toolbars/File”, position = 0),
@ActionReference(path = “Shortcuts”, name = “D-SPACE”)
})
@Messages(“CTL_DemoAction=Demo”)
public final class DemoAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// TODO implement action body
}
}
The entries generated into the layer file from the annotation above are used by the NetBeans Platform to construct the application’s actions, menus, toolbars, and keyboard shortcuts.
For all the details, see: http://bits.netbeans.org/dev/javadoc/org-openide-awt
When needing to change a component in the menu bar or toolbar, extend AbstractAction and implement Presenter:
@ActionID(category = “Build”, id = “org.demo.module1.DemoAction”)
@ActionRegistration(iconBase = “org/demo/module1/icon.png”,
displayName = “#CTL_DemoAction”)
@ActionReferences({
@ActionReference(path = “Menu/File”, position = 0),
@ActionReference(path = “Toolbars/File”, position = 0),
@ActionReference(path = “Shortcuts”, name = “D-M”)
})
public final class DemoAction extends AbstractAction implements
Presenter.Toolbar
{
public void actionPerformed(ActionEvent e) {
// TODO implement action body
}
public Component getToolbarPresenter() {
// TODO define the component to be displayed
}
}
The Presenter class provides inner interfaces for creating customized presentation features for an Action. The following are available.
Interface Description
Presenter.Menu Present an Action in a menu.
Presenter.Popup Present an Action in a popup menu.
Presenter.Toolbar Present an Action in a toolbar.
A Node is a generic model for a business object, which it visualizes within an Explorer View. Each Node can have visual attributes, such as a display name, icon, properties, and actions.
The list of Nodes is below, which you can use as is or extend as needed:
Type Description
Node Base class for representing business objects to the user.
AbstractNode The usual base class you would use for your Node implementations.
DataNode Specialized Node class for wrapping a file and displaying it as a Node to the user.
BeanNode Specialized Node class that wraps a JavaBean and presents it to the user as a Node. It also provides simplistic access to property sheets.
FilterNode Specialized Node class that decorates an existing Node by adding/removing features to/from it.
For all the details, see: http://bits.netbeans.org/dev/javadoc/orgopenide- nodes/org/openide/nodes/doc-files/api.html
A Node is a container for its own child nodes, created via a children class.
Type Description
ChildFactory Factory for creating child Nodes. Optionally, these can be created asynchronously, that is, when the user expands the Node.
Children.Keys Older version of ChildFactory. You should be able to replace any implementation of Children.Keys with ChildFactory
Less Used: Children.Array, Children.Map, and Children.SortedArray.
Explorer views are Swing components that display Node hierarchies.
Type Description
BeanTreeView JTree for displaying Nodes.
OutlineView JTree for displaying nodes, with a JTable for displaying the related node properties.
PropertySheetView Property sheet displaying the properties of a node.
PropertyPanel A generic GUI component for displaying and editing a single JavaBeans property. Though not technically an explorer view, PropertyPanel is an associated API.
Less Used: IconView, ListView, ChoiceView, ContextTreeView, MenuView, and TableView.
For all the details, see: http://bits.netbeans.org/dev/javadoc/orgopenide- explorer/org/openide/explorer/doc-files/api.html
The NetBeans Platform provides default property editors for:
Boolean, Color, Dimension, Font, Insets, Integer, Point, Rectangle,File, Class, String, URL, Date, Properties, ListModel, and TableModel.
The Visual Library provides predefined widgets with predefined actions, layouts, and borders. The list of predefined widgets is as follows:
Type Description
Scene The root element of the hierarchy of displayed widgets.
LayerWidget A transparent surface, like a JGlassPane.
ComponentWidget A placeholder widget for AWT/Swing components.
ImageWidget An image as a widget.
LabelWidget A label as a widget.
IconNodeWidget An image and a label as a widget.
ConnectionWidget Connections between widgets, with anchors, control points, and end points.
ConvolveWidget Coil/twist effect, i.e., a convolve filter to a child element.
LevelOfDetailsWidget A container for widgets, with visibility and zoom features.
ScrollWidget/SwingScrollWidget A scrollable area, with/without JScrollBar as scroll bars.
SeparatorWidget A space with thickness and orientation.
For all the details, see: http://bits.netbeans.org/dev/javadoc/org-netbeans-api-visual
The NetBeans Dialogs API provides a number of standard dialogs for displaying standard messages for information, questions (such as “Are you sure?”, when saving), input, and error messages to the user.
Each dialog comes with a standard appearance, buttons, and icons.
Type Description
Information Dialog
NotifyDescriptor d = new NotifyDescriptor.
Message(“Text”);
Question Dialog
NotifyDescriptor d = new NotifyDescriptor.
Confirmation(“Title”, “Text”);
Input Dialog
’NotifyDescriptor d = new NotifyDescriptor.
InputLine(“Title”, “Text”);
Add the Dialogs API to your module and then use the table above to create dialogs as follows (in the example below, we display an information dialog):
NotifyDescriptor d = new NotifyDescriptor.Message(“Text”);
DialogDisplayer.getDefault().notify(d);
For all the details, see: http://bits.netbeans.org/dev/javadoc/org-openide-dialogs
Type Description
Displays URLs, opens browsers, distinguishes embedded vs. external browsers.
Lets you display messages in the status line.
Provides useful static methods for manipulation with images/icons, results are cached.
Performs asynchronous threads in a dedicated thread pool.
Lets you create new tabs in the Output window and write into them.
In addition to the NetBeans APIs, many UI components can be used as is, simply by including the related JAR (or JARs) in your application. Normally, they also provide an API for accessing and changing their default behavior.
Component Palette, Database Explorer, Debugger, Diff Viewer, Editors (Properties, Java, XML,HTML, SQL, and more), External Browser, File Browser (Favorites Window), JavaHelp Window,Navigator Window, Options Window, Output Window, Progress Bar, Properties Window,Plugin Manager, Project System, Quick Search Field, Task List, Terminal Window, UndoRedoManager, Validation System, and Versioning Systems (CVS, Subversion, Mercurial).
Everything in the NetBeans Platform can be customized to fit your specific business requirements. For example:
Icons, Look & Feel, Splash Screen, Strings (Menu Items, Title Bar, etc.)
Right-click an application in the Projects window, choose Branding, and use the Branding Editor.
The following are frequently asked questions:
FAQ Answers
What’s the difference between a ‘NetBeans Platform Application’ and a ‘Module Suite’? A “suite” project is a collection of modules that might be published for addition to an application, while an “application” project is a suite project intended to become a complete, standalone application by incorporating a base platform.
Why is my explorer view not synchronized with the Properties window? Because you have not exposed the Node, with its Properties, to the Lookup. For example, add this line to the TopComponent constructor: associateLookup(ExplorerUtils.createLookup(em, getActionMap());
I created a palette but it isn’t showing when I open the related TopComponent. Because your TopComponent is not registered in the ‘editor’ mode, where the palette is available.
Technical information on the NetBeans Platform is available on-line in many different forms. The most important of these are listed below:
Site URL
Homepage http://platform.netbeans.org
NetBeans API javadoc http://bits.netbeans.org/dev/javadoc/
Tutorials http://platform.netbeans.org/tutorials
Blogs http://planetnetbeans.org
FAQ http://wiki.netbeans.org/NetBeansDeveloperFAQ
Mailing List dev@platform.netbeans.org
Screencast http://platform.netbeans.org/tutorials/nbm-10-top-apis.html
Free Training for Universities http://edu.netbeans.org/courses/nbplatform-certified-training/
Commercial Training and Consulting http://www.eppleton.de
This Refcard could not have been made without the technical insights provided by the following: Tim Boudreau, Tim Dudgeon, Jeremy Faden, Laurent Forêt, Jesse Glick, Manikantan, Ernie Rael, Antonio Vieiro and Tom Wheeler.
|
When I submit an empty form with a
phone_typeselected (forformHomePhone) the form returns its self without a value selected inphone_typestipulatingThis field is required
As you can see from the view The first phone number in the form is required but the other phone numbers are not. I only want to process them if there is a value present. Though when I click submit on an empty form the additional phone number fields throw up an error from the
UKPhoneNumberField>Phone number must include an area code.How can I only validate when there is a number in the respected field?
I have a view.py file like this
def new_client_view(request):
if request.method == 'POST':
formDetails = ClientDetailsForm(request.POST)
formAddress = ClientAddressForm(request.POST)
formHomePhone = ClientPhoneForm(request.POST)
formWorkPhone = ClientOtherPhoneForm(request.POST)
formMobilePhone = ClientOtherPhoneForm(request.POST)
if formDetails.is_valid() and formAddress.is_valid() and formHomePhone.is_valid():
c = Client()
c.save()
fd = formDetails.save(commit=False)
fd.client = c
fd.created_by = request.user
fd.save()
fa = formAddress.save(commit=False)
fa.client = c
fa.created_by = request.user
fa.save()
fph = formHomePhone.save(commit=False)
fph.client = c
fph.created_by = request.user
fph.save()
if 'p2-number' in request.POST and request.POST['p2-number']:
fpw = formWorkPhone.save(commit=False)
fpw.client = c.id
fpw.created_by = request.user
if fpw.is_valid():
fpw.save()
if 'p3-number' in request.POST and request.POST['p3-number']:
fpm = formMobilePhone.save(commit=False)
fpm.client = c
fpm.created_by = request.user
if fpm.is_valid():
fpm.save()
return render_to_response('client/client.html', context_instance=RequestContext(request))
else:
return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))
else:
formAddress = ClientAddressForm()
formDetails = ClientDetailsForm()
formHomePhone = ClientPhoneForm(initial={'phone_type':'home'}, prefix="p1")
formWorkPhone = ClientPhoneForm(initial={'phone_type':'work'}, prefix="p2")
formMobilePhone = ClientPhoneForm(initial={'phone_type':'mobi'}, prefix="p3")
return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))
a forms.py like this:
class ClientDetailsForm(ModelForm):
class Meta:
model = ClientDetails
exclude = ('client', 'created', 'created_by')
class ClientAddressForm(ModelForm):
class Meta:
model = ClientAddress
exclude = ('client', 'created', 'created_by')
class ClientPhoneForm(ModelForm):
number = UKPhoneNumberField()
class Meta:
model = ClientPhone
exclude = ('client', 'created', 'created_by')
class ClientOtherPhoneForm(ModelForm):
number = UKPhoneNumberField(required=False)
class Meta:
model = ClientPhone
exclude = ('client', 'created', 'created_by')
and a models.py like this:
MARITAL_STATUS_CHOICES = (
...
)
NAME_TITLE_CHOICES = (
...
)
PHONE_CHOICES = (
('home', 'Home'),
('home2', 'Home 2'),
('mobi', 'Mobile'),
('mobi2', 'Mobile 2'),
('work', 'Work'),
('work2', 'Work 2'),
)
class Client(models.Model):
closed = models.DateTimeField(blank=True, null=True)
closed_by = models.ForeignKey(User, blank=True, null=True)
comment = models.TextField(blank=True, null=True)
def __unicode__(self):
return u'%s' % (self.id)
class ClientDetails(models.Model):
...
class ClientAddress(models.Model):
...
class ClientPhone(models.Model):
client = models.ForeignKey(Client, null=True)
created = models.DateTimeField(default=datetime.now)
created_by = models.ForeignKey(User, blank=True, null=True)
phone_type = models.CharField(max_length=5, choices=PHONE_CHOICES)
number = models.CharField(max_length=24)
BTW(my new_client_view function is not very DRY I know. Any recommendations would be gratefully received)
|
Hello everybody,
i am using Zenoss Core Version 3.2.0 and want to have a global search function for the interface descriptions. In the IRC Channel hackman238(i think he was Shane Scott) told me that his ZenPack Device Search does this job after a little modifcation.
I have to add "device.os.interfaces.interface.description" in line 30 in "%ZENHOME/ZenPacks/ZenPacks.ShaneScott.DeviceSearch-1.0.0-py2.6.egg/ZenPacks/ShaneScott/DeviceSearch/__init__.py"
But when i install the ZenPack as Zenoss User with the following command: "zenpack --install=ZenPacks.ShaneScott.DeviceSearch-1.0.0-py2.6.egg"
i get a huge Error and Warning list. I suppose it has something to do with some Transforms i had already in Zenoss...
I append a huge log from my console that you can see what i have done till now. (You can jump over the mid part because its a repeating error output)
So can you please take a look over this log and tell me what i have done wrong? At the moment there is still a search box in the top left to the user name, but it doesnt work.
Thanks
Michael
Tito:
No one should ever take your advice for anything after reading your posts.
My packs are not dangerous, infact, this problem is a transform issue which I've been discussing with Mike in IRC.
Best,
--Shane
Yes were talking over IRC to find out why the zenpack isnt working.
The installation of the zenpack has no influences of the stability of the other Zenoss-Stuff.. I can remove or install it. There are only the error messages from the install. All other Zenoss-Related Stuff is working.
Is there a requirement for the normal Global Device Search ZenPack?
For everyone i post here my transforms which i pasted under Events -> event classes -> gear (bottom left) -> Transform:
<code>
import re
# code for showing the 95th percentile in graphs
fs_id = device.prepId(evt.component)
for f in device.os.interfaces():
if f.id != fs_id: continue
# Extract the percent and utilization from the summary
m = re.search("threshold of [^:]+: current value ([\d\.]+)", evt.message)
if not m: continue
currentusage = (float(m.groups()[0])) * 8
p = (currentusage / f.speed) * 100
evtKey = evt.eventKey
# Whether Input or Output Traffic
if evtKey == "ifInOctets_ifInOctets|high utilization":
evtNewKey = "Input"
elif evtKey == "ifOutOctets_ifOutOctets|high utilization":
evtNewKey = "Output"
# code to show correct units in events
# Check the speed to determine the appropriate conversion
# Gbps utilization
if currentusage > 1000000000:
Usage = currentusage / 1000000000
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f Gbps) or %3.2f%% is being used." % (Usage, p)
# Mbps utilization
elif currentusage > 1000000:
Usage = currentusage / 1000000
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f Mbps) or %3.2f%% is being used." % (Usage, p)
# Kbps utilization
elif currentusage > 1000:
Usage = currentusage / 1000
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f Kbps) or %3.2f%% is being used." % (Usage, p)
# bps utilization
elif currentusage < 1000:
Usage = currentusage
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f bps) or %3.2f%% is being used." % (Usage, p)
break
# no generating of "High-Threshold"-Warnings for Tunnel-, Dialer- or Virtual-Access-Interfaces
if evt.component.find("Tunnel") >= 0:
evt._action = "drop"
if evt.component.find("Dialer") >= 0:
evt._action = "drop"
if evt.component.find("Virtual-Access") >= 0:
evt._action = "drop"
</code>
Now i will post the main error message which is responsible for the disfunction(i think):
After "zenpack --install=ZenPacks.ShaneScott.DeviceSearch-1.0.0-py2.6.egg":
2011-09-26 17:38:24,424 INFO zen.HookReportLoader: loading reports from:/var/zenoss/zenoss/ZenPacks/ZenPacks.ShaneScott.DeviceSearch-1.0.0-py2.6.egg/ZenPacks/ShaneScott/DeviceSearch/reports
2011-09-26 17:38:25,132 WARNING zen.Events: Error processing transform/mapping on Event Class /
Problem on line 2: AttributeError: 'NoneType' object has no attribute 'prepId'
fs_id = device.prepId(evt.component)
btw: how can i make code fields in my post?
Michael:
Try:
import re
# test device object is not None
if device:
# code for showing the 95th percentile in graphs
fs_id = device.prepId(evt.component)
for f in device.os.interfaces():
if f.id != fs_id: continue
# Extract the percent and utilization from the summary
m = re.search("threshold of [^:]+: current value ([\d\.]+)", evt.message)
if not m: continue
currentusage = (float(m.groups()[0])) * 8
p = (currentusage / f.speed) * 100
evtKey = evt.eventKey
# Whether Input or Output Traffic
if evtKey == "ifInOctets_ifInOctets|high utilization":
evtNewKey = "Input"
elif evtKey == "ifOutOctets_ifOutOctets|high utilization":
evtNewKey = "Output"
# code to show correct units in events
# Check the speed to determine the appropriate conversion
# Gbps utilization
if currentusage > 1000000000:
Usage = currentusage / 1000000000
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f Gbps) or %3.2f%% is being used." % (Usage, p)
# Mbps utilization
elif currentusage > 1000000:
Usage = currentusage / 1000000
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f Mbps) or %3.2f%% is being used." % (Usage, p)
# Kbps utilization
elif currentusage > 1000:
Usage = currentusage / 1000
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f Kbps) or %3.2f%% is being used." % (Usage, p)
# bps utilization
elif currentusage < 1000:
Usage = currentusage
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f bps) or %3.2f%% is being used." % (Usage, p)
break
# no generating of "High-Threshold"-Warnings for Tunnel-, Dialer- or Virtual-Access-Interfaces
if evt.component.find("Tunnel") >= 0:
evt._action = "drop"
if evt.component.find("Dialer") >= 0:
evt._action = "drop"
if evt.component.find("Virtual-Access") >= 0:
evt._action = "drop"
I think this will work by bailing when device is not set.
--Shane
Tito:
Transforms cannot break ZODB or an install. If you ahd problems its because you did not remove the pack, upgrade to zenoss 3 and nistall the new pack. That is how it should be done.
I don't know precisely what you want... I post you a screenshot from my Event Console and also the responsible code:
# no generating of "High-Threshold"-Warnings for Tunnel-, Dialer- or Virtual-Access-Interfaces
if evt.component.find("Tunnel") >= 0:
evt._action = "drop"
if evt.component.find("Dialer") >= 0:
evt._action = "drop"
if evt.component.find("Virtual-Access") >= 0:
evt._action = "drop"
in the event console there is an event "Error processing transform/mapping on Event Class" in the detailed view of this event it says:
Problem with line 68: evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f Kbps) or %3.2f%% is being used." % (Usage, p)
exception NameError: name 'evtNewKey' is not defined
can we talk today on irc?
Also i got an error in the ZenPacks-Overview: It says "This pack was just installed, or is missing or broken. Please restart Zope."
Restarting Zope has no effect.
Another Error is when i want to add a new Datasource under "Monitoring Templates" i get a "Server Exception":
The Server reported the following error:
AttributeError
getDataSourceClasses
The System has encountered an error. Please reload the page.
Reloading doesnt have an effect..
This error is really bad because i cant add any new datasources for new devices!!!
PLEASE HELP!!
isn't there anyone who can help? My Problem from post 9 still exists...
@Shane Scott: did you had time to write the lines for search in interfaces?
maybe this thread can help?: http://community.zenoss.org/message/57014#57014
Michael s:
I hope you're well! I've recently updated the pack to provide the needed functionality out of the box.
You can find it and documentation here: http://shanewilliamscott.com/Code/devicepropertysearch-zenpack.html
Is your transform still give you grief?
Best,
--Shane W. Scott(Hackman238)
Hello Shane,
the installation of your new modified Zenpack doesn't work. Even with your new version without version check(i just re-downloaded the *.egg file from your website...)
Here is the output in my console:
zenoss@x:~$ zenpack --install=ZenPacks.ShaneScott.DeviceSearch-1.2.0-py2.6.egg
Not found: zenoss >= 3.2
2011-11-14 11:50:55,764 INFO zen.HookReportLoader: loading reports from:/usr/local/zenoss/zenoss/ZenPacks/ZenPacks.ShaneScott.DeviceSearch-1.2.0-py2.6.egg/ZenPacks/ShaneScott/DeviceSearch/reports
But i am using Zenoss Version 3.2.1. What value is the installer checking for version check?
My current transform is exactly the one you've posted above:
import re
# test device object is not None
if device:
# code for showing the 95th percentile in graphs
fs_id = device.prepId(evt.component)
for f in device.os.interfaces():
if f.id != fs_id: continue
# Extract the percent and utilization from the summary
m = re.search("threshold of [^:]+: current value ([\d\.]+)", evt.message)
if not m: continue
currentusage = (float(m.groups()[0])) * 8
p = (currentusage / f.speed) * 100
evtKey = evt.eventKey
# Whether Input or Output Traffic
if evtKey == "ifInOctets_ifInOctets|high utilization":
evtNewKey = "Input"
elif evtKey == "ifOutOctets_ifOutOctets|high utilization":
evtNewKey = "Output"
# code to show correct units in events
# Check the speed to determine the appropriate conversion
# Gbps utilization
if currentusage > 1000000000:
Usage = currentusage / 1000000000
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f Gbps) or %3.2f%% is being used." % (Usage, p)
# Mbps utilization
elif currentusage > 1000000:
Usage = currentusage / 1000000
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f Mbps) or %3.2f%% is being used." % (Usage, p)
# Kbps utilization
elif currentusage > 1000:
Usage = currentusage / 1000
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f Kbps) or %3.2f%% is being used." % (Usage, p)
# bps utilization
elif currentusage < 1000:
Usage = currentusage
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f bps) or %3.2f%% is being used." % (Usage, p)
break
# no generating of "High-Threshold"-Warnings for Tunnel-, Dialer- or Virtual-Access-Interfaces
if evt.component.find("Tunnel") >= 0:
evt._action = "drop"
if evt.component.find("Dialer") >= 0:
evt._action = "drop"
if evt.component.find("Virtual-Access") >= 0:
evt._action = "drop"
These transforms generate a warning in my event list:
Error processing transform/mapping on Event Class /
"Problem with line 72: evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f Kbps) or %3.2f%% is being used." % (Usage, p)"
Also Tunnel-, Dialer and Virtual-Access interfaces are generating "threshold of high utilization exeeded: current value xxxxx"-warnings. That means the Transform code you gave me works to install your ZenPack but does not drop the high threshold-warnings. Is there a way to get both things to work?
Greetz
Michael
Michael:
I think f.speed is sometimes invalid and causing a problem.
Try this:
import re
# test device object is not None
if device:
# code for showing the 95th percentile in graphs
fs_id = device.prepId(evt.component)
for f in device.os.interfaces():
if f.id != fs_id: continue
# Extract the percent and utilization from the summary
m = re.search("threshold of [^:]+: current value ([\d\.]+)", evt.message)
if not m: continue
currentusage = (float(m.groups()[0])) * 8
#computer percent using f.speed where f.speed != None, otherwise assume speed = 1
speed = (f.speed or 1)
p = (currentusage / int(speed)) * 100
evtKey = evt.eventKey
# Whether Input or Output Traffic
if evtKey == "ifInOctets_ifInOctets|high utilization":
evtNewKey = "Input"
elif evtKey == "ifOutOctets_ifOutOctets|high utilization":
evtNewKey = "Output"
# code to show correct units in events
# Check the speed to determine the appropriate conversion
# check if speed > 1
if speed > 1:
# Gbps utilization
if currentusage > 1000000000:
Usage = currentusage / 1000000000
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f Gbps) or %3.2f%% is being used." % (Usage, p)
# Mbps utilization
elif currentusage > 1000000:
Usage = currentusage / 1000000
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f Mbps) or %3.2f%% is being used." % (Usage, p)
# Kbps utilization
elif currentusage > 1000:
Usage = currentusage / 1000
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f Kbps) or %3.2f%% is being used." % (Usage, p)
# bps utilization
elif currentusage < 1000:
Usage = currentusage
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f bps) or %3.2f%% is being used." % (Usage, p)
break
else:
# Gbps utilization
if currentusage > 1000000000:
Usage = currentusage / 1000000000
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f Gbps is being used. Interface speed invalid" % (Usage)
# Mbps utilization
elif currentusage > 1000000:
Usage = currentusage / 1000000
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f Mbps) is being used. Interface speed invalid" % (Usage)
# Kbps utilization
elif currentusage > 1000:
Usage = currentusage / 1000
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f Kbps) is being used. Interface speed invalid" % (Usage)
# bps utilization
elif currentusage < 1000:
Usage = currentusage
evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f bps) is being used. Interface speed invalid" % (Usage)
break
# no generating of "High-Threshold"-Warnings for Tunnel-, Dialer- or Virtual-Access-Interfaces
if evt.component.find("Tunnel") >= 0:
evt._action = "drop"
if evt.component.find("Dialer") >= 0:
evt._action = "drop"
if evt.component.find("Virtual-Access") >= 0:
evt._action = "drop"
Follow Us On Twitter » Latest from the Zenoss Blog » Community Products Services Customers About Us
Copyright © 2005-2011 Zenoss, Inc.
|
How can I convert an ndarray to a matrix in numpy? I'm trying to import data from a csv and turn it into a matrix.
from numpy import array, matrix, recfromcsv
my_vars = ['docid','coderid','answer1','answer2']
toy_data = matrix( array( recfromcsv('toy_data.csv', names=True)[my_vars] ) )
print toy_data
print toy_data.shape
But I get this:
[[(1, 1, 3, 3) (1, 2, 4, 1) (1, 3, 7, 2) (2, 1, 3, 3) (2, 2, 4, 4) (2, 4, 3, 1) (3, 1, 3, 3) (3, 2, 4, 3) (3, 3, 3, 4) (4, 4, 5, 1) (4, 5, 6, 2) (4, 2, 4, 3) (5, 2, 5, 4) (5, 3, 3, 1) (5, 4, 7, 2) (6, 1, 3, 3) (6, 5, 4, 1) (6, 2, 5, 2)]](1, 18)
What do I have to do to get a 4 by 18 matrix out of this code? There's got to be an easy answer to this question, but I just can't find it.
|
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).
|
I was wondering if anyone had an idea as to why the code below does not display a graph with a line in it after the button on the GUI is pressed. I would like to create a program that executes a long list of commands after a set of data is imported by clicking a button. One of these commands would be to display the spectral data on a graph within the same window. Here is what I have so far:
# import modules that I'm using
import matplotlib
matplotlib.use('TKAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.pyplot as pltlib
import Tkinter
from Tkinter import *
import numpy as np
import scipy as sc
#import matplotlib.pyplot as pltlib
# lmfit is imported becuase parameters are allowed to depend on each other along with bounds, etc.
from lmfit import minimize, Parameters, Minimizer
#Make object for application
class App_Window(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
button = Tkinter.Button(self,text="Open File",command=self.OnButtonClick).pack(side=Tkinter.TOP)
self.canvasFig=pltlib.figure(1)
Fig = matplotlib.figure.Figure(figsize=(5,4),dpi=100)
FigSubPlot = Fig.add_subplot(111)
x=[]
y=[]
self.line1, = FigSubPlot.plot(x,y,'r-')
self.canvas = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(Fig, master=self)
self.canvas.show()
self.canvas.get_tk_widget().pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)
self.canvas._tkcanvas.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)
self.resizable(True,False)
self.update()
def refreshFigure(self,x,y):
self.line1.set_xdata(x)
self.line1.set_ydata(y)
self.canvas.draw()
def OnButtonClick(self):
# file is opened here and some data is taken
# I've just set some arrays here so it will compile alone
x=[]
y=[]
for num in range(0,1000):x.append(num*.001+1)
# just some random function is given here, the real data is a UV-Vis spectrum
for num2 in range(0,1000):y.append(sc.math.sin(num2*.06)+sc.math.e**(num2*.001))
X = np.array(x)
Y = np.array(y)
self.refreshFigure(X,Y)
if __name__ == "__main__":
MainWindow = App_Window(None)
MainWindow.mainloop()
|
sqlite is a SQL database and works by far best when used as such (wrapped in SQLAlchemy or whatever if you really insist;-).
Syntax such as d[key="NAME", 'Joe'] is simply illegal Python, no matter how much wrapping and huffing and puffing you may do. A simple class wrapper around the DB connection is easy, but it will never give you that syntax -- something like d.fetch('Joe', key='Name') is reasonably easy to achieve, but indexing has very different syntax from function calls, and even in the latter named arguments must come after positional ones.
If you're willing to renounce your ambitious syntax dreams in favor of sensible Python syntax, and need help designing a class to implement the latter, feel free to ask, of course (I'm off to bed pretty soon, but I'm sure other, later-sleepers will be eager to help;-).
Edit: given the OP's clarifications (in a comment), it looks like a set_key method is acceptable to maintain Python-acceptable syntax (though the semantics of course will still be a tad off, since the OP wants a "dict-like" object which may have non unique keys -- no such thing in Python, really... but, we can approximate it a bit, at least).
So, here's a very first sketch (requires Python 2.6 or better -- just because I've used collections.MutableMapping to get other dict-like methods and .format to format strings; if you're stuck in 2.5, %-formatting of strings and UserDict.DictMixin will work instead):
import collections
import sqlite3
class SqliteDict(collections.MutableMapping):
@classmethod
def create(cls, path, columns):
conn = sqlite3.connect(path)
conn.execute('DROP TABLE IF EXISTS SqliteDict')
conn.execute('CREATE TABLE SqliteDict ({0})'.format(','.join(columns.split())))
conn.commit()
return cls(conn)
@classmethod
def open(cls, path):
conn = sqlite3.connect(path)
return cls(conn)
def __init__(self, conn):
# looks like for sime weird reason you want str, not unicode, when feasible, so...:
conn.text_factory = sqlite3.OptimizedUnicode
c = conn.cursor()
c.execute('SELECT * FROM SqliteDict LIMIT 0')
self.cols = [x[0] for x in c.description]
self.conn = conn
# start with a keyname (==column name) of `ID`
self.set_key('ID')
def set_key(self, key):
self.i = self.cols.index(key)
self.kn = key
def __len__(self):
c = self.conn.cursor()
c.execute('SELECT COUNT(*) FROM SqliteDict')
return c.fetchone()[0]
def __iter__(self):
c = self.conn.cursor()
c.execute('SELECT * FROM SqliteDict')
while True:
result = c.fetchone()
if result is None: break
k = result.pop(self.i)
return k, result
def __getitem__(self, k):
c = self.conn.cursor()
# print 'doing:', 'SELECT * FROM SqliteDict WHERE {0}=?'.format(self.kn)
# print ' with:', repr(k)
c.execute('SELECT * FROM SqliteDict WHERE {0}=?'.format(self.kn), (k,))
result = [list(r) for r in c.fetchall()]
# print ' resu:', repr(result)
for r in result: del r[self.i]
return result
def __contains__(self, k):
c = self.conn.cursor()
c.execute('SELECT * FROM SqliteDict WHERE {0}=?'.format(self.kn), (k,))
return c.fetchone() is not None
def __delitem__(self, k):
c = self.conn.cursor()
c.execute('DELETE FROM SqliteDict WHERE {0}=?'.format(self.kn), (k,))
self.conn.commit()
def __setitem__(self, k, v):
r = list(v)
r.insert(self.i, k)
if len(r) != len(self.cols):
raise ValueError, 'len({0}) is {1}, must be {2} instead'.format(r, len(r), len(self.cols))
c = self.conn.cursor()
# print 'doing:', 'REPLACE INTO SqliteDict VALUES({0})'.format(','.join(['?']*len(r)))
# print ' with:', r
c.execute('REPLACE INTO SqliteDict VALUES({0})'.format(','.join(['?']*len(r))), r)
self.conn.commit()
def close(self):
self.conn.close()
def main():
d = SqliteDict.create('student_table', 'ID NAME BIRTH AGE SEX')
d['1'] = ["Joe", "01011980", "30", "M"]
d['2'] = ["Rose", "12111986", "24", "F"]
print len(d), 'items in table created.'
print d['2']
print d['1']
d.close()
d = SqliteDict.open('student_table')
d.set_key('NAME')
print len(d), 'items in table opened.'
print d['Joe']
if __name__ == '__main__':
main()
The class is not meant to be instantiated directly (though it's OK to do so by passing an open sqlite3 connection to a DB with an appropriate SqliteDict table) but through the two class methods create (to make a new DB or wipe out an existing one) and open, which seems to match the OP's desires better than the alternative (have __init__ take a DB file path an an option string describing how to open it, just like modules such as gdbm take -- 'r' to open read-only, 'c' to create or wipe out, 'w' to open read-write -- easy to adjust of course). Among the columns passed (as a whitespace-separated string) to create, there must be one named ID (I haven't given much care to raising "the right" errors for any of the many, many user errors that can occur on building and using instances of this class; errors will occur on all incorrect usage, but not necessarily ones obvious to the user).
Once an instance is opened (or created), it behaves as closely to a dict as possible, except that all values set must be lists of exactly the right length, while the values returned are lists of lists (due to the weird "non-unique key" issue). For example, the above code, when run, prints
2 items in table created.
[['Rose', '12111986', '24', 'F']]
[['Joe', '01011980', '30', 'M']]
2 items in table opened.
[['1', '01011980', '30', 'M']]
The "Pythonically absurd" behavior is that d[x] = d[x] will fail -- because the right hand side is a list e.g. with a single item (which is a list of the column values) while the item assignment absolutely requires a list with e.g. four items (the column values). This absurdity is in the OP's requested semantics, and could be altered only by drastically changing such absurd required semantics again (e.g., forcing item assignment to have a list of lists on the RHS, and using executemany in lieu of plain execute).
Non-uniqueness of keys also makes it impossible to guess if d[x] = v, for a key k which corresponds to some number n of table entries, is meant to replace one (and if so, which one?!) or all of those entries, or add another new entry instead. In the code above I've taken the "add another entry" interpretation, but with a SQL statement REPLACE that, should the CREATE TABLE be changed to specify some uniqueness constraints, will change some semantics from "add entry" to "replace entries" if and when uniqueness constraints would otherwise be violated.
I'll let you all to play with this code, and reflect how huge the semantic gap is between Python mappings and relational tables, that the OP is desperately keen to bridge (apparently as a side effect of his urge to "use nicer syntax" than SQL affords -- I wonder if he has looked at SqlAlchemy as I recommended).
I think, in the end, the important lesson is what I stated right at the start, in the first paragraph of the part of the answer I wrote yesterday, and I self-quote...:
sqlite is a SQL database and works
by far best when used as such (wrapped
in SQLAlchemy or whatever if you
really insist;-).
|
I've started to use constructs like these:
class DictObj(object):
def __init__(self):
self.d = {}
def __getattr__(self, m):
return self.d.get(m, None)
def __setattr__(self, m, v):
super.__setattr__(self, m, v)
Update: based on this thread, I've revised the DictObj implementation to:
class dotdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
class AutoEnum(object):
def __init__(self):
self.counter = 0
self.d = {}
def __getattr__(self, c):
if c not in self.d:
self.d[c] = self.counter
self.counter += 1
return self.d[c]
where DictObj is a dictionary that can be accessed via dot notation:
d = DictObj()
d.something = 'one'
I find it more aesthetically pleasing than d['something']. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.
Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using dict instead of defining a new dictionary; if not, I like mhawke's solution a lot.
AutoEnum is an auto-incrementing Enum, used like this:
CMD = AutoEnum()
cmds = {
"peek": CMD.PEEK,
"look": CMD.PEEK,
"help": CMD.HELP,
"poke": CMD.POKE,
"modify": CMD.POKE,
}
Both are working well for me, but I'm feeling unpythonic about them.
Are these in fact bad constructs?
|
This is one of the research project that I am current going through. The requirement is almost exactly as yours, and we have developed nice algorithms to solve the problem.
The Input
The input is an endless stream of English words or phrases (we refer them as tokens).
The Output
Output top N tokens we have seen sofar (from all the tokens we haveseen!)
Output top N tokens in ahistorical window, say, last day orlast week.
An application of this research is to find the hot topic or trends of topic in Twitter or Facebook. We have a crawler that crawls on the website, which generates a stream of words, which will feed into the system. The system then will output the words or phrases of top frequency either at overall or historically. Imagine in last couple of weeks the phrase "World Cup" would appears many times in Twitter. So does "Paul the octopus". :)
String into Integers
The system has an integer ID for each word. Though there is almost infinite possible words on the Internet, but after accumulating a large set of words, the possibility of finding new words becomes lower and lower. We have already found 4 million different words, and assigned a unique ID for each. This whole set of data can be loaded into memory as a hash table, consuming roughly 300MB memory. (We have implemented our own hash table. The Java's implementation takes huge memory overhead)
Each phrase then can be identified as an array of integers.
This is important, because sorting and comparisons on integers is much much faster than on strings.
Archive Data
The system keeps archive data for every token. Basically it's pairs of (Token, Frequency). However, the table that stores the data would be so huge such that we have to partition the table physically. Once partition scheme is based on ngrams of the token. If the token is a single word, it is 1gram. If the token is two-word phrase, it is 2gram. And this goes on. Roughly at 4gram we have 1 billion records, with table sized at around 60GB.
Processing Incoming Streams
The system will absorbs incoming sentences until memory becomes fully utilized (Ya, we need a MemoryManager). After taking N sentences and storing in memory, the system pauses, and starts tokenize each sentence into words and phrases. Each token (word or phrase) is counted.
For highly frequent tokens, they are always kept in memory. For less frequent tokens, they are sorted based on IDs (remember we translate the String into an array of integers), and serialized into a disk file.
(However, for your problem, since you are counting only words, then you can put all word-frequency map in memory only. A carefully designed data structure would consume only 300MB memory for 4 million different words. Some hint: use ASCII char to represent Strings), and this is much acceptable.
Meanwhile, there will be another process that is activated once it finds any disk file generated by the system, then start merging it. Since the disk file is sorted, merging would take a similar process like merge sort. Some design need to be taken care at here as well, since we want to avoid too many random disk seeks. The idea is to avoid read (merge process)/write (system output) at the same time, and let the merge process read form one disk while writing into a different disk. This is similar like to implementing a locking.
End of Day
At end of day, the system will have many frequent tokens with frequency stored in memory, and many other less frequent tokens stored in several disk files (and each file is sorted).
The system flush the in-memory map into a disk file (sort it). Now, the problem becomes merging a set of sorted disk file. Using similar process, we would get one sorted disk file at the end.
Then, the final task is to merge the sorted disk file into archive database. Depends on the size of archive database, the algorithm works like below if it is big enough:
for each record in sorted disk file
update archive database by increasing frequency
if rowcount == 0 then put the record into a list
end for
for each record in the list of having rowcount == 0
insert into archive database
end for
The intuition is that after sometime, the number of inserting will become smaller and smaller. More and more operation will be on updating only. And this updating will not be penalized by index.
Hope this entire explanation would help. :)
|
yann458
paquet computertemp ou autre
Bonjour,
J'ai monté une machine AMD , et étant donnée que les processeur AMD chauffe plus ,
je cherche un utilitaire aqéquat qui avertit d'une boite de dialogue si le processeur est en surchauffe.
L'utilitaire computertemp joue un son si le processeur est en surchauffe , et je preferais que ca affiche une boite
de dialogue de surchauffe , car mes baffle ne sont pas toujours connecté.
Merci.
Hors ligne
bishop
Re : paquet computertemp ou autre
Salut yann458 !
Psensor affiche des notifications de bureau. Voir Ubuntu – Installation du moniteur de température Psensor..
Dernière modification par bishop (Le 30/12/2012, à 13:54)
En ligne
yann458
Re : paquet computertemp ou autre
Ca fonctionne mais je n'ai pas les températures de CPU Core X (0,1,2,3,4,5,6,7).
J'ai la température du GPU.
Carte mère MSI 970A-G46 - Chipset AMD 970 -
AMD - Processeur AMD FX-8350 Black Edition - 4.0GHz - Socket AM3+
Hors ligne
bishop
Re : paquet computertemp ou autre
Tu as installé et configuré lm-sensors comme indiqué au paragraphe Configuration automatique de lm-sensors ?
Note qu'il faut que tu redémarres ton ordi pour charger les modules.
Voir aussi lm-sensors : Utiliser les capteurs matériels.
Qu'est-ce que te renvoie la commande :
sensors
Dernière modification par bishop (Le 30/12/2012, à 18:55)
En ligne
yann458
Re : paquet computertemp ou autre
Ce que me renvoie la commande sensors :
f71889a-isa-0480
Adapter: ISA adapter
+3.3V: +3.28 V
in1: +0.97 V (max = +2.04 V)
in2: +1.08 V
in3: +0.87 V
in4: +0.62 V
in5: +1.36 V
in6: +1.66 V
3VSB: +3.26 V
Vbat: +3.30 V
fan1: 3614 RPM
fan2: 0 RPM ALARM
fan3: 0 RPM ALARM
temp1: +26.0°C (high = +85.0°C, hyst = +81.0°C)
(crit = +80.0°C, hyst = +76.0°C) sensor = transistor
temp2: +38.0°C (high = +85.0°C, hyst = +79.0°C)
(crit = +109.0°C, hyst = +103.0°C) sensor = thermistor
temp3: +39.0°C (high = +70.0°C, hyst = +68.0°C)
(crit = +85.0°C, hyst = +83.0°C) sensor = transistor
fam15h_power-pci-00c4
Adapter: PCI adapter
power1: 38.27 W (crit = 125.19 W)
k10temp-pci-00c3
Adapter: PCI adapter
temp1: +14.1°C (high = +70.0°C)
(crit = +80.0°C, hyst = +77.0°C)
Hors ligne
bishop
Re : paquet computertemp ou autre
Ah Oui... Les "Cores" ne sont pas reconnus. Sur ma distrib (proc. Intel) cela donne :
bishop@JC:~$ sensors
acpitz-virtual-0
Adapter: Virtual device
temp1: +19.0°C (crit = +6280.3°C)
coretemp-isa-0000
Adapter: ISA adapter
Core 0: +29.0°C (high = +81.0°C, crit = +101.0°C)
Core 1: +32.0°C (high = +81.0°C, crit = +101.0°C)
Core 2: +31.0°C (high = +81.0°C, crit = +101.0°C)
Core 8: +18.0°C (high = +81.0°C, crit = +101.0°C)
Core 9: +35.0°C (high = +81.0°C, crit = +101.0°C)
Core 10: +35.0°C (high = +81.0°C, crit = +101.0°C)
J'avais pas remarqué que la température critique de temp1 est "crit = +6280.3°C" > >
Tu as bien tout suivi dans la configuration de lm-sensors ?
En ligne
|
For my program I have a lot of places where an object can be either a string or a list containing strings and other similar lists. These are generally read from a JSON file. They both need to be treated differently. Right now, I am just using isinstance, but that does not feel like the most pythonic way of doing it, so does anyone have a better way of doing it?
No need to import modules,
Python 2.x:
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance(u'', (str, unicode))
True
>>> isinstance('', (str, unicode))
True
>>> isinstance([], (str, unicode))
False
>>> for value in ('snowman', u'☃ ', ['snowman', u'☃ ']):
... print type(value)
...
<type 'str'>
<type 'unicode'>
<type 'list'>
Python 3.x:
Python 3.2 (r32:88445, May 29 2011, 08:00:24)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance('☃ ', str)
True
>>> isinstance([], str)
False
>>> for value in ('snowman', '☃ ', ['snowman', '☃ ']):
... print(type(value))
...
<class 'str'>
<class 'str'>
<class 'list'>
From PEP008:
Since Python3 no longer has
if isinstance(thing, list):
# treat as list
else:
# treat as str/unicode
as that is compatible with both Python2 and Python3
Using
On Python>=2.3 a string may be a
if isinstance(a,basestring): # same as isinstance(obj, (str, unicode))
print "Object is a string"
From Python 3 only one string type exists, so instead of
if isinstance(a,str):
print "Object is a string"
You can use types module:
import types
if type(ls) == types.ListType:
#your code for list objects here
|
JavaScript
reedbird8 — 2012-10-02T13:44:41-04:00 — #1
Not sure if this is the best place to ask this, or if it can be done, but here it goes.
Is there a way to generate a tooltip anytime a certain word or phrase appears within my site? Ideally, I'd like to create a series of tooltips for some terminology. Essentially, anytime the abbreviation "TSD-1a" appears a tooltip would be generated for this abbreviation. (I'm looking for something other than me having to type the html markup everytime I want the tooltip to appear.)
pullo — 2012-10-02T17:09:17-04:00 — #2
Hi,
Presuming that your content is in a <div> called "container" you can wrap all occurences of the abbreviation "TSD-1a" in <a> tags and apply a class of "normalTip" to these with the following jQuery:
$('#container').html($('#container').html().replace(/(TSD-1a)/g,'<a href="#" class="normalTip" title="Some Text">$1</a>'));
After that you can get all elements with the class "normalTip" and hook them up to tooltips. The title attribute serves as the text for the tip.
Here's an example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tooltip demo</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://ara-abcarians.com/jquery/atooltip/js/jquery.atooltip.js"></script>
<link type="text/css" href="http://ara-abcarians.com/jquery/atooltip/css/atooltip.css" rel="stylesheet" media="screen" />
<script>$(function(){$('a.normalTip').aToolTip(); });</script>
</head>
<body>
<div id="container" style="width:600px; margin: 0 auto; padding-top:50px;">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, TSD-1a sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut TSD-1a enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis TSD-1a aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur TSD-1a sint occaecat cupidatat non proident, TSD-1a sunt in culpa qui officia deserunt
mollit anim id est TSD-1a laborum.
</p>
</div>
<script>$('#container').html($('#container').html().replace(/(TSD-1a)/g,'<a href="#" class="normalTip" title="Some Text">$1</a>'));</script>
</body>
</html>
Here, I've used a simple jQuery tooltip plugin to achieve the tooltips.
If you opt for this, please download the files you need from here: http://ara-abcarians.com/jquery/atooltip/ and don't use the author's site as a CDN.
reedbird8 — 2012-10-02T17:33:42-04:00 — #3
Thanks! Question - will it only grab those directly appearing in the div with id "container"? Or if there is a div inside the "container" div, will it grab those, as well?
i.e.:
<body>
<div id="container" style="width:600px; margin: 0 auto; padding-top:50px;">
<div id="left column">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, TSD-1a sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut TSD-1a enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis TSD-1a aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur TSD-1a sint occaecat cupidatat non proident, TSD-1a sunt in culpa qui officia deserunt
mollit anim id est TSD-1a laborum.
</p>
</div>
</div>
<script>$('#container').html($('#container').html().replace(/(TSD-1a)/g,'<a href="#" class="normalTip" title="Some Text">$1</a>'));</script>
</body>
pullo — 2012-10-03T01:34:46-04:00 — #4
It'll grab everything within the "container" div, irrespective of whether it's nested in a further div/divs.
Is this the desired behaviour?
reedbird8 — 2012-10-03T05:10:06-04:00 — #5
yes, that's what I would want it to do.
pullo — 2012-10-03T05:12:03-04:00 — #6
Cool
If this changes at any point you can always refine the '#container' selector.
reedbird8 — 2012-10-03T05:48:10-04:00 — #7
Well, it works, but it clashes with other script on my site. A bunch of my other jquery features stop working. (tabs, certain menus, etc)
pullo — 2012-10-03T07:02:07-04:00 — #8
That's not good.
Are you using any other libraries?
If you can post a url, I don't mind taking a look.
reedbird8 — 2012-10-03T07:12:42-04:00 — #9
Thanks, url is http://theturtleroom.com
pullo — 2012-10-03T07:27:27-04:00 — #10
Nice site, but everything seems to be working for me.
Plus I could find no mention of the abbreviation "TSD-1a"
reedbird8 — 2012-10-03T07:42:34-04:00 — #11
Thanks!
Oh, I had pulled it down, since things weren't working....I'll put it back up. Instead of looking for TSD-1a (which is for a future reference), look for SCL on this page:
http://theturtleroom.com/projects/steve-projects/graptemys/graptemys-barbouri/
You can see that the tabs below the text and the main navigational menus (can't get to the submenu level) have stopped working. In addition, my sidebar menu is a jquery menu and no longer automatically collapses (and expands/collapses on hover)
pullo — 2012-10-03T08:03:26-04:00 — #12
Your problem is twofold.
You have included jQuery twice.
jQuery seems to be operating in noConflict mode on your page.
Just for your info: all noConflict mode does is have jQuery relinquish control of the $ variable. You can read about it here: http://api.jquery.com/jQuery.noConflict/
reedbird8 — 2012-10-03T08:08:19-04:00 — #13
Thanks again! It's all working well now!
There is still one place where the tooltip is not visually appearing properly. Its not live to the public yet, but if you wouldn't mind looking at it, I'll send some login information and the page link so you could look at that page, too.
pullo — 2012-10-03T08:09:33-04:00 — #14
Go on then, but if I ever want to buy a turtle, I expect a good price
reedbird8 — 2012-10-03T08:17:18-04:00 — #15
No problem!....message sent
reedbird8 — 2012-10-03T10:23:07-04:00 — #16
So, one last tooltip question:
I'd like to be able to tip all of TSD, TSD-1a, TSD-1b, and TSD-2. However, a tip for TSD seems to interfere with the other 3 tips. Any idea?
pullo — 2012-10-03T14:17:59-04:00 — #17
Hi There,
do it like this, with the use of a regular expression:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tooltip demo</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://ara-abcarians.com/jquery/atooltip/js/jquery.atooltip.js"></script>
<link type="text/css" href="http://ara-abcarians.com/jquery/atooltip/css/atooltip.css" rel="stylesheet" media="screen" />
<script>$(function(){$('a.normalTip').aToolTip(); });</script>
</head>
<body>
<div id="container" style="width:600px; margin: 0 auto; padding-top:50px;">
<div id="left column">
<p>
TSD Lorem ipsum TSD dolor sit amet, consectetur adipisicing elit, TSD-1a sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut TSD-1a enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis TSD-1a aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur TSD-1a sint occaecat cupidatat non TSD, proident, TSD-1a sunt in culpa qui officia deserunt
mollit anim id est TSD TSD-1a laborum TSD.
</p>
</div>
</div>
<script>
//Matches (start of line or whitespace)(TSD)(whitespace, or a fullstop, or a comma, or the end of the line)
var tsd = /(^|\\s)(TSD)(\\s|\\.|,|$)/g;
var tsdTip = '$1<a href="#" class="normalTip" title="TSD">$2</a>$3'
//Matches (start of line or whitespace)(TSD-1a)(whitespace, or a fullstop, or a comma, or the end of the line)
var tsd1a = /(^|\\s)(TSD-1a)(\\s|\\.|,|$)/g;
var tsd1aTip = '$1<a href="#" class="normalTip" title="TSD-1a">$2</a>$3'
$('#container').html(
$('#container').html().replace(tsd, tsdTip).replace(tsd1a, tsd1aTip)
);
</script>
</body>
</html>
reedbird8 — 2012-10-03T14:39:15-04:00 — #18
Thanks again!
These forums are a great place to get help.
|
So what I want to do seems relatively simple, but for the life of me, I just can't quite get it. I have a .txt file like
4 26 5 19 4 5
And I want its information to be available to me like so (i.e. I do not need to write a new .txt file unless it would be necessary.)...
3 15 4 08 3 4
or, 1 is subtracted from every number but the formatting remains the same. There will never be a number greater than 1 in the original, so negatives won't be possible. This whole headache is due to converting indexing to begin with 0 instead of 1. What may complicate things is that the original file prints like
['4 2 /n','6 5 1 /n', '9 4 5 /n']
What I've Done
Well its a mishmash of different things I've found on StackOverflow, but I think I'm going about it in the most cumbersome way possible. And this one didn't make sense when I implemented it.. although it may be on the same track with the issue with spaces..
origianl = open(file, 'r')
for line in original.readlines():
newline = line.replace(" \n","")
finalWithStrings.append(newline)
finalWithIntegers = [map(int,x) for x in finalWithStrings]
finalWithIntegers[:] = [x-1 for x in finalWithIntegers]
My thought process was, I need to remove the "/n" and to convert these strings into integers so I can subtract 1 from them. And somehow keep the formatting. It's important to have the formatting be the same since each line contains information on the similarly indexed line of another file. I don't want to see the "/n" in the end result (or print statement) but I still want the effect of a new line beginning. The above code however, wont work for two reasons (that I know of).
int(n[:]) throws an error since it doesn't like the spaces and when I put a value (say 0) in there, then the code prints the first number on each of the lines and subtracts one.. and puts it all on one line.
[3, 5, 8]
So, it seems redundant to take out a carriage return and have to throw another in, but I do need to keep the formatting, as well as have a way to get all the numbers!
This also didn't work:
for line in original.readlines():
newline = line.replace(" \n","")
finalWithStrings.append(newline)
finalWithIntegers = [map(int,x) for x in finalWithStrings]
finalWithIntegers[:] = [x-1 for x in finalWithIntegers]
but instead of just a wrong output it was an error:
ValueError:invalid literal for int() with base 10:''
Does anyone have any ideas on what I'm doing wrong here and how to fix this? I am working with Python 2.6 and am a beginner.
|
The lda.show_topics module from the following code only prints the distribution of the top 10 words for each topic, how do i print out the full distribution of all the words in the corpus?
from gensim import corpora, models
documents = ["Human machine interface for lab abc computer applications",
"A survey of user opinion of computer system response time",
"The EPS user interface management system",
"System and human system engineering testing of EPS",
"Relation of user perceived response time to error measurement",
"The generation of random binary unordered trees",
"The intersection graph of paths in trees",
"Graph minors IV Widths of trees and well quasi ordering",
"Graph minors A survey"]
stoplist = set('for a of the and to in'.split())
texts = [[word for word in document.lower().split() if word not in stoplist]
for document in documents]
dictionary = corpora.Dictionary(texts)
corpus = [dictionary.doc2bow(text) for text in texts]
lda = models.ldamodel.LdaModel(corpus_tfidf, id2word=dictionary, num_topics=2)
for i in lda.show_topics():
print i
|
FTG
[script/python] Nautilus et picasaweb!
Bonjour à tous,
depuis longtemps je voulais réaliser un petit script python a l'aide des API Google, me permettant d'uploader en 2 temps 3 mouvements un paquet de photos de Nautilus vers Picasaweb par un clic droit de souris.
Je n'avais pratiquement rien à faire aujourd hui et je m'y suis attelé et j'ai fini par obtenir un résultat.
Ce n'est pas grandiose grandiose mais ca fait le boulot!
Est ce que cela interesserait quelqu un que je décrive la marche à suivre ainsi que les outils à installer pour que cela fonctionne sachant que ce n'est vraiment pas compliqué?
a+
Hors ligne
Jeece
Re : [script/python] Nautilus et picasaweb!
Salut. Non ça intéresse sûrement personne car Picasa c'est propriétaire et on préfère F-Spot qui fait très bien le boulot.
J'rigole hein
Dis nous vite vite vite. Et maintenant fait nous la même chose pour flickr ce serait chupa chups.
Dernière modification par Jeece (Le 11/05/2008, à 17:46)
Content que ça vous plaise !
Hors ligne
FTG
Re : [script/python] Nautilus et picasaweb!
Re à tous,
Le but de ce post est d'initier peut etre un projet plus solide qui pourrait voir le jour, à la communauté de trancher
Bon voila l'affaire.
Ce que vous devez avoir installé sur votre machine:
- python 2.4 au moins (de base vous l'avez)
- xterm
- nautilus-actions (dans les depots debian stable, je pense que sous Ubuntu y aura pas de soucis)
Une fois ces trois paquets installés, allez voir du côté de ce lien:
http://code.google.com/p/gdata-python-c … loads/list et telechargez la derniere version de
gdate-py dans un endroit de votre partition /home/user. Décompresser avec la commande tar xvf puis bien lire INSTALL.TXT ca vaut le coup! Pour les plus préssés d'entre vous lancez tout de suite
python setup.py
en root. Dans l'INSTALL.TXT il est bien indiqué comment tester si l'installation a bien fonctionné!
Copiez le script suivant dans ~/Scripts_python/nom_de_fichier.py
# -*- coding: utf-8 -*-
# Envoi de photos sur picasaweb
# installation de gdata, xterm requise, nautilus-actions
# Dans Nautilus Action rentrer
# Chemin:: xterm -e python "script"
# Parametres:: %M
import sys
import gdata.photos.service
#import gdata.media
#import gdata.geo
print "####################### Fichiers à envoyer: #################################"
for i in range(len(sys.argv)-1):
print sys.argv[i+1]
print "#############################################################################"
print ""
print ""
email=raw_input("Veuillez entrer votre login Picasa/Google: ")
password=raw_input("Veuillez entrer votre mot de passe: ")
gd_client = gdata.photos.service.PhotosService()
gd_client.email = email
gd_client.password = password
gd_client.source = 'exampleCo-exampleApp-1'
try:
gd_client.ProgrammaticLogin()
except gdata.service.CaptchaRequired:
print('Required Captcha')
except gdata.service.BadAuthentication:
print('Mauvaise authentification')
except gdata_client.Error:
print('Probleme de Login')
else:
nouvelalbum=raw_input("Voulez vous creer un nouvel album? (O/N) ")
if nouvelalbum=="O" or nouvelalbum=="o":
nom_album=raw_input("Nom de l'album (sans espaces): ")
# Verification si l'album existe deja
feed = gd_client.GetUserFeed(user="default")
for entry in feed.entry:
while nom_album.lower()==str(entry.title.text).lower():
print "Cet album existe deja, veuillez entrer un autre nom!"
nom_album=raw_input("Nom de l'album (sans espaces): ")
acces=raw_input("Acces de l'album (private/public): ")
entry = gd_client.InsertAlbum(nom_album, summary='This is an album', access=acces)
album_url = '/data/feed/api/user/%s/album/%s' % ('default', nom_album)
for i in range(len(sys.argv)-1):
entry = gd_client.InsertPhotoSimple(album_url, 'New Photo','Uploaded using FTG loader', sys.argv[i+1], content_type='image/jpeg')
print "Photo numero " + str(i+1) + " envoyee!"
else:
print "Choisissez un album: "
feed = gd_client.GetUserFeed(user="default")
i=0
for entry in feed.entry:
i=i+1
print str(i) + ':: %s, number of photos: %s' % (entry.title.text,
entry.numphotos.text)
album=raw_input("Veuillez rentrer un numero d'album (Chiffre de 1 a " + str(i) + "): ")
i=0
for entry in feed.entry:
i=i+1
if str(i)==str(album):
nom_album=entry.title.text
album_url = '/data/feed/api/user/%s/album/%s' % ('default', nom_album)
for j in range(len(sys.argv)-1):
entry = gd_client.InsertPhotoSimple(album_url, 'New Photo','Uploaded using FTG loader', sys.argv[j+1], content_type='image/jpeg')
print "Photo numero " + str(j+1) + " envoyee!"
fin=raw_input("Appuyez sur Entree pour sortir!")
Ensuite, ouvrir Menu Gnome>Bureau>Preferences>Configuration des actions de nautilus (issu du paquet nautilus-actions)
Cliquer sur Ajouter. Dans Libellé ecrire un truc du genre "Envoyer vers Picasaweb".
Dans Chemin, mettre xterm -e python "lien vers le script python que vous avez stockés plus haut"
Dans Parametres, mettre %M
Fermez le tout!
Ensuite allez dans nautilus, selectionnez les photos que vous desirez envoyer vers picasaweb, cliquez droit puis selectionner "Envoyer vers Picasaweb" et suivez les instructions sous xterm!!
Bon je suis bien conscient que ce tuto est un peu leger, mais c'est historie de vous en faire profiter au plus vite, a terme je compte developper une petite page web avec screenshots et ameliorer l'emballage avec pourquoi pas du GTK et des options supplémentaires!
De plus, le script python est loin d'etre optimisé, mais j'ai codé ca à la va-vite cet apres midi, mais promis je vais améliorer tout ca!
Pour tout dysfonctionnement, n'hésitez pas à m'appeler au secours.
Pour toute idée supplémentaire, n'hésitez pas à me contacter non plus!
Bonne soirée à tous
Dernière modification par FTG (Le 11/05/2008, à 19:00)
Hors ligne
Annala
Re : [script/python] Nautilus et picasaweb!
Bonjour,
Superbe idée, c'est exactement ce que je cherchais.
L'installation a l'air de bien se dérouler, c'est tout à la fin que ça coince : en faisant le clic droit, je n'ai pas "Envoyer vers ..." pourtant j'ai configuré nautilus-actions comme indiqué.
En cherchant mon erreur, je viens de découvrir dans F-Spot > Fichier >Envoyer vers > Webgallery, Picasaweb, Flickr, CD ...
Dernière modification par Annala (Le 12/05/2008, à 17:42)
Dell XPS M1530 - Trusty Tahr
Hors ligne
FTG
Re : [script/python] Nautilus et picasaweb!
Oui mais le but est de pouvoir envoyer les photos de Nautilus sans passer par un autre logiciel...
Hors ligne
FTG
Re : [script/python] Nautilus et picasaweb!
up,pour les curieux
Hors ligne
Axelap
Re : [script/python] Nautilus et picasaweb!
Vous n'auriez pas un script pour faire l'inverse des fois ? En effet même avec Picase je n'arrive pas à les récupérer. Je ne me vois pas les enregistret une par une.
ps : la galerie est bien à moi et je suis connecté.
Axelap, sous Ubuntu depuis début octobre 2008
Hors ligne
FTG
Re : [script/python] Nautilus et picasaweb!
Hola,
non désolé je n'ai pas l'inverse pour le moment, mais ca pourrait etre une bonne idée!
Hors ligne
Axelap
Re : [script/python] Nautilus et picasaweb!
Je viens de découvrir une extension pour firefox qui peut gérer les connexions à double sens : fire/universal uploader.
Axelap, sous Ubuntu depuis début octobre 2008
Hors ligne
Sebco
Re : [script/python] Nautilus et picasaweb!
vachement bien.....ouaip!!! merci et bravo
.*´¨;) -->Pour les problemes http://chat.jabberfr.org/muckl_int/index.php?room=ubu-personnalisation
¸.•´¸.•´¨;)¸.•*¨;)-->Le site http://penguincape.org/
(¸.•´ (¸.•´ .•´ : (´¸.•*´¯`*•~--> Wiki --> http://doc.ubuntu-fr.org/tutoriel/personnalisation_cubemodel_wallpaper_dynamique_et_usplash
Hanoi - VIETNAM
Hors ligne
Pedrodelalunabe
Re : [script/python] Nautilus et picasaweb!
Très efficace l'uploader de firefox.
Hors ligne
GNU-max
Re : [script/python] Nautilus et picasaweb!
J'ai repris le script de FTG (merci bcp à lui, j'ai pas changé grand chose) et j'ai ajouté une interface avec zenity (grâce au code de PyZenity de Brian Ramos). J'ai jamais fait de Python alors soyez indulgent.
L'essentiel du code est à la fin.
# -*- coding: utf-8 -*-
# Envoi de photos sur picasaweb
# Dépend de :
# gdata [ à télécharger sur http://code.google.com/p/gdata-python-client/downloads/list et installer - cf. INSTALL.TXT - ]
# nautilus-actions
# zenity
# Dans Nautilus Action rentrer
# Chemin : /usr/bin/python </chemni/vers/script>
# Parametres : %M
# Conditions :
# Types Mime : image/*
# Cocher : Apparaît si la selection contient plusieurs fichiers ou dossiers
#
######-PyZenity-##########
#Afin de ne pas avoir à télécharger et installer le code de PyZenity, je l'ai reproduis en partie ici.
######################################################################################################
# Name: iPyZenity.py
# Author: Brian Ramos
# Created: 10/17/2005
# Revision Information:
# $Date: $
# $Revision: $
# $Author: bramos $
#
# Licence: MIT Licence
#
# Copyright (c) 2005 Brian Ramos
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
################################################################################
from datetime import date
from subprocess import Popen, PIPE
from itertools import chain
from os import path
__all__ = ['GetText','Question', 'Warning', 'ErrorMessage', 'Progress','List' ]
zen_exec = 'zenity'
def run_zenity(type, *args):
return Popen([zen_exec, type] + list(args), stdin=PIPE, stdout=PIPE)
def List(column_names, title=None, boolstyle=None, editable=False,
select_col=None, sep='|', data=[]):
"""Present a list of items to select.
This will raise a Zenity List Dialog populated with the colomns and rows
specified and return either the cell or row that was selected or None if
the user hit cancel.
column_names - A tuple or list containing the names of the columns.
title - The title of the dialog box.
boolstyle - Whether the first columns should be a bool option ("checklist",
"radiolist") or None if it should be a text field.
editable - True if the user can edit the cells.
select_col - The column number of the selected cell to return or "ALL" to
return the entire row.
sep - Token to use as the row separator when parsing Zenity's return.
Cells should not contain this token.
data - A list or tuple of tuples that contain the cells in the row. The
size of the row's tuple must be equal to the number of columns."""
args = []
for column in column_names:
args.append('--column=%s' % column)
if title:
args.append('--title=%s' % title)
if boolstyle:
if not (boolstyle == 'checklist' or boolstyle == 'radiolist'):
raise ValueError('"%s" is not a proper boolean column style.'
% boolstyle)
args.append('--' + boolstyle)
if editable:
args.append('--editable')
if select_col:
args.append('--print-column=%s' % select_col)
if sep != '|':
args.append('--separator=%s' % sep)
for datum in chain(*data):
args.append(str(datum))
p = run_zenity('--list', *args)
if p.wait() == 0:
return p.stdout.read().strip().split(sep)
def ErrorMessage(text):
"""Show an error message dialog to the user.
This will raise a Zenity Error Dialog with a description of the error.
text - A description of the error."""
run_zenity('--error', '--text=%s' % text).wait()
def Question(text):
"""Ask the user a question.
This will raise a Zenity Question Dialog that will present the user with an
OK/Cancel dialog box. It returns True if the user clicked OK; False on
Cancel.
text - The question to ask."""
return run_zenity('--question', '--text=%s' % text).wait() == 0
def Warning(text):
"""Show a warning message dialog to the user.
This will raise a Zenity Warning Dialog with a description of the warning.
It returns True if the user clicked OK; False on cancel.
text - A description of the warning."""
return run_zenity('--warning', '--text=%s' % text).wait() == 0
def Progress(text='', percentage=0, auto_close=False, pulsate=False):
"""Show a progress dialog to the user.
This will raise a Zenity Progress Dialog. It returns a callback that
accepts two arguments. The first is a numeric value of the percent
complete. The second is a message about the progress.
NOTE: This function sends the SIGHUP signal if the user hits the cancel
button. You must connect to this signal if you do not want your
application to exit.
text - The initial message about the progress.
percentage - The initial percentage to set the progress bar to.
auto_close - True if the dialog should close automatically if it reaches
100%.
pulsate - True is the status should pulsate instead of progress."""
args = []
if text:
args.append('--text=%s' % text)
if percentage:
args.append('--percentage=%s' % percentage)
if auto_close:
args.append('--auto-close=%s' % auto_close)
if pulsate:
args.append('--pulsate=%s' % pulsate)
p = Popen([zen_exec, '--progress'] + args, stdin=PIPE, stdout=PIPE)
def update(percent, message=''):
if type(percent) == float:
percent = int(percent * 100)
p.stdin.write(str(percent) + '\n')
if message:
p.stdin.write('# %s\n' % message)
return p.returncode
return update
def GetText(text='', entry_text='', password=False):
"""Get some text from the user.
This will raise a Zenity Text Entry Dialog. It returns the text the user
entered or None if the user hit cancel.
text - A description of the text to enter.
entry_text - The initial value of the text entry box.
password - True if text entered should be hidden by stars."""
args = []
if text:
args.append('--text=%s' % text)
if entry_text:
args.append('--entry-text=%s' % entry_text)
if password:
args.append('--hide-text')
p = run_zenity('--entry', *args)
if p.wait() == 0:
return p.stdout.read()[:-1]
########################################################
#####-END of PyZenity-######
import sys
import gdata.photos.service
#import PyZenity
#import bz2
#Paramètres : possibilité de les rentrer en dur
email=GetText(text='Email', entry_text='@gmail.com', password=False)
password=GetText(text='Mot de passe', entry_text='Picasa', password=True)
#key=...
########-Fonction d'envoi des photos-########
def send_photo(album):
album_url = '/data/feed/api/user/%s/album/%s' % ('default', album)
update=Progress(text='Envoi des photos ...', percentage=0, auto_close=False, pulsate=False)
percent=0
for i in range(len(sys.argv)-1):
text='Envoi des photos ... ('+str(i+1)+'/'+str(len(sys.argv)-1)+')'
print str(percent)
update(percent,text)
entry = gd_client.InsertPhotoSimple(album_url, 'New Photo','', sys.argv[i+1], content_type='image/jpeg')
percent=int(float(i+1)/(len(sys.argv)-1)*100)
#############################################
#Connection à picasaweb
gd_client = gdata.photos.service.PhotosService()
gd_client.email = email
#gd_client.password = bz2.decompress(key)
gd_client.password = password
gd_client.source = 'exampleCo-exampleApp-1'
try:
gd_client.ProgrammaticLogin()
except gdata.service.CaptchaRequired:
# print('Required Captcha')
ErrorMessage('Required Captcha')
except gdata.service.BadAuthentication:
# print('Mauvaise authentification')
ErrorMessage('Mauvaise authentification')
except gdata_client.Error:
# print('Probleme de Login')
ErrorMessage('Probleme de Login')
else:
nouvelalbum=Question("Creer un nouvel album ?")
if nouvelalbum==True :
nom_album=GetText(text='Nom de l\'album (sans espaces): ', entry_text='Nouvel_album', password=False)
# Verification si l'album existe deja
feed = gd_client.GetUserFeed(user="default")
for entry in feed.entry:
while nom_album.lower()==str(entry.title.text).lower():
Warning("Cet album existe deja, veuillez entrer un autre nom !")
nom_album=GetText(text='Nom de l\'album (sans espaces): ', entry_text='Nouvel_album_2', password=False)
#Permissions sur l'album
acces="private"
#Crée l'album
entry = gd_client.InsertAlbum(nom_album, summary='This is an album', access=acces)
#Envoi des photos
send_photo(nom_album)
else:
# Choisir un album
feed = gd_client.GetUserFeed(user="default")
i=0
liste=()
for entry in feed.entry:
i=i+1
liste = liste + (entry.title.text,)
nom_album=(List(('Album',), title=None, boolstyle=None, editable=False, select_col=None, sep='|', data=[liste]))[0]
#Envoi des photos
send_photo(nom_album)
Dernière modification par GNU-max (Le 18/07/2009, à 16:39)
Hors ligne
GNU-max
Re : [script/python] Nautilus et picasaweb!
J'ai fait aussi un script bash qui permet de télécharger un album de picasaweb en cliquant sur «Télécharger vers picasa» depuis l'interface web.
Désolé pour la longueur du script précédent.
#! /bin/bash
# Script de téléchargement d'un album Picasa à partir de son uri picasa://
# Equivalent à «Télécharger avec picasa» sur picasaweb
#.................................................
# Dépends de : Zenity, plugin picasa pour firefox (npPicasa3.so) dispo dans le paquet .deb de Picasa 3 for linux
#--1--
# Copier npPicasa3.so dans les dossiers de plugins firefox :
#...................................................
# sudo cp npPicasa3.so /usr/lib/mozilla/plugins/
# sudo ln -s /usr/lib/mozilla/plugins/npPicasa3.so /usr/lib/firefox/plugins/npPicasa3.so
# sudo ln -s /usr/lib/mozilla/plugins/npPicasa3.so /usr/lib/firefox-addons/plugins/npPicasa3.so
#...................................................
#Verifier le chargement du plugins (taper about:plugins dans firefox)
#--2--
# Configurer Firefox [adapter le chemin vers le script]
#...................................................
# path=$(ls -d /home/$USER/.mozilla/firefox/*.default)
# echo -e "user_pref(\"network.protocol-handler.app.picasa\", \"/home/$USER/picasa_down.sh\");\nuser_pref(\"network.protocol-handler.external.picasa\", true);$" > $path/user.js
#....................................................
rss_link=$(
echo $1 | \
sed "
s#picasa://downloadfeed/?url=##
s/%25/%/g
s/%21/!/g
s/%23/#/g
s/%24/\$/g
s/%26/\&/g
s/%27/'\''/g
s/%28/(/g
s/%29/)/g
s/%2A/\*/g
s/%2B/+/g
s/%2C/,/g
s/%2D/-/g
s/%2E/\./g
s/%2F/\//g
s/%3A/:/g
s/%3B/;/g
s/%3D/=/g
s/%3F/?/g
s/%40/@/g
s/%5B/\[/g
s/%5C/\\\/
s/%5D/\]/g
s/%5E/\^/g
s/%5F/_/g
s/%60/\`/g
s/%7B/{/g
s/%7C/|/g
s/%7D/}/g
s/%7E/~/g
")
DOSSIER=`zenity --file-selection --title="Sélectionnez un dossier de destination" --directory --filename=/home/$USER/`
if [ ! "$DOSSIER" ]
then exit 1
else
wget -q -O - "$rss_link" |
sed -e 's/<pheed:imgsrc>/\n/g ; s/<\/pheed:imgsrc>/\n/g' |
grep -E '^http' |sed '1d' > /tmp/picasa_down
Npics=$(cat /tmp/picasa_down | wc -l)
j=1
(
echo "#Téléchargement de l'album ..."
for i in $(cat /tmp/picasa_down)
do
echo "#Téléchargement de l'album : photo $j/$Npics."
echo "scale=2 ; $j/$Npics*100"| bc
j=$((j+1))
(pidof zenity >/dev/null) && wget -q --directory-prefix="$DOSSIER" "$i"
done
echo "#Terminé"
)| zenity --progress --title="Picasa" --percentage=0 --auto-kill --width=400
fi
exit 0
[Edit 10/10/09] Ajout de guillemets à $DOSSIER pour gérer les espaces dans les noms de dossier.
Dernière modification par GNU-max (Le 10/10/2009, à 09:04)
Hors ligne
lylambda
Re : [script/python] Nautilus et picasaweb!
Salut GNU-max,
Tes scripts adaptés de celui de FTG sont exactement ce que je cherche. J'utilise jBrout pour gérer mes photos, ce logiciel étant parfait niveau tagage. Malheureusement le plugin d'export sur picasaweb ne fonctionne plus sur mon système dernièrement.
[Pour info, j'obtiens ce message d'erreur : ]
Erreur d'upload : 'PicasaWeb' object has no attribute '_PrepareConnection'
Le 1er scripts seraient la solution idéale. Néanmoins, ma 1 ère tentative n'a aboutit qu'à un échec :
# Dépend de : gdata, nautilus-actions, zenity--> Aprés vérification sur synaptic, j'ai bien ces paquets sur mon ubuntu
# Dans Nautilus Action rentrer
# Chemin : /usr/bin/python </chemni/vers/script>
# Parametres : %M
# Conditions :
# Types Mime : image/*
# Cocher : Apparaît si la selection contient plusieurs fichiers ou dossiers--> j'ai créé une nouvelle action selon les indications ci-dessus (en mettant évidement mon propre chemin de script, celui-ci étant exécutable)
Au final, l'intitulé de l'action apparait bien lorsque je clique droit dans Nautilus mais rien ne se passe lorsque je tente de l'activer.
Aurais-je oublié un élément important ?
Dernière modification par lylambda (Le 04/07/2009, à 13:43)
Hors ligne
GNU-max
Re : [script/python] Nautilus et picasaweb!
Salut lylambda,
Désolé pour la réponse tardive, je ne passe pas souvent sur le forum.
En fait le paquet gdata n'est pas suffisant, il faut installer gdata manuellement comme l'a décrit FTG :
Une fois ces trois paquets installés, allez voir du côté de ce lien:
http://code.google.com/p/gdata-python-c … loads/list et telechargez la derniere version de
gdate-py dans un endroit de votre partition /home/user. Décompresser avec la commande tar xvf puis bien lire INSTALL.TXT ca vaut le coup! Pour les plus préssés d'entre vous lancez tout de suite
python setup.py
en root. Dans l'INSTALL.TXT il est bien indiqué comment tester si l'installation a bien fonctionné!
Merci d'avoir relevé ce point (je modifie la note d'installation en conséquence). J'espère que c'est ça.
Dernière modification par GNU-max (Le 18/07/2009, à 16:34)
Hors ligne
lylambda
Re : [script/python] Nautilus et picasaweb!
Merci beaucoup pour le retour GNU-max !
Effectivement, si c'est une dépendance qui n'est pas à jour, cela explique le non-fonctionnement du script
J'ai tenté de compiler gdata-2.0.0 comme indiquer mais apparemment je manque encore de connaissance.
Quand je tape dans mon répertoire de décompression
sudo python setup.py
cela ne me donne que
/usr/lib/python2.6/distutils/dist.py:266: UserWarning: Unknown distribution option: 'install_requires'
warnings.warn(msg)
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: no commands supplied
Par contre taper
sudo python setup.py install
à plus d'effet avec comme résultat
/usr/lib/python2.6/distutils/dist.py:266: UserWarning: Unknown distribution option: 'install_requires'
warnings.warn(msg)
running install
running build
running build_py
creating build
creating build/lib.linux-i686-2.6
creating build/lib.linux-i686-2.6/atom
copying src/atom/http.py -> build/lib.linux-i686-2.6/atom
copying src/atom/data.py -> build/lib.linux-i686-2.6/atom
copying src/atom/mock_service.py -> build/lib.linux-i686-2.6/atom
copying src/atom/http_core.py -> build/lib.linux-i686-2.6/atom
copying src/atom/mock_http_core.py -> build/lib.linux-i686-2.6/atom
copying src/atom/core.py -> build/lib.linux-i686-2.6/atom
copying src/atom/client.py -> build/lib.linux-i686-2.6/atom
copying src/atom/token_store.py -> build/lib.linux-i686-2.6/atom
copying src/atom/http_interface.py -> build/lib.linux-i686-2.6/atom
copying src/atom/service.py -> build/lib.linux-i686-2.6/atom
copying src/atom/auth.py -> build/lib.linux-i686-2.6/atom
copying src/atom/url.py -> build/lib.linux-i686-2.6/atom
copying src/atom/__init__.py -> build/lib.linux-i686-2.6/atom
copying src/atom/mock_http.py -> build/lib.linux-i686-2.6/atom
creating build/lib.linux-i686-2.6/gdata
copying src/gdata/data.py -> build/lib.linux-i686-2.6/gdata
copying src/gdata/gauth.py -> build/lib.linux-i686-2.6/gdata
copying src/gdata/urlfetch.py -> build/lib.linux-i686-2.6/gdata
copying src/gdata/test_config.py -> build/lib.linux-i686-2.6/gdata
copying src/gdata/sample_util.py -> build/lib.linux-i686-2.6/gdata
copying src/gdata/client.py -> build/lib.linux-i686-2.6/gdata
copying src/gdata/service.py -> build/lib.linux-i686-2.6/gdata
copying src/gdata/auth.py -> build/lib.linux-i686-2.6/gdata
copying src/gdata/test_config_template.py -> build/lib.linux-i686-2.6/gdata
copying src/gdata/test_data.py -> build/lib.linux-i686-2.6/gdata
copying src/gdata/__init__.py -> build/lib.linux-i686-2.6/gdata
creating build/lib.linux-i686-2.6/gdata/calendar
copying src/gdata/calendar/service.py -> build/lib.linux-i686-2.6/gdata/calendar
copying src/gdata/calendar/__init__.py -> build/lib.linux-i686-2.6/gdata/calendar
creating build/lib.linux-i686-2.6/gdata/base
copying src/gdata/base/service.py -> build/lib.linux-i686-2.6/gdata/base
copying src/gdata/base/__init__.py -> build/lib.linux-i686-2.6/gdata/base
creating build/lib.linux-i686-2.6/gdata/spreadsheet
copying src/gdata/spreadsheet/service.py -> build/lib.linux-i686-2.6/gdata/spreadsheet
copying src/gdata/spreadsheet/text_db.py -> build/lib.linux-i686-2.6/gdata/spreadsheet
copying src/gdata/spreadsheet/__init__.py -> build/lib.linux-i686-2.6/gdata/spreadsheet
creating build/lib.linux-i686-2.6/gdata/apps
copying src/gdata/apps/service.py -> build/lib.linux-i686-2.6/gdata/apps
copying src/gdata/apps/__init__.py -> build/lib.linux-i686-2.6/gdata/apps
creating build/lib.linux-i686-2.6/gdata/apps/emailsettings
copying src/gdata/apps/emailsettings/service.py -> build/lib.linux-i686-2.6/gdata/apps/emailsettings
copying src/gdata/apps/emailsettings/__init__.py -> build/lib.linux-i686-2.6/gdata/apps/emailsettings
creating build/lib.linux-i686-2.6/gdata/apps/migration
copying src/gdata/apps/migration/service.py -> build/lib.linux-i686-2.6/gdata/apps/migration
copying src/gdata/apps/migration/__init__.py -> build/lib.linux-i686-2.6/gdata/apps/migration
creating build/lib.linux-i686-2.6/gdata/apps/groups
copying src/gdata/apps/groups/service.py -> build/lib.linux-i686-2.6/gdata/apps/groups
copying src/gdata/apps/groups/__init__.py -> build/lib.linux-i686-2.6/gdata/apps/groups
creating build/lib.linux-i686-2.6/gdata/docs
copying src/gdata/docs/service.py -> build/lib.linux-i686-2.6/gdata/docs
copying src/gdata/docs/__init__.py -> build/lib.linux-i686-2.6/gdata/docs
creating build/lib.linux-i686-2.6/gdata/codesearch
copying src/gdata/codesearch/service.py -> build/lib.linux-i686-2.6/gdata/codesearch
copying src/gdata/codesearch/__init__.py -> build/lib.linux-i686-2.6/gdata/codesearch
creating build/lib.linux-i686-2.6/gdata/books
copying src/gdata/books/service.py -> build/lib.linux-i686-2.6/gdata/books
copying src/gdata/books/__init__.py -> build/lib.linux-i686-2.6/gdata/books
creating build/lib.linux-i686-2.6/gdata/photos
copying src/gdata/photos/service.py -> build/lib.linux-i686-2.6/gdata/photos
copying src/gdata/photos/__init__.py -> build/lib.linux-i686-2.6/gdata/photos
creating build/lib.linux-i686-2.6/gdata/exif
copying src/gdata/exif/__init__.py -> build/lib.linux-i686-2.6/gdata/exif
creating build/lib.linux-i686-2.6/gdata/geo
copying src/gdata/geo/__init__.py -> build/lib.linux-i686-2.6/gdata/geo
creating build/lib.linux-i686-2.6/gdata/media
copying src/gdata/media/__init__.py -> build/lib.linux-i686-2.6/gdata/media
creating build/lib.linux-i686-2.6/gdata/contacts
copying src/gdata/contacts/service.py -> build/lib.linux-i686-2.6/gdata/contacts
copying src/gdata/contacts/__init__.py -> build/lib.linux-i686-2.6/gdata/contacts
creating build/lib.linux-i686-2.6/gdata/youtube
copying src/gdata/youtube/service.py -> build/lib.linux-i686-2.6/gdata/youtube
copying src/gdata/youtube/__init__.py -> build/lib.linux-i686-2.6/gdata/youtube
creating build/lib.linux-i686-2.6/gdata/webmastertools
copying src/gdata/webmastertools/service.py -> build/lib.linux-i686-2.6/gdata/webmastertools
copying src/gdata/webmastertools/__init__.py -> build/lib.linux-i686-2.6/gdata/webmastertools
creating build/lib.linux-i686-2.6/gdata/blogger
copying src/gdata/blogger/data.py -> build/lib.linux-i686-2.6/gdata/blogger
copying src/gdata/blogger/client.py -> build/lib.linux-i686-2.6/gdata/blogger
copying src/gdata/blogger/service.py -> build/lib.linux-i686-2.6/gdata/blogger
copying src/gdata/blogger/__init__.py -> build/lib.linux-i686-2.6/gdata/blogger
creating build/lib.linux-i686-2.6/gdata/alt
copying src/gdata/alt/appengine.py -> build/lib.linux-i686-2.6/gdata/alt
copying src/gdata/alt/app_engine.py -> build/lib.linux-i686-2.6/gdata/alt
copying src/gdata/alt/__init__.py -> build/lib.linux-i686-2.6/gdata/alt
creating build/lib.linux-i686-2.6/gdata/oauth
copying src/gdata/oauth/rsa.py -> build/lib.linux-i686-2.6/gdata/oauth
copying src/gdata/oauth/__init__.py -> build/lib.linux-i686-2.6/gdata/oauth
creating build/lib.linux-i686-2.6/gdata/tlslite
copying src/gdata/tlslite/SessionCache.py -> build/lib.linux-i686-2.6/gdata/tlslite
copying src/gdata/tlslite/Session.py -> build/lib.linux-i686-2.6/gdata/tlslite
copying src/gdata/tlslite/errors.py -> build/lib.linux-i686-2.6/gdata/tlslite
copying src/gdata/tlslite/FileObject.py -> build/lib.linux-i686-2.6/gdata/tlslite
copying src/gdata/tlslite/X509CertChain.py -> build/lib.linux-i686-2.6/gdata/tlslite
copying src/gdata/tlslite/mathtls.py -> build/lib.linux-i686-2.6/gdata/tlslite
copying src/gdata/tlslite/api.py -> build/lib.linux-i686-2.6/gdata/tlslite
copying src/gdata/tlslite/BaseDB.py -> build/lib.linux-i686-2.6/gdata/tlslite
copying src/gdata/tlslite/TLSRecordLayer.py -> build/lib.linux-i686-2.6/gdata/tlslite
copying src/gdata/tlslite/SharedKeyDB.py -> build/lib.linux-i686-2.6/gdata/tlslite
copying src/gdata/tlslite/HandshakeSettings.py -> build/lib.linux-i686-2.6/gdata/tlslite
copying src/gdata/tlslite/Checker.py -> build/lib.linux-i686-2.6/gdata/tlslite
copying src/gdata/tlslite/X509.py -> build/lib.linux-i686-2.6/gdata/tlslite
copying src/gdata/tlslite/constants.py -> build/lib.linux-i686-2.6/gdata/tlslite
copying src/gdata/tlslite/TLSConnection.py -> build/lib.linux-i686-2.6/gdata/tlslite
copying src/gdata/tlslite/messages.py -> build/lib.linux-i686-2.6/gdata/tlslite
copying src/gdata/tlslite/__init__.py -> build/lib.linux-i686-2.6/gdata/tlslite
copying src/gdata/tlslite/VerifierDB.py -> build/lib.linux-i686-2.6/gdata/tlslite
creating build/lib.linux-i686-2.6/gdata/Crypto
copying src/gdata/Crypto/test.py -> build/lib.linux-i686-2.6/gdata/Crypto
copying src/gdata/Crypto/__init__.py -> build/lib.linux-i686-2.6/gdata/Crypto
creating build/lib.linux-i686-2.6/gdata/Crypto/Cipher
copying src/gdata/Crypto/Cipher/__init__.py -> build/lib.linux-i686-2.6/gdata/Crypto/Cipher
creating build/lib.linux-i686-2.6/gdata/Crypto/Hash
copying src/gdata/Crypto/Hash/HMAC.py -> build/lib.linux-i686-2.6/gdata/Crypto/Hash
copying src/gdata/Crypto/Hash/MD5.py -> build/lib.linux-i686-2.6/gdata/Crypto/Hash
copying src/gdata/Crypto/Hash/SHA.py -> build/lib.linux-i686-2.6/gdata/Crypto/Hash
copying src/gdata/Crypto/Hash/__init__.py -> build/lib.linux-i686-2.6/gdata/Crypto/Hash
creating build/lib.linux-i686-2.6/gdata/Crypto/Protocol
copying src/gdata/Crypto/Protocol/Chaffing.py -> build/lib.linux-i686-2.6/gdata/Crypto/Protocol
copying src/gdata/Crypto/Protocol/__init__.py -> build/lib.linux-i686-2.6/gdata/Crypto/Protocol
copying src/gdata/Crypto/Protocol/AllOrNothing.py -> build/lib.linux-i686-2.6/gdata/Crypto/Protocol
creating build/lib.linux-i686-2.6/gdata/Crypto/PublicKey
copying src/gdata/Crypto/PublicKey/pubkey.py -> build/lib.linux-i686-2.6/gdata/Crypto/PublicKey
copying src/gdata/Crypto/PublicKey/ElGamal.py -> build/lib.linux-i686-2.6/gdata/Crypto/PublicKey
copying src/gdata/Crypto/PublicKey/DSA.py -> build/lib.linux-i686-2.6/gdata/Crypto/PublicKey
copying src/gdata/Crypto/PublicKey/__init__.py -> build/lib.linux-i686-2.6/gdata/Crypto/PublicKey
copying src/gdata/Crypto/PublicKey/RSA.py -> build/lib.linux-i686-2.6/gdata/Crypto/PublicKey
copying src/gdata/Crypto/PublicKey/qNEW.py -> build/lib.linux-i686-2.6/gdata/Crypto/PublicKey
creating build/lib.linux-i686-2.6/gdata/Crypto/Util
copying src/gdata/Crypto/Util/randpool.py -> build/lib.linux-i686-2.6/gdata/Crypto/Util
copying src/gdata/Crypto/Util/test.py -> build/lib.linux-i686-2.6/gdata/Crypto/Util
copying src/gdata/Crypto/Util/RFC1751.py -> build/lib.linux-i686-2.6/gdata/Crypto/Util
copying src/gdata/Crypto/Util/number.py -> build/lib.linux-i686-2.6/gdata/Crypto/Util
copying src/gdata/Crypto/Util/__init__.py -> build/lib.linux-i686-2.6/gdata/Crypto/Util
creating build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/Cryptlib_AES.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/Cryptlib_TripleDES.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/keyfactory.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/dateFuncs.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/PyCrypto_AES.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/PyCrypto_RSAKey.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/Python_RSAKey.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/RSAKey.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/codec.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/AES.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/hmac.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/OpenSSL_AES.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/Cryptlib_RC4.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/cryptomath.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/OpenSSL_RSAKey.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/compat.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/TripleDES.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/OpenSSL_TripleDES.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/Python_RC4.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/Python_AES.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/PyCrypto_RC4.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/xmltools.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/RC4.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/OpenSSL_RC4.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/__init__.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/PyCrypto_TripleDES.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/ASN1Parser.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/cipherfactory.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/jython_compat.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
copying src/gdata/tlslite/utils/rijndael.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils
creating build/lib.linux-i686-2.6/gdata/tlslite/integration
copying src/gdata/tlslite/integration/IMAP4_TLS.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration
copying src/gdata/tlslite/integration/TLSAsyncDispatcherMixIn.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration
copying src/gdata/tlslite/integration/IntegrationHelper.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration
copying src/gdata/tlslite/integration/SMTP_TLS.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration
copying src/gdata/tlslite/integration/POP3_TLS.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration
copying src/gdata/tlslite/integration/TLSSocketServerMixIn.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration
copying src/gdata/tlslite/integration/TLSTwistedProtocolWrapper.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration
copying src/gdata/tlslite/integration/HTTPTLSConnection.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration
copying src/gdata/tlslite/integration/AsyncStateMachine.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration
copying src/gdata/tlslite/integration/ClientHelper.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration
copying src/gdata/tlslite/integration/__init__.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration
copying src/gdata/tlslite/integration/XMLRPCTransport.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration
creating build/lib.linux-i686-2.6/gdata/health
copying src/gdata/health/service.py -> build/lib.linux-i686-2.6/gdata/health
copying src/gdata/health/__init__.py -> build/lib.linux-i686-2.6/gdata/health
creating build/lib.linux-i686-2.6/gdata/analytics
copying src/gdata/analytics/service.py -> build/lib.linux-i686-2.6/gdata/analytics
copying src/gdata/analytics/__init__.py -> build/lib.linux-i686-2.6/gdata/analytics
creating build/lib.linux-i686-2.6/gdata/finance
copying src/gdata/finance/service.py -> build/lib.linux-i686-2.6/gdata/finance
copying src/gdata/finance/__init__.py -> build/lib.linux-i686-2.6/gdata/finance
running install_lib
running install_egg_info
Removing /usr/local/lib/python2.6/dist-packages/gdata-2.0.0.egg-info
Writing /usr/local/lib/python2.6/dist-packages/gdata-2.0.0.egg-info
Mais ce ne doit pas être la solution vu qu'au final le script ne s'active toujours pas lorsque je le sélectionne par "clique-droit" dans Nautilus. Bref, je fais une pause pour ce soir et je me replongerais dans l'INSTALL.TXT un peu plus tard.
En tout cas, si tu as tout lu jusqu'ici, tu es décidément serviable (et surtout courageux ;-) !
PS: si un petit paquet deb du dernier gdata traine dans le coin, dis lui que je lui offre un CDI illico :-p
Hors ligne
GNU-max
Re : [script/python] Nautilus et picasaweb!
Lorsque j'ai fait le script c'était gdata 1.3.3 mais je ne pense pas que ce soit ça. Dans l'INSTALL.TXT il y a une procédure pour tester l'installation : lancer ./tests/run_data_tests.py
Essaye d'executer le script en ligne de commande pour voir si il y a un message d'erreur.
python picasa_export.py <une image>
Hors ligne
lylambda
Re : [script/python] Nautilus et picasaweb!
Désolé de l'absence.
Dans mon répertoire de compilation, j'avais bien fait le test
./tests/run_data_tests.py
Le résultat a était positif d'après l'INSTALL.
Par contre
python picasa_export.py <une image>
me renvois un message d'erreur, donc je suppose que ça vient de ma manière de rentrer l'action dans Nautilus.
Comme j'ai bloqué à ce niveau, j'ai testé l'extension firefox "fire/universal uploader" indiqué précédemment par Axelap.
Il me convient parfaitement mais cela me frustre de ne pas avoir réussi à faire fonctionner ton script >_<.
Merci encore et promis, je referais un essai lorsque mes compétences se seront améliorées !
Hors ligne
GNU-max
Re : [script/python] Nautilus et picasaweb!
C'est bien si t'as trouvé quelque chose qui te convient. Si tu décides de remettre les mains dans le cambouis, n'hésite pas. J'essayerais de t'aider du mieux que je peux.
P.S.
Par contre
python picasa_export.py <une image>
me renvois un message d'erreur, donc je suppose que ça vient de ma manière de rentrer l'action dans Nautilus.
Au contraire, cette commande permet d'exécuter le script sans utiliser nautilus-actions, donc de s'affranchir des éventuelles erreurs liées à celui-ci. Par contre d'une manière générale, si on te demande d'essayer une commande c'est justement pour voir quelle erreur(s) s'affiche(nt)
Je n'exlcus pas qu'il s'agissent d'une erreur de ma part.
Dernière modification par GNU-max (Le 02/08/2009, à 21:11)
Hors ligne
Qid
Re : [script/python] Nautilus et picasaweb!
Salut. Non ça intéresse sûrement personne car Picasa c'est propriétaire et on préfère F-Spot qui fait très bien le boulot.
au depart j'avais picasa sur ubuntu et quand je suis passé au 3
j'ai eu des mauvaises surprise alors je l'ai désinstallé car entre temp en plus
j'avais découvert que f-spot effectivement faisait aussi bine le boulot
(pas moyen de mettre de transfere en standby mais bon)
enfin voila par contre c'est vrais que
la gestion de fspot ne me plaisant pas dutout
je ne m'en sert vraiement que pour les transfere vers picasa
et dois le revider à chaque fois ... bref faudra que je teste ton truc
mais la méthode d'install me plait pas trop
"GNU/Linux c'est que du bon mais M$ Windows c'est pas si mal"
bientôt 1 Gigabyte P35G W$ & UBUNTU pour moi + Ubuntu-gnome & KLXUbuntu + mint mate & cinamon pour démos1 Zalman de 120Go pour le GUL dont je suis le dépanneur de référence1 tablettes ASUS non rootée : Android 4.2.2 | doc.ubuntu-fr/Qid
Hors ligne
YvanD
Re : [script/python] Nautilus et picasaweb!
Ce serait super de créer un clone (enfin de s'inspirer) de nautilus-flirck-uploader mais pour picasa.
Hors ligne
elephant
Re : [script/python] Nautilus et picasaweb!
bonjour à tous
Je ne suis pas sûre que le problème que je rencontre est le même que ceux évoqués plus haut : depuis plus d'un an, j'ai une galerie picasa gratuite qui me sert de vitrine pour exposer mes peintures. J'ai donc besoin de poster des photos dessus très régulièrement. Or, impossible de faire ça depuis mon ordi (sous Ubuntu). je dois aller dans des internet café.
kafkaïen : je clique sur
"transférer des fichiers"
je tombe sur
"Picasa Albums Web ne comporte pas encore de programme de transfert propre à Linux. Pour tenter de transférer des photos avec notre formulaire de transfert via le Web, cliquez sur le bouton Transférer des photos, à droite."
J'appuie donc, on me dit de me connecter (alors que je suis connectée), je clique donc sur "me connecter"
et je tombe sur
"La fonctionnalité que vous avez demandée est actuellement indisponible. Veuillez réessayer ultérieurement."
J'ai lu vos échanges, mais je suis une femme des cavernes : je ne m'y connais pas suffisamment en informatiques pour engager les procédures que vous décrivez.
en résumé, je cherche un moyen compréhensible pour seulement exporter des fichiers jpeg depuis mon ordi vers Picasa.
des suggestions ?
merci
Hors ligne
GNU-max
Re : [script/python] Nautilus et picasaweb!
Bonjour,
Vous avez bien fait de lire les sujets du forum sur picasa. Mais peut-être auriez vous dû créer un nouveau sujet car celui-ci est ancien et contient des informations sûrement obsolètes.
Je n'utilise pas Picasa et je ne peux pas vous aider sur votre problème avec l'interface web de Picasa.
Pour utiliser Picasa avec Ubuntu vous pouvez essayer les logiciels Shotwell (normalement installé par défaut sur ubuntu) ou Conduit. (source : askubuntu)
Hors ligne
En ligne
|
mol1
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
Un lien vers une esquisse de musique :
http://ubuntuone.com/7RqEp9oXkT6K338qog5WlX
Hors ligne
Ypnose
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
La zike est pas mal.
J'aiderai bien mais je suis pas bon codeur C, donc si vous avez des tâches à réaliser, je pourrais peut-être aider.
Dernière modification par Ypnose (Le 22/06/2012, à 15:53)
tshirtman
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
On fait pas du C, on fait du python ^^, mais oui, il y a des trucs qu'un non codeur peut faire
On va sans doute utiliser tiled (http://www.mapeditor.org/) comme editeur de niveau, avec les éléments de tileset qu'on est en train de construire, si tu veux t'essayer au level design (si tu connais les principes d'un tower defense).
Il faudra aussi bosser sur les fichiers décrivants les unités et les vaques d'attaques, je suis en train de travailler a des formats de fichiers basés sur yaml, si tu pense que tu pourrais bosser avec ça pour ajuster les caractéristiques des éléments du jeu.
https://www.stypi.com/tshirtman/yamls
(les données sont à titre d'exemple, le format n'est pas définitif)
sinon de l'aide sur la musique et les graphismes (si tu peut dessiner des insectes en mouvements en pixel art avec une vue a 45° ou un peu plus ce serait génial ^^ mais des textures de décors c'est bien aussi) est toujours possible.
Dernière modification par tshirtman (Le 22/06/2012, à 16:18)
Hors ligne
mol1
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
Une ébauche de fourmi :
Hors ligne
Kanor
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
@tshirtman
J'ai envoyé un commit pour corriger les problèmes d'import.
Mais j'ai quand même un bug quand je lance l'appli
--> python bin/hortus-belli
/usr/lib/python2.7/dist-packages/gi/overrides/Gtk.py:391: Warning: g_object_set_property: construct property "type" for object `Window' can't be set after construction
Gtk.Window.__init__(self, type=type, **kwds)
(hortus-belli:10546): GLib-GIO-ERROR **: Settings schema 'net.launchpad.hortus-belli' is not installed
zsh: trace trap (core dumped) python bin/hortus-belli
J'ai le même bug avec un projet à partir de 0.
Sinon tu a spécifié un template particilier pour quickly git-python-gtk
il faut le télécharger ici
https://github.com/ali1234/quickly-git-templates
et penser à faire un lien symbolique dans le dossier ~/quickly-templates/ (à créer)
du dossier git-python-gtk.
Il semble avoir une variable d’environnement pour régler les chemins à explorer pour obtenir la liste des templates, mais ça ne semble pas fonctionner (cf le man)
Hors ligne
tshirtman
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
yep pour lancer la version quickly du projet il faut faire quickly run.
Hors ligne
Baronsed
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
Un bâtisseur (nain de jardin) :
http://imgur.com/pDcoK,WAVC7,G4zCO,DIcM … 0pUQ,zrxQQ
Le même, en rouge (terminé) :
deschodt.iiens.net/dwarf.tgz
D'autres décors (maj 27/06) :
http://imgur.com/fvneo,u6brb,uRvaD,y0e9 … PD0J,uOzvH
Dernière modification par Baronsed (Le 11/07/2012, à 20:59)
Hors ligne
samυncle
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
Idée pour la version 0
1) L'espace ou on joue est un terrain de 16 * 10 case de 32px (avec un agrandissement x2 pour l'effet pixel)
2) Les fourmis suivent un chemin de terre qui fait 32px de large jusqu'à la destination
3) Une des ressources est de l'eau a aller chercher à la rivière (avec le nain. À noter que celui ci porte beaucoup d'eau (pour éviter d'aller faire 15 fois l'aller et retour)
4) À chaque fourmis tué on reçoit une autre ressource (je sais pas quoi disons que le score monte de 1)
Hello world
Hors ligne
mol1
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
Une version plus recente de la musique se trouve ici :
http://ubuntuone.com/3WAZ95oPdwwDset8iFPd8k
Hors ligne
grim7reaper
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
1) L'espace ou on joue est un terrain de 16 * 10 case de 32px (avec un agrandissement x2 pour l'effet pixel)
Plutôt du 15*10 (1024x640, on retire une bande de 64px sur le côté pour le menu).
@mol1 : Si tu pouvais nous les sortir en ogg ça serait parfait.
Il me semble que les brevets sur le mp3 sont tombés maintenant, mais dans le doute utilise l’ogg on sera sûr de pas avoir de problème (et la compression est meilleure en plus)
Dernière modification par grim7reaper (Le 01/07/2012, à 05:21)
Hors ligne
Grünt
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
Et le jeu ne dépendra pas de codecs proprios sous Debian.
Red flashing lights. I bet they mean something.
Hors ligne
:!pakman
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
@samυncle : Super les textures, j'adore en tout cas !
...
Hors ligne
samυncle
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
Bon alors j'ai ajouté un début de map pour tester et tenter de la charger . On va pouvoir avancer
Concernant la musique je trouve qu'elle devient vite lourde faudrait trouver un moyen de rendre ça mieux, peut être atténuer le trombone (je suis nul en musique hein je suis conscient que c'est un travail énorme de déjà faire ça, faut pas le prendre mal hein ^^)
@samυncle : Super les textures, j'adore en tout cas !
Merci
Là je vais tenter de faire une belle animation d'eau
Hello world
Hors ligne
mol1
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
@ samuncle : tkt je le prens pas mal ... ;-)
c'est vrai qu'atténuer la flûte (et pas le tombone ! :-) ) serait pas mal ... vu qu'elle sert plutôt d'accompagnement ....
Par contre je pourrai pas te tester ça avant jeudi vu que je ne suis pas chez moi en ce moment ...
après je rejoins :!pacman, les textures sont sympas .... Vivement qu'on ait une version jouable !
Dernière modification par mol1 (Le 05/07/2012, à 19:30)
Hors ligne
tshirtman
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
avec l'eau animée et correctement orientée, c'est mieux
edit: en fait c'est moins lourd et plus fluide en ogv
oO, la balise vidéo ne marche qu'en prévisualisation maintenant ?
http://pub.tshirtman.fr/animation_eau.ogv
Dernière modification par tshirtman (Le 03/07/2012, à 17:53)
Hors ligne
Grünt
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
L'eau qui tourne en rond ? Ça descend tout le long du parcours ?
Red flashing lights. I bet they mean something.
Hors ligne
tshirtman
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
C'est un test (et un hommage a M.C Escher on va dire )
Dernière modification par tshirtman (Le 03/08/2012, à 21:18)
Hors ligne
Grünt
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
M.C. Escher est mort aussi ? Mais c'est une hécatombe !
Red flashing lights. I bet they mean something.
Hors ligne
mol1
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
C'était qui M.C.Escher ? Il faisait du kayak ?
Sinon une version un peu moins soulante de la musique est ici : http://ubuntuone.com/4mTbv7dQ2mCLQ4V1ek0cgR (et en .ogg, s'il vous plait )
Dernière modification par mol1 (Le 26/07/2012, à 20:30)
Hors ligne
:!pakman
Re : Hortus belli projet de tower defense (finissons le jeu d'helly)
La texture de l'eau est géniale !
Du boulot de pros
(Oui je fais une fixation sur les textures, le visuel est super )
Edit : j'ai l'impression d'avoir fait un déterrage ?
Dernière modification par :!pakman (Le 03/08/2012, à 21:12)
...
Hors ligne
|
crypto178
Le point sur les codecs (+intégration à firefox)
Je crois qu'un tel sujet est nécessaire, car pour l'instant c'est un peu la jungle.
La diversité est une bonne chose, mais nous devrions essayer, à travers ce sujet, de dégager un guide clair et universel. J'ai moi même quelques idées sur la méthode qui a -selon moi- le plus de sens, mais faute d'avoir une breezy toute neuve sous la main, j'aurais besoin de quelques commentaires pour corriger ce qui va suivre, les erreurs issues de ma mémoire défaillante. Et bien sur, pour ajouter les HOW-TO pour les autres lecteurs multimédia, je ne sais faire que la partie sur Totem.
Le but de ce guide se résume en 3 points :
- Lire toutes les vidéos possibles (formats propriétaires) avec le lecteur multimédia de son choix (pour éviter les débats stériles).
- Pouvoir lire les vidéos realmedia, windows media et quicktime directement dans firefox (+ 1.5 beta).
- Arriver aux deux buts précédents de la manière la plus simple et propre possible, mais aussi ajouter des liens vers des guides pour ceux qui veulent aller plus loin (compilation de mplayer avec gtk2 par exemple).
En guise de bonus, il n'est pas nécessaire d'installer le lecteur propriétaire de realmedia .
Finalement, corriger, compléter et mettre en page le guide puis l'intégrer au wiki.
Note: Certains crient au scandale à la vue d'une ligne de commande, et à l'élitisme débridé à la vue d'un terme technique, j'essaierais donc de proposer une manière de faire graphique en parallèle aux lignes de commandes et/ou un lien vers l'explication des termes techniques.
Note2: J'espère n'avoir pas été trop trollesque sur la description des lecteurs multimédias, n'hésitez pas à suggérer d'autres descriptions.
1. Introduction
Il n'est aujourd'hui pas possible de lire la plupart des fichiers vidéos et audio disponibles sur internet avec une Ubuntu fraîchement installée. Celà ajoute à la confusion d'un nouvel utilisateur de linux, mais rien n'est fait par sadisme ou complaisance dans la complexité, les fichiers ne sont pas lisibles pour des raisons légales et éthiques (les deux, dans ce cas ci, intiment liées).
Les formats dont nous parlons sont des formats dit propriétaires. Leurs auteurs (de grandes sociétés, en général : Apple, Microsoft, Realmedia) ont jugé que le format (et donc, les routines d'encodage et de décodage qui l'accompagne : http://fr.wikipedia.org/wiki/Codec) devait rester "fermé", c'est à dire, que l'utilisation en serait contrôlée, et qu'il serait (en général) impossible d'encoder des fichiers dans ce format sans s'acquitter d'une license, et impossible de les lire sans avoir le codec fourni par l'auteur (ça, en général, gratuitement, mais uniquement pour Windows).
Ubuntu étant distribué à l'échelle mondiale, il est impossible de fournir ces codecs avec le CD d'installation sans compromettre la légalité de la distribution dans certains pays. De plus, ces formats sont peu compatibles avec l'éthique et la philosophie de partage qu'accompagne la distribution.
Il existe d'autres distributions qui distribuent malgré tout ces formats, par exemple, Mepis.
Heureusement, il n'est pas trop difficile d'installer ces formats. Mais la diversité des possibilités rend les choses assez confuses, d'où la présence de ce guide.
Astuce avant de commencer :
Les indications qui vont suivre feront souvent appel au terminal. Pour y avoir accès plus rapidement, il est conseillé d'installer le paquet 'nautilus-open-terminal' pour pouvoir ouvrir une fenêtre de terminal en faisant un clic droit dans n'importe quel dossier ou sur le bureau (pour les utilisateurs de gnome).
Il est aussi vivement recommandé d'activer les dépôts universe et multiverse avant de passer à la suite. Je renvoie pour celà à la page du wiki qui explique en détail la procédure.
Dernière modification par crypto178 (Le 28/11/2005, à 15:31)
Hors ligne
crypto178
Re : Le point sur les codecs (+intégration à firefox)
2. Support des fichiers mp3 :2.1 Introduction :- Pourquoi le mp3 n'est-il pas supporté par défaut sur ubuntu?
Le format mp3 est un format breveté. Dans certains pays (comme les Etats-Unis), celà rend illégal la distribution de lecteurs lisant le format sauf acquittement d'une participation financière au groupe qui détient le brevet (http://www.mp3licensing.com/royalty/index.html). Il est donc impossible et incompatible d'un point de vue éthique, pour une distribution comme ubuntu, de fournir le support du mp3 sur son cd d'installation.
Il est vivement conseillé de passer à un format libre pour ses fichiers musicaux, par exemple le format ogg/vorbis, qui lui restera gratuit et libre (en plus de certains avantages techniques).
2.2 Installation
Il faut installer le paquet 'gstreamer0.8-mad', disponible dans synaptic ou par la commande :
sudo apt-get install gstreamer0.8-mad
2.3 Lecteurs multimedia
2.3.1 Lecteurs simples (liste de lecture):
- XMMS: Si vous venez de windows, vous retrouverez dans XMMS un équivalent assez fidèle à Winamp (il est d'ailleurs compatible avec les skins de winamp). Il supporte un grand nombre de formats (dont le mp3 nativement, sans avoir besoin de gsteamer-mad), est développé depuis longtemps et présente donc -je ne crois pas blasphémer - la solution 'par défaut' pour lire des fichiers audio sur linux.
- Beep-Media-Player: Basé sur XMMS, c'est un choix recommandé pour les utilisateurs de Gnome. Il est mieux intégré à l'interface (utilisation de la bibliothèque GTK) générale de gnome (également compatible avec les skins winamp).
2.3.2 Lecteurs basés sur la gestion d'une bibliothèque:
- Rythmbox: C'est le lecteur par défaut d'ubuntu. Il importe les fichiers audio et les organise dans une bibliothèque. On notera qu'il s'intègre à d'autres programmes et applets gnome, ce qui en fait un bon choix malgré ses fonctionnalités encore un peu réduites par rapport à amarok.
- Amarok: C'est l'équivalent de rythmbox pour le bureau KDE. Très populaire, il permet de gérer de nombreuses informations sur les artistes et albums.
2.3.3 Autres
... (mentionner gnome ou kde)
Dernière modification par crypto178 (Le 02/11/2005, à 00:16)
Hors ligne
crypto178
Re : Le point sur les codecs (+intégration à firefox)
3. Installation des codecs vidéos windows "w32codecs".
Il y a à peu près 557 manières de faire (et je compte encore), je vais aborder la manière manuelle utilisant le dépôt PLF, mais je crois que l'outil EasyUbuntu proposé par Keyes est ici la meilleure solution. Si vous l'utilisez, vous pouvez passer ce chapitre.
3.1 Installation à partir des dépôts Pinguin Liberation Front (PLF)
3.1.1 Ajout des dépôts PLF à la liste des dépôts.
Note: Pour en savoir plus sur les dépôts, allez voir la page du wiki http://wiki.ubuntu-fr.org/installation/depots
Et sur le PLF : http://wiki.ubuntu-fr.org/doc/plf
3.1.1.1 Edition du fichier sources.list
Ce fichier ce trouve dans /etc/apt/sources.list
Ouvrez le avec votre éditeur de choix ou simplement avec gedit via la commande :
sudo gedit /etc/apt/sources.list
Ajoutez les deux lignes suivantes à la fin du fichier :
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
**ces deux lignes sont sujettes à changements, si vous obtenez une erreur à l'étape suivante, référez vous à http://wiki.ubuntu-fr.org/doc/plf pour des liens à jour**
Sauvegardez et entrez ensuite la commande :
sudo apt-get update
3.1.1.2 Installation
Installez le paquet 'w32codecs' par synaptic ou via la commande:
sudo apt-get install w32codecs
3.1.2 Configuration supplémentaire
Le paquet w32codecs distribué par le PLF installe ses fichiers dans /usr/share/codecs, hors, certains (vieux) lecteurs se réfèrent à /usr/lib/win32/ pour trouver leurs codecs.
Solution : Créer un lien symbolique pour que tout le monde puisse s'y retrouver.
Soit la commande :
sudo ln -s /usr/share/codecs /usr/lib/win32
Note: Il est fort possible que ce lien soit déjà créé par le paquet w32codecs.
3.3 En complément...
Je recommande d'en profiter pour installer le paquet 'libdvdcss2' qui permet de lire les DVD encryptés.
Dernière modification par crypto178 (Le 19/11/2005, à 23:36)
Hors ligne
crypto178
Re : Le point sur les codecs (+intégration à firefox)
4. Configuration d'un lecteur:
Ici vous avez le choix:
- Totem: bonne intégration à gnome en général, bonne compatibilité une fois couplé avec xine, bref bon choix pour une ubuntu.
- VLC: un choix qui tient à coeur aux ex-utilisateurs de windows, pas besoin de s'encombrer de codecs.
- Mplayer: un player un peu plus musclé mais moins sympathique au niveau de l'interface (skins dispo ici http://themes.freshmeat.net/).
- ... Un lecteur KDE ?
4.1 Installation de Totem-xine :
4.1.1 Introduction
Totem est le lecteur par défaut de gnome. L'avantage de le faire fonctionner avec les w32codecs est qu'il est aussi appelé pour créer les aperçus dans nautilus.
Pourquoi totem-xine? xine améliore grandement les capacités de lecture de Totem (compatibilité DVD)
4.1.2 Installation
Totem est déjà installé par défaut sur Ubuntu.
Nous allons ajouter le paquet 'totem-xine', passez par synaptic ou tapez la ligne de commande suivante:
sudo apt-get install totem-xine
4.2 VLC
4.2.1 Installation
- détailler ici l'installation 'de base' sur une ubuntu
4.2.2 Avancé
- compiler une version plus récente, support de windows media, etc.
Peut-être tout simplement fournir un .deb?4.3 Mplayer
Pas nécessaire pour le fonctionnement du plugin, toutes les dépendances sont gérées à l'installation du plugin.
4.2.1 Installation
- détailler ici l'installation 'de base' sur une ubuntu
4.2.2 Avancé
- compiler mplayer avec un gui gtk2
voir guide ici : http://ubuntuforums.org/showthread.php?t=78037
Dernière modification par crypto178 (Le 21/11/2005, à 15:46)
Hors ligne
crypto178
Re : Le point sur les codecs (+intégration à firefox)
5. Firefox
Pourquoi mplayer-plugin et pas le plugin Totem?
- mplayer lit TOUT. (totem ne fonctionne pas pour les vidéos d'apple.com/trailers par exemple)
- le plugin totem ne fonctionne pas encore avec firefox 1.5 beta (il le fait même planter)
- la qualité de l'intégration et de leur interface est plus ou moins équivalente (mplayer-plugin s'est grandement amélioré entre hoary et breezy)
5.1 Enlever le plugin totem :
sudo mv -f /usr/lib/mozilla-firefox/plugins/libtotem_mozilla.a /usr/lib/mozilla-firefox/plugins/libtotem_mozilla.a_backup
sudo mv -f /usr/lib/mozilla-firefox/plugins/libtotem_mozilla.la /usr/lib/mozilla-firefox/plugins/libtotem_mozilla.la_backup
sudo mv -f /usr/lib/mozilla-firefox/plugins/libtotem_mozilla.so /usr/lib/mozilla-firefox/plugins/libtotem_mozilla.so_backup
sudo mv -f /usr/lib/mozilla-firefox/plugins/libtotem_mozilla.xpt /usr/lib/mozilla-firefox/plugins/libtotem_mozilla.xpt_backup
Note: ceci n'est pas vraiment faisable sous synaptic, il n'y a pas de de paquet dédié au plugin ou en tous cas, je n'en ai pas connaissance.
5.2 Installer mplayer-plugin :
Il s'agit du paquet 'mozilla-mplayer' à installer par synaptic
ou par la commande :
sudo apt-get install mozilla-mplayer
Pensez aussi à ajouter le paquet mplayer-k7 si vous utilisez un processeur AMD athlon
5.3 Tester?
Sites de test? il y'a bien sur Apple.com/trailers, BBC.co.uk, France 3, Allocine.fr, mais aussi la1.be.
Connaissez-vous d'autres sites utilisant des version récentes de realplayer et windows media?
5.3.1 Exemples
Captures d'écrans :
Quicktime:
RealPlayer:
Windows Media Player:
Je ne crois pas vous mentir en vous disant que le plugin se charge plus vite que ses équivalents propriétaires!
5.4 Annexe: Firefox 1.5 beta:
5.4.1 Installer firefox 1.5 dans /opt/firefox
(traduit - et testé - à partir de https://wiki.ubuntu.com/FirefoxNewVersion)
Télécharger la beta sur http://www.mozilla.org/projects/firefox/
A partir du dossier de téléchargement :
sudo cp firefox-1.5rc1.tar.gz /opt/
cd /opt
sudo tar xzvf firefox-1.5rc1.tar.gz
sudo rm firefox-1.5rc1.tar.gz
Faire un backup de son profil :
cdmv .mozilla .mozilla.ubuntu
Faire de firefox beta le firefox par défaut (réversible, voir lien cité plus haut) :
sudo dpkg-divert --divert /usr/bin/firefox.ubuntu --rename /usr/bin/firefox
sudo ln -s /opt/firefox/firefox /usr/bin/firefox
5.4.2 Récupérer les plugins de la version précédente :
Supprimer le dossier plugins de la nouvelle installation :
sudo rm -r /opt/firefox/plugins
Créer un lien vers le dossier de plugin précédent :
sudo ln -s /usr/lib/mozilla-firefox/plugins /opt/firefox/plugins
Dernière modification par crypto178 (Le 19/11/2005, à 23:38)
Hors ligne
crypto178
Re : Le point sur les codecs (+intégration à firefox)
6. Intégration avec d'autres navigateurs web, opera, epiphany?
...7. ?
PS: au fait, es-ce que je gagne l'award du post le plus long?
Dernière modification par crypto178 (Le 02/11/2005, à 00:18)
Hors ligne
Anbreizh
Re : Le point sur les codecs (+intégration à firefox)
BRAVO POUR TON POST , IL EST GENIAL !!!!
"C'est le devoir de chaque homme de rendre au monde au moins autant qu'il en a reçu" Albert Einstein
Pour votre webcam : http://projet.jbtheou.fr
Mon site web (Mathématique, physique, science et service de publication ) http://jbtheou.fr
Hors ligne
Desintegr
Re : Le point sur les codecs (+intégration à firefox)
Pourquoi ne pas faire une page sur le Wiki ?
Hoc Volo, Sic Jubeo !
Mon wiki : http://desintegr.free.fr
Hors ligne
crypto178
Re : Le point sur les codecs (+intégration à firefox)
Pourquoi ne pas faire une page sur le Wiki ?
Ca va venir
Mais avant ça, faut vérifier 2 / 3 trucs, (comme la partie sur libquicktime et sur le lien entre /usr/share/win32 et /usr/share/codecs que j'ai mise en vert par exemple)
EDIT
Ca va venir
En fait, non. La plupart des informations sont déjà présentes éparpillées dans le wiki, ce serait marcher sur les plates-bandes des rédacteurs du wiki, je crois que c'est mieux de garder la page comme tel qui est un HOW-TO qui suit une logique bien précise. Breezy fraîche -> codecs pour son player favoris (que Totem pour l'instant) + vidéos dans Firefox.
Dernière modification par crypto178 (Le 01/11/2005, à 22:05)
Hors ligne
keyes
Re : Le point sur les codecs (+intégration à firefox)
En fait tu expliques presque exactement comment faire "a la main" ce que Easy Ubuntu fait automatiquement.
J'ai lu en diagonale, juste quelques choses:
Une précision quand même pour mplayerplug-in ça ne marche pas si tu ne supprimes pas le plugin Totem. Pour ce faire seule la solution barbare marche (ou bien supprimer le paquet totem):
sudo mv -f /usr/lib/mozilla-firefox/plugins/libtotem_mozilla.a /usr/lib/mozilla-firefox/plugins/libtotem_mozilla.a_backup
sudo mv -f /usr/lib/mozilla-firefox/plugins/libtotem_mozilla.la /usr/lib/mozilla-firefox/plugins/libtotem_mozilla.la_backup
sudo mv -f /usr/lib/mozilla-firefox/plugins/libtotem_mozilla.so /usr/lib/mozilla-firefox/plugins/libtotem_mozilla.so_backup
sudo mv -f /usr/lib/mozilla-firefox/plugins/libtotem_mozilla.xpt /usr/lib/mozilla-firefox/plugins/libtotem_mozilla.xpt_backup
Pour les w32codecs le lien c'est plus /usr/lib/win32 si mes souvenirs sont bons, mon paquet PLF faisait automatiquement ce lien reste a voir si Mirno qui la repris la conservé (ça n'est utile que pour les vieux lecteurs)
Dernière modification par keyes (Le 01/11/2005, à 22:52)
Hors ligne
crypto178
Re : Le point sur les codecs (+intégration à firefox)
En fait tu expliques presque exactement comment faire "a la main" ce que Easy Ubuntu fait automatiquement.
Une précision quand même pour mplayerplug-in ça ne marche pas si tu ne supprimes pas le plugin Totem. Pour ce faire seule la solution barbare marche (ou bien supprimer le paquet totem):
Pour EasyUbuntu yep c'est un excellent outil (je le recommande au point 3) je n'ai vu qu'à l'instant que tu avais ajouté le mplayerplugin dedans. De plus j'utilise firefox beta donc j'étais amené à bidouiller de toute manière (et je n'aime pas non plus realplayer). Ce qui m'a motivé pour écrire ce post c'est surtout la jungle du chan IRC où EasyUbuntu n'est presque jamais recommandé pour l'installation des w32codecs (au contraire, toute une série de méthodes exotiques sont proposées), va savoir pourquoi.
Et puis un ptit guide comme celui-ci avec les aspects légaux ça permet de donner un lien pour répondre aux posts "linux est trop compliqué y'a pas les codecs" (il y a aussi une page du wiki plus détaillée à ce sujet).
Bref, se créer des armes
Une précision quand même pour mplayerplug-in ça ne marche pas si tu ne supprimes pas le plugin Totem. Pour ce faire seule la solution barbare marche (ou bien supprimer le paquet totem):
Merci pour la précision, je sais que le truc est un peu long, mais j'avais déjà précisé en effet qu'il fallait l'enlever au point 5.1.
Pour les w32codecs le lien c'est plus /usr/lib/win32 si mes souvenirs sont bons, mon paquet PLF faisait automatiquement ce lien reste a voir si Mirno qui la repris la conservé (ça n'est utile que pour les vieux lecteurs)
Ok, bon ben je vais ptêtre laisser ça dans le HOW-TO, je ne crois pas que ce lien était présent j'ai du l'ajouter. En fait j'ai pas mal bidouillé avant d'utiliser mplayerplugin, du coup je ne sais plus très bien ce qui a effectivement aidé au fonctionnement ou pas.
Dernière modification par crypto178 (Le 01/11/2005, à 23:09)
Hors ligne
pequatre
Re : Le point sur les codecs (+intégration à firefox)
Salut Crypto178 !
super super super topic.Super idée de mettre TOUTES les infos sur le multimedia dans 1 endroit !! et après c'est réglé.
Un truc qui manque encore dans ton topic: tu parles pas des histoires d'ALSA, OSS, etc...j'y comprends rien, mais apparemment, il faut installer un plugin à vlc pour qu'il gère esd (?) ou Alsa (?), sinon les videos ont pas le son ou seulement aleatoirement (par exemple vlc me met le son 1 fois sur 2, pour le même fichier). Y a des histoires comme ça, j'éspère que tu vas en parler.
Big UP !
(ps: hésitez pas à effacer mon post si le topic doit rester "propre")
Dernière modification par pequatre (Le 02/11/2005, à 00:00)
Hors ligne
crypto178
Re : Le point sur les codecs (+intégration à firefox)
pequatre, j'aimerais bien en parler, mais le problème c'est que je n'y connais pas grand chose. Je n'ai une expérience très limitée de VLC et je comptais un peu sur les commentaires de quelqu'un qui aurait galéré à mort pour le faire fonctionner comme il le veut mais qui aurait trouvé la solution et la posterais ici.
Pareil pour l'intégration à d'autres browser, il doit y avoir des utilisateus d'opera et epiphany qui pourraient nous éclairer.
Mais bon si ça ne vient pas je vais essayer de mettre les mains dans le cambuis et tester toutes les possibilités de VLC et mplayer par moi même (je n'ai pas chipoté au son jusqu'ici donc de ce côté là ma breezy ne s'écarte pas trop d'une nouvelle installation).
(ps: hésitez pas à effacer mon post si le topic doit rester "propre")
Pas de problème à discuter ici j'éditerai les posts originaux pour les changements.
Hors ligne
Aom Apes
Re : Le point sur les codecs (+intégration à firefox)
Bonjour,
j' ai installé Mplayer comme tu l'indiques crypto178 et je suis super content ça marche du tonnerre ; à l'exception des flux en realvideo qui plantent sytématiquement .
En fait, je venais juste d'installer la toute dernière version de Easy Ubuntu (sur la 2.3 elle même sur la 2.2...) de keyes (pour enfin avoir Skype ) avec realplayer 10 en automatique et c'est toujours lui qui prend les flux real dans Firefox, ce qui donne un message d'erreur à chaque fois .
Comment le retirer pour donner la prééminence à Mplayer ?
Hors ligne
crypto178
Re : Le point sur les codecs (+intégration à firefox)
Comment le retirer pour donner la prééminence à Mplayer ?
Tu peux essayer de l'enlever dans synaptic (le paquet s'appelle 'realplay' je crois), mais sinon la méthode barbare est de faire :
ls /usr/lib/mozilla-firefox/plugins/
Dans la liste qui s'affiche, repérer les fichiers qui semblent appartenir à realplayer (sans doute 'real' quelque part dans le nom), et les effacer avec la commande :
sudo rm /usr/lib/mozilla-firefox/plugins/nom_du_fichier_en_cause
Et ensuite, de redémarrer firefox. Mplayer devrait reprendre le dessus.
Hors ligne
dawar
Re : Le point sur les codecs (+intégration à firefox)
Un truc qui manque encore dans ton topic: tu parles pas des histoires d'ALSA, OSS, etc...j'y comprends rien, mais apparemment, il faut installer un plugin à vlc pour qu'il gère esd (?) ou Alsa (?),
Normalement il y'a tout ce qu'il faut dans http://wiki.ubuntu-fr.org/installation/son même si c'est pour Hoary, c'est encore d'actualité sauf que maintenant dmix est par défaut.
S'il n'y a pas de solution, c'est qu'il n'y a pas de problème (Devise Shadoks)
Hors ligne
Grui
Re : Le point sur les codecs (+intégration à firefox)
j ai fait les manips en prenant k7 mplayer pour mon amd. résultat rien marche a part le format windows media player (france3 testé) sous firefox
Hors ligne
Watto
Re : Le point sur les codecs (+intégration à firefox)
joli dossier! comment ne pas aimer ubuntu avec toute cette doc dispo?!
au faite au sujet de mplayer, vous savez se que c'est le cmd pour le piloter? genre le "xmms -play" pour xmms
merci
Hors ligne
Ratur
Re : Le point sur les codecs (+intégration à firefox)
Merci pour ce guide.
Il était vraiment temps de faire le point sur les codecs
Allez, vite, dans le wiki:P
Hors ligne
reggaemanu
Re : Le point sur les codecs (+intégration à firefox)
Sympa comme tuto c'est bien complet
Par contre mplayer à xmms en dépendances c'est chiant, j'en veux pas moi de xmms (déja qu'a la base j'veux pas de mplayer, c'est juste pour le plugin)
Hors ligne
dawar
Re : Le point sur les codecs (+intégration à firefox)
Par contre mplayer à xmms en dépendances c'est chiant, j'en veux pas moi de xmms roll (déja qu'a la base j'veux pas de mplayer, c'est juste pour le plugin)
Ben le plugin utilise mplayer pour lire les vidéos, je vois pas comment la centaines de ko du plugins pourraient lire plein de format par magie
Pour la dépendance a xmms, effectivement j'ai jamais compris pourquoi, peux être utilise-il certains plugins d'xmms...
S'il n'y a pas de solution, c'est qu'il n'y a pas de problème (Devise Shadoks)
Hors ligne
Julian
Re : Le point sur les codecs (+intégration à firefox)
Merci pour cette mise au point sur le multimédia, nickel
Le plugin mplayer est vraiment terrible, rien à redire.
Seulement un petit point, le plugin mplayer lit tout les fichier real média "video", ça c'est bon, mais par exemple sur le site de la fnac où ce sont des extraits "audio", ben ça ne veut pas.
En cliquant sur un lien musicale, un nouvel onglet s'ouvre, le plugin s'ouvre mais rien ne se passe.
On va dire que je ne suis jamais content, mais pour ce genre de manip, je préfère que ce soit le lecteur Realmedia qui s'ouvre, en plus ça fonctionne pour ça.
J'ai donc installé Realplay, les fichiers de plugins se trouvent bien dans /mozilla/plugins/ mais Firefox ne les reconnait pas.
Opera qui utilise aussi ce même dossier /mozilla/plugins/ , lui, reconnait le plugin et lance le lecteur sans problème.
En revanche il ne reconnait pas le plugin mplayer (problème avec libxpcom.so) Bref il y a toujours un truc qui s'acharne.
Je précise que j'utilise la toute dernière version de Firefox disponible depuis hier.
Comment vous faites vous?
@ bientôt
Julian.
julian@jabber.fr
Hors ligne
Julian
Re : Le point sur les codecs (+intégration à firefox)
Ok désolé pour les 2 posts rapprochés.
Pour les fichiers musicaux de la fnac (par exemple) RA , j'ai juste indiqué à firefox de les ouvrir avec realplay (/usr/lib/realplay/realplay) et c'est bon. Sinon pour les vidéos .rm, le plugin mplayer se lance toujours donc nickel .
En revanche le problème Opera/mplayer est toujours là . Je cherche....
julian@jabber.fr
Hors ligne
reggaemanu
Re : Le point sur les codecs (+intégration à firefox)
Ben le plugin utilise mplayer pour lire les vidéos, je vois pas comment la centaines de ko du plugins pourraient lire plein de format par magie
Je le sais bien lol ^^ je dis juste que j'ai juste besoin du plugin, ce qui oblige à installer mplayer dont je n'me servirais pas autrement (c'est pas grave c'est normal) et xmms (ça c'est pas normal et ça fait chier ) dont je n'me servirait pas non plus et je vois absolument pas ce qu'il vient faire la en fait.
Du coup je me passerais du plugin mplayer, pas envi d'avoir 15 applis pour la vidéos et 15 pour le son a cause de dépendances mal faites alors que je me sert d'une seule dans chaque cas j'ai mis le plugin vlc à la place.
Hors ligne
|
I want to delete all files with the extension .bak in a directory. How can I do that in Python?
import os
filelist = [ f for f in os.listdir(".") if f.endswith(".bak") ]
for f in filelist:
os.remove(f)
Or via
import glob, os
filelist = glob.glob("*.bak")
for f in filelist:
os.remove(f)
Be sure to be in the correct directory, eventually using
Use
Then you could use
#!/usr/bin/env python
import glob
import os
directory='/path/to/dir'
os.chdir(directory)
files=glob.glob('*.bak')
for filename in files:
os.unlink(filename)
you can create a function. Add maxdepth as you like for traversing subdirectories.
def findNremove(path,pattern,maxdepth=1):
cpath=path.count(os.sep)
for r,d,f in os.walk(path):
if r.count(os.sep) - cpath <maxdepth:
for files in f:
if files.endswith(pattern):
try:
print "Removing %s" % (os.path.join(r,files))
#os.remove(os.path.join(r,files))
except Exception,e:
print e
else:
print "%s removed" % (os.path.join(r,files))
path=os.path.join("/home","dir1","dir2")
findNremove(path,".bak")
|
I am creating a basic blog with only basic python and the taggit module, it resides at http://127.0.0.1:8000/ (have to put random spaces in so i can submit) when i run ./manage.py syncdb it executes correctly and when i runserver it returns no erros. The problem is when i actually visit the website. Than this happens...
SyntaxError at /
invalid syntax (admin.py, line 4)
This is displayed in the webbrowser..
Here is the traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.4.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'taggit',
'MainBlog')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
101. request.path_info)
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in resolve
298. for pattern in self.url_patterns:
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in url_patterns
328. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in urlconf_module
323. self._urlconf_module = import_module(self.urlconf_name)
File "/Library/Python/2.7/site-packages/django/utils/importlib.py" in import_module
35. __import__(name)
File "/Users/zackbaker/MyBlog/MyBlog/urls.py" in <module>
5. admin.autodiscover()
File "/Library/Python/2.7/site-packages/django/contrib/admin/__init__.py" in autodiscover
29. import_module('%s.admin' % app)
File "/Library/Python/2.7/site-packages/django/utils/importlib.py" in import_module
35. __import__(name)
Exception Type: SyntaxError at /
Exception Value: invalid syntax (admin.py, line 4)
Anyways any help that could be given would be awesome! Thank you guys so much!!
|
the au600 device is a usb PSTN gateway that allows using a plain old telephone as VoIP phone.
This driver got reverse engineered, so not everything might work as expected yet.
Current developer: Markus Rechberger \<mrechberger|at|gmail.com>
IRC on freenode: mrec/mrec_
Supported:
Probably supported:
OEM Page:
A note on phone suport: Referencing http://www.epanorama.net/circuits/telephone_ringer.html on data on what to expect from an FXS line:
"In USA minimum ring voltage supplied is 40Vrms (delivered into a 5 REN load)."
Using a multimeter, I got about 45VAC for the ringer voltage. The manual for the Asound TLink says it will support up to 5 phones which would indicate a REN of 5. The USR says 3 as does the AU600. In any case, I had a great deal of difficulty finding phones that would ring with the adapter. I think that this device cannot quite push enough current to ring some non-european phones or is otherwise out of spec.
Tue Okt 3 19:20:49 CEST 2006
small cleanup, the driver will only create one device instead of 2 from now on. Also adjusted the .asoundrc file below
So Aug 20 15:44:49 CEST 2006
Since I'd like to get that device work with asterisk some more work is needed.. after modifying chan_alsa.c (which is part of the asterisk project), asterisk starts to detect inband DTMF tones..
Detected inband DTMF digit: 0 on ALSADetected inband DTMF digit: 0 on ALSADetected inband DTMF digit: 4 on ALSADetected inband DTMF digit: 3 on ALSADetected inband DTMF digit: 3 on ALSADetected inband DTMF digit: 3 on ALSADetected inband DTMF digit: 3 on ALSADetected inband DTMF digit: 6 on ALSADetected inband DTMF digit: * on ALSADetected inband DTMF digit: * on ALSADetected inband DTMF digit: * on ALSADetected inband DTMF digit: * on ALSA
since this device only works with 9600 hz you might have some problems to play other files with a different sample rate.. alsa is capable of converting and multiplexing different streams. Here's an example that can be used for playback:
aplay -D plug:duplex <filename>
pcm.au600playback {
type dmix
ipc_key 1024
ipc_perm 0777
slave {
pcm "hw:2,0"
period_time 0
period_size 96
buffer_size 1920
format S16_LE
periods 4
rate 9600
}
}
pcm.au600capture {
type rate
slave {
pcm "hw:2,0"
format S16_LE
rate 9600
}
}
pcm.duplex {
type asym
playback.pcm "au600playback"
capture.pcm "au600capture"
}
Tue Aug 15 01:44:42 CEST 2006
$ amixer -c 2
Simple mixer control 'PC/PHONE',0
Capabilities: pswitch pswitch-joined
Playback channels: Mono
Mono: Playback [off]
Simple mixer control 'VOIPPSTN',0
Capabilities: pswitch pswitch-joined
Playback channels: Mono
Mono: Playback [on]
So Aug 13 22:04:10 CEST 2006
I figured out how playback and capturing audio is done "correctly". Support has been added to the current development driver.
The driver isn't completly done yet but I'd say it's 90% done.
I developed that driver on a 2.6.16.16 kernel, so this one will probably be the best one.
hg is also called mercurial you can get a copy from: http://www.selenic.com/mercurial/wiki/index.cgi
$ hg clone http://85.10.198.106/hg/~mrec/au600
$ cd au600
$ make
$ insmod au600.ko
This will create an alsa device and you can use that device as usbaudio device. Recording audio only works if playback is on.
ringing (as documented before):
$ echo 0 > /proc/au600/ring
$ cat /proc/au600/ring
0
$ echo 1 > /proc/au600/ring
$ cat /proc/au600/ring
1
switching from PSTN to VOIP:
$ aplay -l$ alsamixer -c <devicenumber>
Do Aug 10 12:52:13 CEST 2006
playback in linux works fine now for 47 seconds afterwards it adds some buzz again, but I'm sure this will get fixed sooner or later. Used xmms for testing the audio device.
Di Aug 8 03:20:50 CEST 2006
ok fixed some parts of that driver.. the playback sounds clear now _but_ kinda choppy (as the underruns messages indicate).
Using log2bin.pl I verified that the outgoing data is PCM 9600Hz 16 Bit Mono (S16_LE). log2bin plays the transfered data clearly on my other soundcard.
SMlink sold their technology to conexant a while ago too
debian:/devel/kernel/au600# aplay -D hw:2,1 5_5_2006__07_00_59.wav
Playing WAVE '5_5_2006__07_00_59.wav' : Signed 16 bit Little Endian, Rate 9600 Hz, Mono
underrun!!! (at least 1,370 ms long)
underrun!!! (at least 0,456 ms long)
underrun!!! (at least 0,281 ms long)
underrun!!! (at least 1,644 ms long)
underrun!!! (at least 1,296 ms long)
underrun!!! (at least 0,275 ms long)
underrun!!! (at least 0,273 ms long)
Mo Mai 8 03:13:29 CEST 2006
figured out how playback is done, poor support is already implemented. To get it work correctly is just some extra homework now.
following line enables audio playback:
enable PCM playback:000658: OUT: -00002 ms 006456 ms 40 17 c0 03 00 00 00 00 >>>
Sa May 6 18:09:06 CEST 2006
Todo:
The premature usb driver now supports
turn device on:?
usb_control_msg(h,0x40,0x08,0xbef8,0x0000,0x00,0x00,HZ);
enable status led:
usb_control_msg(h,0x40,0x0a,0x10c0,0x0000,0x00,0x00,HZ);
this sequence turns the data transfer on:
000047: OUT: 000002 ms 000373 ms 40 01 01 00 00 00 00 00 >>>
000074: OUT: -00001 ms 000501 ms 40 04 2f 00 00 00 00 00 >>>
this sequence turns the usb data transfer off:
000017: OUT: 000002 ms 000264 ms 40 04 00 00 00 00 00 00 >>>
make the phone ring:
010809: OUT: 000005 ms 015766 ms 40 0a c0 18 00 00 00 00 >>>
stop ringing:
012414: OUT: 000007 ms 017735 ms 40 0a ca 10 00 00 00 00 >>>
enable PCM capture:
000056: OUT: 000002 ms 000401 ms 40 19 00 a0 00 00 00 00 >>>
enable PCM playback:
000658: OUT: -00002 ms 006456 ms 40 17 c0 03 00 00 00 00 >>>
letting the phone ring
debian:/proc# echo 0 > /proc/au600/ring
debian:/proc# cat /proc/au600/ring
0
debian:/proc# echo 1 > /proc/au600/ring
debian:/proc# cat /proc/au600/ring
1
Fr May 5 16:24:07 CEST 2006
haven't worked on that project for a long time because I wrote a driver for an hybrid analogue TV/DVB-T usb device.. maybe I'll find some more time during the next few days to have a look at this project..
After updating the driver an app came up that supports recording. I compared the captured raw usb stream with the content of that recorded audio file that was stored on my disk -- everything's identical!
00000000 52 49 46 46 24 ce 01 00 57 41 56 45 66 6d 74 20 |RIFF$Î..WAVEfmt |00000010 10 00 00 00 01 00 01 00 80 25 00 00 00 4b 00 00 |.........%...K..|00000020 02 00 10 00 64 61 74 61 00 ce 01 00 fe 80 fe 28 |....data.Î..þ.þ(|00000030 fe de fd a6 fd 8f fd a1 fd d1 fd 20 fe 6f fe b7 |þÞý¦ý.ý¡ýÑý þoþ·|00000040 fe 19 ff 7f ff ea ff 3c 00 6e 00 9a 00 a3 00 88 |þ.ÿ.ÿêÿ<.n...£..|
The audiostream has following format:
AUDIO: 9600 Hz, 1 ch, s16le, 153.6 kbit/100.00% (ratio: 19200->19200)
Selected audio codec: [pcm] afm:pcm (Uncompressed PCM)
\ Di Jan 10 14:27:29 CET 2006
implemented isoc out transfer to the device - the interrupt and isoc endpoints are handled now, I also do receive raw data from the device now. Next step would be to analyze the received data.. well another day then..
isoc packet with length: 18dumping packet: 0x66 0x36 0x74 0x36 0x66 0x36 0x6b 0x36 0x6e 0x36 0x64 0x36 0x65 0x36 0x63 0x36 0x60 0x36isoc packet with length: 20dumping packet: 0x66 0x36 0x74 0x36 0x66 0x36 0x6b 0x36 0x6e 0x36 0x64 0x36 0x65 0x36 0x63 0x36 0x60 0x36 0x6c 0x36isoc packet with length: 18dumping packet: 0x66 0x36 0x74 0x36 0x66 0x36 0x6b 0x36 0x6e 0x36 0x64 0x36 0x65 0x36 0x63 0x36 0x60 0x36resubmitting isoc out!phone is picked up!phone is picked up!phone is picked up!phone is picked up!phone is picked up!phone is picked up!phone is picked up!phone is picked up!phone is picked up!phone is picked up!phone is picked up!phone is picked up!incoming urb with length 128!received: 40 packets 110001 .. 0x3110110001 .. 0xb111000100 .. 0xc41010000 .. 0x50 10000 .. 0x10024647: don't know how to handle ISOCH_TRANSFER024648: OUT: <<< 91 00 c4 50024650: OUT: c0 95 00 00 00 00 02 00 <<< c4 50024652: OUT: <<< 91 00 c4 50024654: OUT: c0 95 00 00 00 00 02 00 <<< c4 50024655: OUT: <<< 91 00 c4 10024658: don't know how to handle ISOCH_TRANSFER024659: OUT: c0 95 00 00 00 00 02 00 <<< c4 10024660: OUT: <<< 91 00 c4 10024663: OUT: c0 95 00 00 00 00 02 00 <<< c4 10
looks like the same information is also accessable using the read control message "c0 95 00 00 00 00 02 00"
c4 50 and c4 10 is also returned within the IRQ function
IRQ responses:
this comes back if the phone is switched to VoIP, and the phone is off the station (active to speak)
data: 0x41 0x0 0xc4 0x10data: 0xc1 0x0 0xc4 0x10
following data is received if the phone is switched to VoIP and not active
data: 0x41 0x0 0xc4 0x50data: 0xc1 0x0 0xc4 0x50
next one comes in if the phone is switched to PSTN and not active (I have no PSTN connection here atm maybe there might show up something else if it's connected to the PSTN network I'll test it later)
data: 0xc1 0x0 0x0 0x40data: 0x41 0x0 0x0 0x40data: 0x41 0x0 0x0 0x40
enough for today...time for gettin a beer
Mo Jan 9 13:03:33 CET 2006
implemented isoc in transfer from the device, as well as interrupt transfers (code looks quite dirty now and the packets which are received are empty .. this is very likely because of a wrong device configuration which has to be set up using usb control messages .. so far so go od the device already plays ping pong with my notebook ..)
au600
Speed: 12Mb/s (full)
USB Version: 1.00
Device Class: 02(comm.)
Device Subclass: 00
Device Protocol: 00
Maximum Default Endpoint Size: 8
Number of Configurations: 1
Vendor Id: 0483
Product Id: 7554
Revision Number: 2.00
Config Number: 1
Number of Interfaces: 1
Attributes: a0
MaxPower Needed: 100mA
Interface Number: 0
Name: au600
Alternate Number: 0
Class: 02(comm.)
Sub Class: 80
Protocol: 0
Number of Endpoints: 1
Endpoint Address: 81
Direction: in
Attribute: 19
Type: Int.
Max Packet Size: 4
Interval: 1ms
Interface Number: 0
Name: au600
Alternate Number: 1
Class: 02(comm.)
Sub Class: 80
Protocol: 0
Number of Endpoints: 3
Endpoint Address: 81
Direction: in
Attribute: 19
Type: Int.
Max Packet Size: 4
Interval: 1ms
Endpoint Address: 02
Direction: out
Attribute: 5
Type: Isoc
Max Packet Size: 128
Interval: 1ms
Endpoint Address: 83
Direction: in
Attribute: 5
Type: Isoc
Max Packet Size: 128
Interval: 1ms
Interface Number: 0
Name: au600
Alternate Number: 2
Class: 02(comm.)
Sub Class: 80
Protocol: 0
Number of Endpoints: 3
Endpoint Address: 81
Direction: in
Attribute: 19
Type: Int.
Max Packet Size: 4
Interval: 1ms
Endpoint Address: 04
Direction: out
Attribute: 5
Type: Isoc
Max Packet Size: 128
Interval: 1ms
Endpoint Address: 85
Direction: in
Attribute: 5
Type: Isoc
Max Packet Size: 128
Interval: 1ms
Interface Number: 0
Name: au600
Alternate Number: 3
Class: 02(comm.)
Sub Class: 80
Protocol: 0
Number of Endpoints: 5
Endpoint Address: 81
Direction: in
Attribute: 19
Type: Int.
Max Packet Size: 4
Interval: 1ms
Endpoint Address: 02
Direction: out
Attribute: 5
Type: Isoc
Max Packet Size: 128
Interval: 1ms
Endpoint Address: 83
Direction: in
Attribute: 5
Type: Isoc
Max Packet Size: 128
Interval: 1ms
Endpoint Address: 04
Direction: out
Attribute: 5
Type: Isoc
Max Packet Size: 128
Interval: 1ms
Endpoint Address: 85
Direction: in
Attribute: 5
Type: Isoc
Max Packet Size: 128
Interval: 1ms
most important is to know what alternate number was used within the windows driver:
$ grep -i Altern usbsnoop.log
Interface[0]: AlternateSetting = 1
Interface[0]: AlternateSetting = 1
so we fixate on Alternate number 1
What endpoint pins are used? ..
grep -i endpoint * | sort | uniq
Interface[0]: Pipes[0] : EndpointAddress = 0x00000081
Interface[0]: Pipes[1] : EndpointAddress = 0x00000002
Interface[0]: Pipes[2] : EndpointAddress = 0x00000083
PipeHandle = 80e02e80 [endpoint 0x00000081]
PipeHandle = 80e02e80 [endpoint 0x00000081]
PipeHandle = 80e02e9c [endpoint 0x00000002]
PipeHandle = 80e02e9c [endpoint 0x00000002]
PipeHandle = 80e02eb8 [endpoint 0x00000083]
PipeHandle = 80e02eb8 [endpoint 0x00000083]
So 81, 02 and 83 are used we also see them in configuration 0 alternate1 good :)
81 is an interrupt endpoint02 an isochronous out data endpoint83 an isochronous in data endpoint
Sa Jan 7 03:25:22 CET 2006
implemented a mixer control for switching from PSTN to VoIP
debian:/devel/usb/usbfs/aufgabe5# amixer -c 2
Simple mixer control 'Master',0
Capabilities: volume volume-joined
Playback channels: Mono
Limits: 0 - 256
Mono: 0 [0%]
Simple mixer control 'Midi',0
Capabilities: volume volume-joined
Playback channels: Mono
Limits: 0 - 256
Mono: 0 [0%]
Simple mixer control 'VoIP Input Select',0
Capabilities: pswitch pswitch-joined
Playback channels: Mono
Mono: Playback [off]
Index 0x0
IndexValues:
1000011000000 .. 0x10c0 VoIP
0000011000000 .. 0x00c0 PSTN
the first bit is for switching to VoIP if it's 1 the device is set to VoIP
0000010000000 .. 0x80 this bit toggles the Link led
0000000000000 .. 0x00
Do Jan 5 19:46:39 CET 2006
Implemented the Alsa frontend:
$ cat /proc/asound/cards
0 [I82801DBICH4 ]: ICH4 - Intel 82801DB-ICH4
Intel 82801DB-ICH4 with ALC202 at 0xe0100c00, irq 10
1 [Modem ]: ICH-MODEM - Intel 82801DB-ICH4 Modem
Intel 82801DB-ICH4 Modem at 0x2400, irq 10
2 [AU-600 ]: AU-600 VoIP - AU-600
AU-600 VoIP USB Adapter
$ amixer -c 2
Simple mixer control 'Midi',0
Capabilities: volume volume-joined
Playback channels: Mono
Limits: 0 - 255
Mono: 0 [0%]
Simple mixer control 'Volume',0
Capabilities: volume volume-joined
Playback channels: Mono
Limits: 0 - 255
Mono: 0 [0%]
Retrieved from "http://alsa.opensrc.org/Au600"
|
jegougou
Re : [Info] Installation du driver Libre ATI Radeon
j'ai suivis ton conseil voila le resultat
4294 frames in 5.0 seconds = 858.715 FPS
4254 frames in 5.0 seconds = 850.774 FPS
4190 frames in 5.0 seconds = 837.903 FPS
3269 frames in 5.0 seconds = 653.660 FPS
4400 frames in 5.0 seconds = 879.915 FPS
4398 frames in 5.0 seconds = 879.502 FPS
4399 frames in 5.0 seconds = 879.631 FPS
4384 frames in 5.0 seconds = 876.751 FPS
4402 frames in 5.0 seconds = 880.342 FPS
4231 frames in 5.1 seconds = 830.142 FPS
c'est grave docteur ?:D
j'ai également fait
glxinfo | grep "direct rendering"
c'est YES donc c'est tout bon
Dernière modification par jegougou (Le 10/07/2007, à 22:01)
Hors ligne
tshirtman
Re : [Info] Installation du driver Libre ATI Radeon
Grave? non pas vraiement, tu as la 3d, avec des performances qui ne cassent pas des briques, mais utilisables quand même... (je tappe actuelement dans du 1600-2000 avec ma nvidia gforce4, sans optimisations particulières... je me souvient d'avoir fait plus dans le passé).
tu m'aurais dit moins de 500 je t'aurais conseillé d'oublier les jeux, mais avec ça tu devrait pouvoir tenter les quakes3 et autres jeux de la même époque... voir plus récents...
Hors ligne
jegougou
Re : [Info] Installation du driver Libre ATI Radeon
ok merci de tes réponses
Hors ligne
Prophet22
Re : [Info] Installation du driver Libre ATI Radeon
Salut à tous,
J'ai un 'chtit problème avec le pilote libre radeon.
Voilà la situation : Feisty, carte graphique radeon 9200 agp, chipset sis_agp. Je n'ai jamais installé fglrx.
J'ai configuré mon xorf.conf pour utiliser le pilote libre radeon (qui apporte une accélération 2D et 3D pour la radeon 9200 normalement).
glxinfo m'indique que le direct rendering est actif
glxgears tourne bien (on se moque des FPS)
... mais le problème est le suivant : pendant que glxgears tourne, je fais un top et là, horreur, le processeur est utilisé à 70%... ce qui signifie que l'accélération 3D n'est pas active.
D'où ma question : est-ce normal ? je m'attendais tout de même à une utilisation moindre du processeur...
Qu'en pensez-vous ?
Merci
Voici les données intéressantes de mon xorg.conf
Section "Device"
Identifier "ATI 9200"
Driver "radeon"
BusID "PCI:1:0:0"
Option "AGPSize" "64" # Décommentez si vous avec une carte AGP
Option "RingSize" "8"
Option "BufferSize" "2"
Option "EnableDepthMoves" "true"
Option "RenderAccel" "true" # Enable the hardware render acceleration
Option "AGPMode" "4" # Décommentez si vous avez une carte AGP
Option "EnablePageFlip" "1" # Enable page flipping for 3D apps
Option "GARTSize" "64"
Option "ColorTiling" "1"
EndSection
Section "Extensions"
Option "RENDER" "Enable"
EndSection
Section "DRI"
Mode 0666
EndSection
CousinM
Re : [Info] Installation du driver Libre ATI Radeon
Moi Jai une ATi 9250 (Asus), Je voudrai afficher l'image sur la TV, via le port RCA Jaune derrière ma Carte vidéo. Jai suivi Beaucoup de discussion, mais malheureusement je ny arrive pas.Pourtant jai une image mais elle est hachurée et on peut a peine savoir qu'on ai sur le bureau. ses tout croche et barioler.
Pourtant en mode console avec ATL+CTRL+F1 je peut facilement voir et lire se quil ya a l'écran.
Jai poster mon Xorg a se lien: http://forum.ubuntu-fr.org/viewtopic.php?id=133467
Quel qu'un aurais t'il une solution.
Merci
Linux le choix par excellence
Hors ligne
asstux
Re : [Info] Installation du driver Libre ATI Radeon
Salut a tous,
je suis sous ubuntu 7.04 et je n'y arrive pas...
mon pb vient du fait que je n'arrive pas a installer ces foutus drivers libres pour ma carte graphique (ATI X1900XTX) ??
Auriez vous une idée sur ce qu'il faut mettre dans xorg.conf ?
merci et @+
Hors ligne
jegougou
Re : [Info] Installation du driver Libre ATI Radeon
salut a tous !!
Voila cela devait arriver a force de bidouiller j'ai mon affichage qui merde, par exemple totem quand j'ecoute de la musique, le visualiseur ne s'affiche pas correctement j'ai plein de clignotement et bandes noires, j'ai la meme chose avec mon screen saver.
Peut on réinnitialiser le driver installé d'origine avec ubuntu 7.04 qui marchait pas trop mal ?
Par avance merci
Hors ligne
jegougou
Re : [Info] Installation du driver Libre ATI Radeon
Mega UP
Au secours je me meure, mon ordi plante séverement je n'ai plus d'environnement graphique message d'erreur totalement brouillé et apres j'arrive sur un console ou est mon gnome?
J'ai vu que j'avais un autre kernel dans le boot menu mais quand je vais dessus il semble aussi foutu
je suis pret a formater et reinstaller mais le problème c'est que j'ai des fichiers que je veux sauvegarder (environ une centaine de mes CD que j'ai encodé pour pouvoir faire de la place) et quand je boot sur le live cd, il ne veut pas copier mes mp3 vers mon HDD externe alors que j'ai reussi a deplacer d'autre type de fichier.
Mon transfert de win se passait bien jusque la mais la c'est la cata
a votre bon coeur j'ai pas envie de tout recommencer cela ma pris de jours et des jours
Hors ligne
tshirtman
Re : [Info] Installation du driver Libre ATI Radeon
C'est une console normale? pas une busybox?
vu que t'as posté ici je vais supposé que c'est juste le serveur X qui est mal configuré. si tu as un message qui dit autre chose ouvre plutot un autre sujet!
bon, quand tu est dans ta console:
tappe
sudo dpkg-reconfigure xserver-xorg
et essaye de prendre les trucs qui on le plus de chance de marcher (ati si ta carte est ati, nv si c'est nvidia, au pire vesa)
a la fin tappe
sudo /etc/init.d/gdm restart
si tu as encore l'erreur retourne sous ta console et recommence en changeant ta réponse pour le driver.
Dernière modification par tshirtman (Le 23/07/2007, à 12:28)
Hors ligne
jegougou
Re : [Info] Installation du driver Libre ATI Radeon
C'est une console normale? pas une busybox?
vu que t'as posté ici je vais supposé que c'est juste le serveur X qui est mal configuré. si tu as un message qui dit autre chose ouvre plutot un autre sujet!
Le seul message d'erreur que j'arrive a peur pres à déchiffrer est effectivement a propos d'un "X quelquechose"
et essaye de prendre les trucs qui on le plus de chance de marcher (ati si ta carte est ati
Si j'ai bien compris le system va me proposer differents choix ?
Si c'est cela tant mieux du moment que j'arrive sous mon gnome meme degradé afin que je puisse au moins faire un backup
Je vais essayer et je vous tient au courant en tout cas merci de ta réponse.
Je réapprends l'informatique sous linux et c'est en forgeant que forgeron donc forcemment il y a parfois de la casse
a+
Hors ligne
dangman
Re : [Info] Installation du driver Libre ATI Radeon
AU SECOURS!!!
Bonjour à tous,
Je suis vraiment au desespoir. Je ne trouve pas de solution pour que ma carte graphique soit reconnue. J'ai une ati mobility radeon 9200 et pour le moment ubuntu studio me met les drivers generique, je ne peux donc pas utiliser la 3D et ne peux pas également changer ma résolution d'ecran.
J'ai lu enormement de chose dessus mais je ne trouve pas de réponses claire.
Historiquement j'ai déjà essayé d'installer les pilotes d'ati 2.28.8 mais l'installation provoque une erreur et je ne peux pas les installer.
Pourriez vous m'indiquer si je dois installer les pilotes libre de radéon et si oui ou je peux les trouver et comment les installer. J'ai cru comprendre que les pilotes libres sont déjà dans la mouture d'ubuntu studio.
Merci beaucoup pour votre aide.
Dangman
Jeryagor
Re : [Info] Installation du driver Libre ATI Radeon
Ce driver est-il utilisable pour une Mobily Radeon X700 ?
Si oui, serait-il possible d'avoir la configuration associee
Merci d'avance.
Hors ligne
jegougou
Re : [Info] Installation du driver Libre ATI Radeon
Salut à tous !!!
juste pour vous dire que j'ai reussi à réparer mon anomalie en reinstallant tout , j'ai perdu une bonne partie de mes données mais bon tant pis.
quand je tapais cette ligne
sudo dpkg-reconfigure xserver-xorg
la console me répondait que c'etait pas installé et que cela ne pouvait marcher donc un coup de sang m'a fait tout formatter et reinstaller par contre en refaisant ma config j'ai découvert un truc normalement je suis en wifi mais pour faire un test j'avais branché l'ethernet pour avoir a éviter de paramétré le live cd et quand j'ai réinstallé le cable est resté branché après avoir rebooter ma machine une fois l'installe finit, les principaux soft était deja en francais et je n'ai pas eu besoin de reparamétrer le tout cela m'a fait gagner du temps.
c'est tout bete mais faut le savoir
a+
et merci de votre aide
Dernière modification par jegougou (Le 26/07/2007, à 15:19)
Hors ligne
Astier
Re : [Info] Installation du driver Libre ATI Radeon
@Jeryagor : c'est tout à fait possible d'utiliser le driver libre radeon avec une ATI Mobility X700, et même d'avoir l'accélération graphique ; je te posterai mon xorg.conf plus tard, du moins la partie Device.
A+
Hors ligne
Jeryagor
Re : [Info] Installation du driver Libre ATI Radeon
je te posterai mon xorg.conf plus tard, du moins la partie Device.
Merci, merci, j'attends ca avec impatience pour tester.
Hors ligne
Astier
Re : [Info] Installation du driver Libre ATI Radeon
@ Jeryagor : Voici la section Device de mon /etc/X11/xorg.conf :
Section "Device"
Identifier "ATI Mobility Radeon X700"
Driver "radeon"
BusID "PCI:1:0:0"
Option "MonitorLayout" "LVDS,AUTO"
Option "EnablePageFlip" "1"
Option "ColorTiling" "1"
Option "AccelMethod" "XXA"
Option "XAANoOffscreenPixmaps"
Option "GARTSize" "64"
Option "RingSize" "8"
Option "BufferSize" "2"
Option "EnableDepthMoves" "yes"
Option "UseFBDev" "false"
Option "RenderAccel" "true" # Enable the hardware render acceleration
Option "mtrr" "on"
Option "SubPixelOrder" "none"
Option "DPMS"
Option "DynamicClocks" "on"
EndSection
Pense également à rajouter à la fin du fichier /etc/X11/xorg.conf la section suivante :
Section "Extensions"
Option "RENDER" "Enable"
Option "Composite" "True"
EndSection
Avant de modifier ce fichier fais en une sauvegarde au cas où :
sudo cp /etc/X11/xorg.conf /etc/X11/xorg.conf.back
Pour restaurer le fichier :
sudo cp /etc/X11/xorg.conf.back /etc/X11/xorg.conf
Après toute modification, il faut relancer le serveurX :
sudo /etc/init.d/gdm restart
A+
Hors ligne
Jeryagor
Re : [Info] Installation du driver Libre ATI Radeon
C'est bon, ça fonctionne nickel : les performances sont légèrement meilleures : je suis passé de 2000 avec le driver ati à 2400 en moyenne avec ledriver radeon dans glxgears.
Petite remarque : bien changer le nom de votre carte de le xorg.conf sinon il y aura problème. Par exemple, celle de Astier s'appelle "ATI Mobility Radeon X700" alors que la mienne porte le nom de "ATI Technologies Inc Radeon Mobility X700 (PCIE)".
Hors ligne
Astier
Re : [Info] Installation du driver Libre ATI Radeon
L'essentiel c'est pas la dénomination de la carte dans la section Device mais que celle-ci corresponde à la ligne Device de la section Screen.
A+
Hors ligne
tetrafred
Re : [Info] Installation du driver Libre ATI Radeon
bonjour à vous,
alors voilà, j'ai installer récemment la version edgy 6.10 ultimate gamers (un gros gros ménage à faire!) et je possède une ati radeon x800xt. Tous fonctionne bien sous beryl, cube etc etc, suaf sous le jeux "sauerbraten"....or quand je vais dans mon gestionnaire de périph il ne me reconnais pas ma carte graph^^. "Dois je" me tenter l'install des driver ati? est ce que je dois les installer avant "ati binary xorg driver"?
merci à vous
ps: je suis conscient que c'est une vrai question de noob, mais bon je préfere demander plutôt que faire des bétises
Dernière modification par tetrafred (Le 06/08/2007, à 15:18)
Hors ligne
Danylo
Re : [Info] Installation du driver Libre ATI Radeon
Je cherche une solution par rapport aux drivers pour mon portable : ACEr carte graphique ATI mobility Radeon X1300
Je serais sauve si jamais il y'a une solution car a chaque fois que j'essaie de passer a la version feisty, patatrassssss
Merci d'avance
dsi0743
Re : [Info] Installation du driver Libre ATI Radeon
Bonjour. Comme beaucoup, je n'arrive pas à "activer" l'accélération matérielle de ma carte Radeon 9600 SE avec les drivers libres.
glxgears me donne un score honnête de 1100 FPS mais avec une conso CPU de 20%, alors que, après avoir installé les pilotes propriétaires, la CPU tombait à 0,3%... mais avec un FPS à 250 ???
Comme je n'arrive plus à me passer de Compiz (du bureau 3D)... j'ai remis les pilotes libres.
Voici mon /etc/X11/xorg.conf :
# /etc/X11/xorg.conf (xorg X Window System server configuration file)
#
# This file was generated by dexconf, the Debian X Configuration tool, using
# values from the debconf database.
#
# Edit this file with caution, and see the xorg.conf(5) manual page.
# (Type "man xorg.conf" at the shell prompt.)
#
# This file is automatically updated on xserver-xorg package upgrades *only*
# if it has not been modified since the last upgrade of the xserver-xorg
# package.
#
# If you have edited this file but would like it to be automatically updated
# again, run the following command:
# sudo dpkg-reconfigure -phigh xserver-xorg
Section "Files"
FontPath "/usr/share/fonts/X11/misc"
FontPath "/usr/share/fonts/X11/cyrillic"
FontPath "/usr/share/fonts/X11/100dpi/:unscaled"
FontPath "/usr/share/fonts/X11/75dpi/:unscaled"
FontPath "/usr/share/fonts/X11/Type1"
FontPath "/usr/share/fonts/X11/100dpi"
FontPath "/usr/share/fonts/X11/75dpi"
# path to defoma fonts
FontPath "/var/lib/defoma/x-ttcidfont-conf.d/dirs/TrueType"
EndSection
Section "Module"
Load "i2c"
Load "bitmap"
Load "ddc"
Load "dri"
Load "extmod"
Load "freetype"
Load "glx"
Load "int10"
Load "type1"
Load "vbe"
EndSection
Section "InputDevice"
Identifier "Generic Keyboard"
Driver "kbd"
Option "CoreKeyboard"
Option "XkbRules" "xorg"
Option "XkbModel" "pc105"
Option "XkbLayout" "fr"
EndSection
Section "InputDevice"
Identifier "Configured Mouse"
Driver "mouse"
Option "CorePointer"
Option "Device" "/dev/input/mice"
Option "Protocol" "ExplorerPS/2"
Option "Emulate3Buttons" "false"
Option "Buttons" "7"
Option "ZAxisMapping" "4 5"
Option "ButtonMapping" "1 2 3 6 7"
EndSection
Section "InputDevice"
Driver "wacom"
Identifier "stylus"
Option "Device" "/dev/input/wacom"
Option "Type" "stylus"
Option "ForceDevice" "ISDV4" # Tablet PC ONLY
EndSection
Section "InputDevice"
Driver "wacom"
Identifier "eraser"
Option "Device" "/dev/input/wacom"
Option "Type" "eraser"
Option "ForceDevice" "ISDV4" # Tablet PC ONLY
EndSection
Section "InputDevice"
Driver "wacom"
Identifier "cursor"
Option "Device" "/dev/input/wacom"
Option "Type" "cursor"
Option "ForceDevice" "ISDV4" # Tablet PC ONLY
EndSection
Section "Device"
Identifier "ATI Technologies Inc RV350 AQ [Radeon 9600]"
Driver "radeon"
Option "AccelMethod" "XAA" # Use XFree86 Acceleration Architecture
Option "AccelDFS" "0" # mettez à 0 si vous avez une carte AGP
Option "mtrr" "on"
Option "DPMS"
Option "DynamicClocks" "on"
Option "GARTSize" "64"
Option "AGPMode" "8"
Option "AGPFastWrite" "true"
Option "AGPSize" "128"
Option "RingSize" "8"
Option "BufferSize" "2"
Option "EnablePageFlip" "true"
Option "EnableDepthMoves" "true"
Option "ColorTiling" "on"
Option "RenderAccel" "true"
Option "DRI" "true"
BusID "PCI:3:0:0"
EndSection
Section "Monitor"
Identifier "B101920"
Option "DPMS"
EndSection
Section "Screen"
Identifier "Default Screen"
Device "ATI Technologies Inc RV350 AQ [Radeon 9600]"
Monitor "B101920"
DefaultDepth 24
SubSection "Display"
Depth 1
Modes "1280x1024" "1152x864" "1024x768" "832x624" "800x600" "720x400" "640x480"
EndSubSection
SubSection "Display"
Depth 4
Modes "1280x1024" "1152x864" "1024x768" "832x624" "800x600" "720x400" "640x480"
EndSubSection
SubSection "Display"
Depth 8
Modes "1280x1024" "1152x864" "1024x768" "832x624" "800x600" "720x400" "640x480"
EndSubSection
SubSection "Display"
Depth 15
Modes "1280x1024" "1152x864" "1024x768" "832x624" "800x600" "720x400" "640x480"
EndSubSection
SubSection "Display"
Depth 16
Modes "1280x1024" "1152x864" "1024x768" "832x624" "800x600" "720x400" "640x480"
EndSubSection
SubSection "Display"
Depth 24
Modes "1280x1024" "1152x864" "1024x768" "832x624" "800x600" "720x400" "640x480"
EndSubSection
EndSection
Section "ServerLayout"
Identifier "Default Layout"
Screen "Default Screen"
InputDevice "Generic Keyboard"
InputDevice "Configured Mouse"
InputDevice "stylus" "SendCoreEvents"
InputDevice "cursor" "SendCoreEvents"
InputDevice "eraser" "SendCoreEvents"
EndSection
Section "Extensions"
Option "RENDER" "Enable"
EndSection
Section "DRI"
Mode 0666
EndSection
et voici le glxinfo :
dsi0743@pc-parents:~$ glxinfo
name of display: :0.0
display: :0 screen: 0
direct rendering: Yes
server glx vendor string: SGI
server glx version string: 1.2
server glx extensions:
GLX_ARB_multisample, GLX_EXT_import_context, GLX_EXT_texture_from_pixmap,
GLX_EXT_visual_info, GLX_EXT_visual_rating, GLX_MESA_copy_sub_buffer,
GLX_OML_swap_method, GLX_SGI_make_current_read, GLX_SGI_swap_control,
GLX_SGIS_multisample, GLX_SGIX_fbconfig, GLX_SGIX_visual_select_group
client glx vendor string: SGI
client glx version string: 1.4
client glx extensions:
GLX_ARB_get_proc_address, GLX_ARB_multisample, GLX_EXT_import_context,
GLX_EXT_visual_info, GLX_EXT_visual_rating, GLX_MESA_allocate_memory,
GLX_MESA_copy_sub_buffer, GLX_MESA_swap_control,
GLX_MESA_swap_frame_usage, GLX_OML_swap_method, GLX_OML_sync_control,
GLX_SGI_make_current_read, GLX_SGI_swap_control, GLX_SGI_video_sync,
GLX_SGIS_multisample, GLX_SGIX_fbconfig, GLX_SGIX_pbuffer,
GLX_SGIX_visual_select_group, GLX_EXT_texture_from_pixmap
GLX version: 1.2
GLX extensions:
GLX_ARB_get_proc_address, GLX_ARB_multisample, GLX_EXT_import_context,
GLX_EXT_visual_info, GLX_EXT_visual_rating, GLX_MESA_copy_sub_buffer,
GLX_MESA_swap_control, GLX_MESA_swap_frame_usage, GLX_OML_swap_method,
GLX_SGI_make_current_read, GLX_SGI_swap_control, GLX_SGI_video_sync,
GLX_SGIS_multisample, GLX_SGIX_fbconfig, GLX_SGIX_visual_select_group
OpenGL vendor string: Tungsten Graphics, Inc.
OpenGL renderer string: Mesa DRI R300 20060815 AGP 8x x86/MMX+/3DNow!+/SSE TCL
OpenGL version string: 1.3 Mesa 6.5.2
OpenGL extensions:
GL_ARB_fragment_program, GL_ARB_imaging, GL_ARB_multisample,
GL_ARB_multitexture, GL_ARB_texture_border_clamp,
GL_ARB_texture_compression, GL_ARB_texture_cube_map,
GL_ARB_texture_env_add, GL_ARB_texture_env_combine,
GL_ARB_texture_env_crossbar, GL_ARB_texture_env_dot3,
GL_MESAX_texture_float, GL_ARB_texture_mirrored_repeat,
GL_ARB_texture_rectangle, GL_ARB_transpose_matrix,
GL_ARB_vertex_buffer_object, GL_ARB_vertex_program, GL_ARB_window_pos,
GL_EXT_abgr, GL_EXT_bgra, GL_EXT_blend_color,
GL_EXT_blend_equation_separate, GL_EXT_blend_func_separate,
GL_EXT_blend_minmax, GL_EXT_blend_subtract, GL_EXT_clip_volume_hint,
GL_EXT_compiled_vertex_array, GL_EXT_convolution, GL_EXT_copy_texture,
GL_EXT_draw_range_elements, GL_EXT_gpu_program_parameters,
GL_EXT_histogram, GL_EXT_packed_pixels, GL_EXT_polygon_offset,
GL_EXT_rescale_normal, GL_EXT_secondary_color,
GL_EXT_separate_specular_color, GL_EXT_stencil_wrap, GL_EXT_subtexture,
GL_EXT_texture, GL_EXT_texture3D, GL_EXT_texture_edge_clamp,
GL_EXT_texture_env_add, GL_EXT_texture_env_combine,
GL_EXT_texture_env_dot3, GL_EXT_texture_filter_anisotropic,
GL_EXT_texture_lod_bias, GL_EXT_texture_mirror_clamp,
GL_EXT_texture_object, GL_EXT_texture_rectangle, GL_EXT_vertex_array,
GL_APPLE_packed_pixels, GL_ATI_blend_equation_separate,
GL_ATI_texture_env_combine3, GL_ATI_texture_mirror_once,
GL_IBM_rasterpos_clip, GL_IBM_texture_mirrored_repeat,
GL_INGR_blend_func_separate, GL_MESA_pack_invert, GL_MESA_ycbcr_texture,
GL_MESA_window_pos, GL_NV_blend_square, GL_NV_light_max_exponent,
GL_NV_texture_rectangle, GL_NV_texgen_reflection, GL_NV_vertex_program,
GL_OES_read_format, GL_SGI_color_matrix, GL_SGI_color_table,
GL_SGIS_generate_mipmap, GL_SGIS_texture_border_clamp,
GL_SGIS_texture_edge_clamp, GL_SGIS_texture_lod
visual x bf lv rg d st colorbuffer ax dp st accumbuffer ms cav
id dep cl sp sz l ci b ro r g b a bf th cl r g b a ns b eat
----------------------------------------------------------------------
0x23 24 tc 0 32 0 r y . 8 8 8 8 0 24 8 0 0 0 0 0 0 None
0x24 24 tc 0 32 0 r y . 8 8 8 8 0 24 0 0 0 0 0 0 0 None
0x25 24 tc 0 32 0 r y . 8 8 8 8 0 24 8 16 16 16 16 0 0 Slow
0x26 24 tc 0 32 0 r y . 8 8 8 8 0 24 0 16 16 16 16 0 0 Slow
0x27 24 tc 0 32 0 r . . 8 8 8 8 0 24 8 0 0 0 0 0 0 None
0x28 24 tc 0 32 0 r . . 8 8 8 8 0 24 0 0 0 0 0 0 0 None
0x29 24 tc 0 32 0 r . . 8 8 8 8 0 24 8 16 16 16 16 0 0 Slow
0x2a 24 tc 0 32 0 r . . 8 8 8 8 0 24 0 16 16 16 16 0 0 Slow
0x2b 24 dc 0 32 0 r y . 8 8 8 8 0 24 8 0 0 0 0 0 0 None
0x2c 24 dc 0 32 0 r y . 8 8 8 8 0 24 0 0 0 0 0 0 0 None
0x2d 24 dc 0 32 0 r y . 8 8 8 8 0 24 8 16 16 16 16 0 0 Slow
0x2e 24 dc 0 32 0 r y . 8 8 8 8 0 24 0 16 16 16 16 0 0 Slow
0x2f 24 dc 0 32 0 r . . 8 8 8 8 0 24 8 0 0 0 0 0 0 None
0x30 24 dc 0 32 0 r . . 8 8 8 8 0 24 0 0 0 0 0 0 0 None
0x31 24 dc 0 32 0 r . . 8 8 8 8 0 24 8 16 16 16 16 0 0 Slow
0x32 24 dc 0 32 0 r . . 8 8 8 8 0 24 0 16 16 16 16 0 0 Slow
0x4b 32 tc 0 32 0 r . . 8 8 8 8 0 0 0 0 0 0 0 0 0 Ncon
voici le /etc/modules :
# /etc/modules: kernel modules to load at boot time.
#
# This file contains the names of kernel modules that should be loaded
# at boot time, one per line. Lines beginning with "#" are ignored.
fuse
lp
sbp2
Ma config :
ATHLON XP2600+
1,5 Go de RAM
ATI RADEON 9600 SE
Carte mère ASUS A7N8X Deluxe
Merci pour toute aide.
Athlon XP2600+ 1,5 Go ram CG NVIDIA Geforce 6800 GT
Ubuntu 10.10 - Vista SP2
Hors ligne
dsi0743
Re : [Info] Installation du driver Libre ATI Radeon
up
Athlon XP2600+ 1,5 Go ram CG NVIDIA Geforce 6800 GT
Ubuntu 10.10 - Vista SP2
Hors ligne
dsi0743
Re : [Info] Installation du driver Libre ATI Radeon
Personne n'a d'idée ? Ai-je mal cherché ?
Athlon XP2600+ 1,5 Go ram CG NVIDIA Geforce 6800 GT
Ubuntu 10.10 - Vista SP2
Hors ligne
_dje
Re : [Info] Installation du driver Libre ATI Radeon
@dsi0743: essaye ça:
Option "AccelMethod" "EXA"
Option "MigrationHeuristic" "greedy"
ou
Option "AccelMethod" "EXA"
Option "MigrationHeuristic" "smart"
dans la section Device.
J'avais aussi un probleme de glxgears tournant anormalement haut, avec ça c'est retombé.
MigrationHeuristic est une fonction non documenté de EXA mais existe apparement depuis Xorg 7.0.
On peut trouver qqs infos sur le net.
Hors ligne
dsi0743
Re : [Info] Installation du driver Libre ATI Radeon
Merci pour ta réponse, mais cela ne change rien dans mon cas.
Athlon XP2600+ 1,5 Go ram CG NVIDIA Geforce 6800 GT
Ubuntu 10.10 - Vista SP2
Hors ligne
|
I'm a Python junior, so keep that in mind. In a Python script, I need to set a Return-Path address that is different than the sender's address. (I'm using Gmail as SMTP server.)
I've done lots of searching on this question and found plenty of "answers", but no solutions. I tried this link Setting Return-Path with Python sendmail for a MIME message but it's not working for me at all. I can change the "To:" address that the email recipient sees, but when they click "Reply", it's back to the sending email address again.
This is the function that I'm trying to write. It works well enough, except that I need to force a different Return-Path.
#!/usr/bin/python
import smtplib
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import sap_mailserverdata as sf
def send_mail(sent_to, subject, body_text, sent_from_addr='', sent_from_name='', files=[], cc=[], bcc=[]):
"""Send emails with or without attachments."""
assert type(sent_to)==list
assert type(files)==list
assert type(cc)==list
assert type(bcc)==list
message = MIMEMultipart()
message['From'] = sent_from_addr
message['To'] = COMMASPACE.join(sent_to)
message['Date'] = formatdate(localtime=True)
message['Subject'] = subject
message['Cc'] = COMMASPACE.join(cc)
message.preamble = 'You need a MIME enabled mail reader to see this message.\n'
message.attach(MIMEText(body_text, 'html'))
for f in files:
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(f, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
message.attach(part)
addresses = []
for x in sent_to:
addresses.append(x)
for x in cc:
addresses.append(x)
for x in bcc:
addresses.append(x)
mail_server = smtplib.SMTP(sf.server, sf.server_port)
mail_server.ehlo()
mail_server.set_debuglevel(1)
mail_server.starttls()
mail_server.login(sf.username, sf.password)
mail_server.sendmail(sent_from_addr, addresses, message.as_string())
mail_server.quit()
What am I missing with this function to be able to reliably specify a different replyto Return-Path?
|
Fuyusuke
[Résolu] Commande archiver plusieurs fichiers
Bonjour,
j'ai regardé dans la documentaion pour voir comment faire pour créer une archive.
Mais ce que j'aimerais, c'est archiver plusieurs fichiers, dans plusieurs archives.
Par exemple, j'ai un dossier "Test 01" et un autre "Test 02" et ainsi de suite. Et j'aimerais qu'en une ligne de commande, je me retrouve avec autant d'archive que de dossiers au départ, avec le nom 01.zip, 02.zip...
J'ai essayé ça, mais ça ne marche pas (ce que je me doutais) :
zip -r $1.zip "Dossier (\d{2})"
Je sais pas si c'est possible, si oui, comment faire ?
Ou bien en script genre en python qui permettrait de faire ça, n'importe en fait, tant que je peux archiver mes dossiers automatiquement sans les faire tous à la main.
Merci d'avance pour votre aide !
Dernière modification par Fuyusuke (Le 24/02/2010, à 21:32)
Hors ligne
sputnick
Re : [Résolu] Commande archiver plusieurs fichiers
for i in */; do zip -r "$i.zip" "$i"; done
de tete ( donc pas teste, je suis dans Les transports... )
bashfr.org(random);
<arciks1994> dou tu connai qel age j'ai ?
Hors ligne
credenhill
Re : [Résolu] Commande archiver plusieurs fichiers
hello
ls -d Test*|xargs -I{} zip -r "{}" "{}"
Hors ligne
Fuyusuke
Re : [Résolu] Commande archiver plusieurs fichiers
Merci pour vos réponses !
Aurez-vous par contre, l'amabilité de m'expliquer un peu comment ça fonctionne ? Histoire que je comprenne ce que je fais
Sans vouloir être trop exigeant, merci !
EDIT :
C'est bon, j'ai réussi avec un petit script python. Merci pour votre aide !
# -*- coding:Utf-8 -*-
import os
a = 1
nb = 2
pref = "Test_"
nom = "Test "
while (a <= nb):
if (a < 10):
a = "0" + str(a)
os.system("zip -r " + pref + a + ".zip \"" + nom + a + "\"")
a = int(a)
a = a + 1
Dernière modification par Fuyusuke (Le 24/02/2010, à 21:32)
Hors ligne
sputnick
Re : [Résolu] Commande archiver plusieurs fichiers
Ah wé, faut au moins ça :þ
Prochain defi, faire un tar.gz en Haskel
Plus serieusement :
for i in */; do # pour tous les chemins qui finissent par un / ( les répertoires quoi ) faire ( un à un ):
zip -r "$i.zip" "$i" # zipper dans la variable.zip le répertoire en cours
done # fin
Dernière modification par sputnick (Le 24/02/2010, à 23:43)
bashfr.org(random);
<arciks1994> dou tu connai qel age j'ai ?
Hors ligne
|
I'm really struggling with getting this to work. Basically, I want my script to get the "newID" value and use that as a look up value. If the "newID" is found in the OldID list then do one thing, else do something else. The problem I'm having is it only grabs the first ID value and then does loops the rest of the code based on whatever category the first ID fell under. I need it to get the value of each field in the new data table, and write it to the corresponding field in the old data table. It does this just fine, but obviously it isn't checking the ID's after the first one, or updating/appending the geometry.
Here's what I've got so far. Just showing applicable code....
rows = gp.SearchCursor(new_data)
row = rows.next()
while row:
newID = row.getValue('ID')
newShape = row.SHAPE
y = 0
while newID in OldID_List:
gp.AddMessage('')
print 'Starting the updating for ratios'
where = 'ID' + ' = ' + str(newID)
new_rows = gp.UpdateCursor(old_data, where)
new_row = new_rows.next()
while y <= len(Field_List): # checks to see if ID exists -
# this means just update
for each in Field_List:
newValue = row.getValue(each)
if newValue is None:
new_row.setValue(str(each), 0)
else:
new_row.setValue(str(each), str(newValue))
y += 1
if y > len(Field_List):
new_row.Shape = newShape
new_rows.UpdateRow(new_row)
new_row = new_rows.next()
row = rows.next()
newID = row.getValue('ID')
newShape = row.SHAPE
y = 0
while newID not in OldID_List: # these are new objects to be appended
flag = 1
nsert_Rows = gp.InsertCursor(old_data)
nsert_Row = nsert_Rows.NewRow()
while y <= len(Field_List):
for each in Field_List:
newValue = row.getValue(each)
print 'Starting appends'
if newValue is None:
nsert_Row.setValue(str(each), 0)
else:
nsert_Row.setValue(str(each), str(newValue))
y += 1
if y > len(Field_List):
nsert_Row.ID = newID
nsert_Row.Shape = newShape
nsert_Rows.insertrow(nsert_Row)
row = rows.next()
newID = row.getValue('ID')
newShape = row.SHAPE
appends += 1
y = 0
del rows
del new_rows
if flag == 1:
del nsert_Rows
Any help or suggestions would be appreciated.
Thanks.
|
I just updated matplotlib to 1.1.0 on a server running ubuntu 10.04 LTS in order to play better with pandas. Pandas was converting my index according the functionality of a different version of matplotlib. I installed on one server using "easyinstall -U matplotlib" and "pip install -U matplotlib" on the other.
I cannot plot in any of my previous working scripts or in ipython. show() has stopped working in pylab. Could someone point me in the direction of what may be broken?
I took the following test script "simple_plot.py" from matplotlib's site and tested it on various servers after first deleting my config directory.
from pylab import *
plot([1,2,3])
show()
simple_plot produces a plot on all servers that are running on versions <= 0.99 but has no output on version 1.1.
here is the debug output on one server that does not work:
$HOME=/home/michael
CONFIGDIR=/home/michael/.matplotlib
matplotlib data path /usr/local/lib/python2.6/dist-packages/matplotlib-1.1.0-py2.6-linux-x86_64.egg/matplotlib/mpl-data
loaded rc file /usr/local/lib/python2.6/dist-packages/matplotlib-1.1.0-py2.6-linux-x86_64.egg/matplotlib/mpl-data/matplotlibrc
matplotlib version 1.1.0
verbose.level debug
interactive is False
platform is linux2
Using fontManager instance from /home/michael/.matplotlib/fontList.cache
backend agg version v2.2
python version:2.6.5
findfont: Matching :family=sans-serif:style=normal:variant=normal:weight=normal:stretch=normal:size=medium to Bitstream Vera Sans (/usr/local/lib/python2.6/dist-packages/matplotlib-1.1.0-py2.6-linux- x86_64.egg/matplotlib/mpl-data/fonts/ttf/Vera.ttf) with score of 0.000000
|
My team has recently been working to refactor our existing, traditional web interface, in order to expose web services instead. In doing so, we've spun the old web front end out into a separate application, which calls the various web services to perform the critical work (most of this web code is automated, with just a few special cases so far).
Our web services are based on a RESTian framework, which has forced the refactoring down into more layers than just the web tier, since it is very much a paradigm shift in thinking. REST (Representational State Transfer) is a collection of design principles best embodied by the Web--stateless client/server protocol, a small set of well-defined operations, a universal syntax for resource identification, and hyperlinking between resources--and the exclusion of RPC-like ideas. The end result is, I believe, a much tighter codebase, and we've been able to chop out large chunks of now-unnecessary source; imagine an Army barber with a large pair of shears and a nervous, long-haired hippy, and you'll get an idea of the amount of virtual detritus we've managed to discard.
I've lately enjoyed a number of books and articles, such as Better, Faster, Lighter Java and The Pragmatic Programmer, which argue against complexity, or at the very least, urge developers to approach problems from a different point of view than the traditionally accepted enterprise architectures pushed by the big corporations. I believe a RESTian simplification fits comfortably within the precepts advanced by many of these texts. Of course, a significant percentage of the code reduction can be attributed to the benefit of hindsight you only get from refactoring, but certainly around 20-30 percent is a result of working within the constraints of a REST framework. We have added some complexity to the separated web application, but that's a small price to pay for the added flexibility you gain from decoupling (and considering the overall picture, we're still better off).
Related Reading
The refactoring has also forced me to reevaluate some past coding decisions, particularly in regard to following standard protocols (i.e., HTTP). For example, up until this project, I cannot recall ever implementing a servlet with more than doGet and doPost--certainly in the projects I've been involved with, I've never come across other source containing more than a bastardization of the fundamental uses of those two methods (by which I mean inserts, updates, and deletes performed by either doGet or doPost, or both). My feeling now is that this has unnecessarily complicated a number of my projects that would have been far more elegant, had I paid more attention to the standards.
In this article, I will present an alternative to basic web development taking into account some of these ideals: a RESTafarian adherence to the HTTP protocol, and using the flexibility proferred by Jython and Velocity in order to simplify servlet development.
One of the main problems we face with implementing more than just GET and POST is the lack of browser support. If you create a form with anything other than method="get" or method="post", most browsers will send an HTTP GET; this at least goes part way to explaining the historical abuse of the doGet and doPost servlet methods.
Luckily, browser support is relatively easy to subvert. One approach is to override the service method in a subclass of HttpServlet, and then have your servlets inherit from that class:
public void service(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
String override =
request.getParameter("method");
if (!StringUtils.isEmpty(override)) {
if (override.equals("delete")) {
doDelete(request, response);
return;
}
else if (override.equals("put")) {
doPut(request, response);
return;
}
}
super.service(request, response);
}
The service method looks for the parameter method, and if the value is delete or put, the requisite servlet methods are then called; otherwise, control is passed up to the HttpServlet superclass. This procedure will work; however, I also want to introduce more flexibility into my servlet development, so I'll be using a combination of Jython servlets and Velocity to create the web content instead.
One of the advantages that web-based scripting languages like PHP offer is a considerable flexibility in development--removing the necessity for the compile, package, deploy, and restart cycle of web development, which we've grown so accustomed to with Java. One alternative is Jython (based on Python), one of many scripting languages available for the JVM, which can provide a level of flexibility similar to PHP, without necessarily having to lose the power of Java.
The first step in this process is to download the Jython distribution. After downloading (at the time of this writing, Jython is distributed as a class file), you then run the Java class (e.g., java jython_21) to extract the Jython directory structure.
I use Jetty both during development and in production (just personal preference, but I've always found it much less hassle to play with than Tomcat). The next step is to copy jython.jar to Jetty's ext directory. Create a new directory for your web app (I'm calling mine test, so I've created $JETTY_HOME/webapps/test and $JETTY_HOME/webapps/test/WEB-INF directories accordingly), and then put the following web.xml (see the Resources section for this article's sample code) in the WEB-INF directory:
<?xml version = '1.0' encoding = 'UTF-8'?>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>test</display-name>
<description></description>
<servlet>
<servlet-name>PyServlet</servlet-name>
<servlet-class>org.python.util.PyServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>PyServlet</servlet-name>
<url-pattern>*.py</url-pattern>
</servlet-mapping>
</web-app>
Without going into too much detail about the workings of a web.xml file, since it's pretty much self-explanatory, this sets up a servlet provided in the Jython distribution, and then maps all URLs matching with an extension of .py to that servlet.
Jython also requires a number of supporting modules. At least with Jetty, you should be able to accomplish this by copying the entire Lib directory from the Jython distribution into the lib directory of your web app (in my case, $JETTY_HOME/webapps/test/WEB-INF/lib).
In the home directory of your web app, create the following Jython servlet in a file called test.py (see sample code in Resources):
from javax.servlet.http import HttpServlet
class test(HttpServlet):
def doGet(self, request, response):
w = response.getWriter()
w.println("hello world")
w.close()
Start Jetty (usually with the command java -jar start.jar from $JETTY_HOME), and point your browser at http://localhost:8080/test/test.py--you should see hello world displayed.
Sean McGrath, CTO of Propylon, gives an excellent tutorial on setting up Tomcat to run Jython servlets (as well as a basic introduction to Jython), if you want to delve more into the nitty-gritty detail. If you're new to Jython, there are a number of books available (O'Reilly has chapter 1 of Jython Essentials here) and the Jython website has a lot of useful information. You will also find the Python docs useful, bearing in mind that Jython is an implementation of version 2.1 of Python.
Now that we have Jython up and running on Jetty, we can deploy the modified servlet previously mentioned, so that PUT and DELETE are supported. However, rather than compiling a Java class, and sticking it somewhere in Jetty's classpath, we can recode as Python in a file called utils.py (see Resources):
from javax.servlet.http import HttpServlet
class enhancedservlet(HttpServlet):
def service(self, request, response):
override = request.getParameter('method')
if override and override != '':
getattr(self,
'do' +
override.lower().capitalize())\
(request, response)
else:
HttpServlet.service(self, request,
response)
There are a couple of things to note about the Jython version:
super keyword as such, so a call to the superclass, to handle cases where the method parameter is HttpServlet.service(...).
A simple subclass of enhancedservlet will look like this (in the file test2.py):
from utils import enhancedservlet
class test2(enhancedservlet):
def doGet(self, request, response):
w = response.getWriter()
w.println("hello world again")
w.close()
In case the ease of development isn't immediately obvious, change the println message and refresh your browser to see an instant change. In the words of Sean: Welcome to Java rapid development.
It's worth noting that you may need to restart your server in certain cases. Changes to dependent modules occasionally do not get picked up if there has been no change to the caller class/module. So if a servlet has not changed, but relies on a module that has been changed, this may require a web server restart.
To test that the override is working correctly, we can use the following servlet (which should be in a file named test3.py), again found in Resources):
from javax.servlet.http import HttpServlet
from utils import enhancedservlet
class test3(enhancedservlet):
def doGet(self, request, response):
w = response.getWriter()
w.println("I'm a GET")
w.close()
def doPost(self, request, response):
w = response.getWriter()
w.println("I'm a POST")
w.close()
def doPut(self, request, response):
w = response.getWriter()
w.println("I'm a PUT")
w.close()
def doDelete(self, request, response):
w = response.getWriter()
w.println("I'm a DELETE")
w.close()
And the HTML page (called methodtest.html):
<html> <form action="test3.py" method="GET"> <p>Test GET <input type="submit" /></p> </form> <form action="test3.py" method="POST"> <p>Test POST <input type="submit" /></p> </form> <form action="test3.py" method="POST"> <input type="hidden" name="method" value="PUT" /> <p>Test PUT <input type="submit" /></p> </form> <form action="test3.py" method="POST"> <input type="hidden" name="method" value="DELETE" /> <p>Test DELETE <input type="submit" /></p> </form> </html>
While neither very awe-inspiring nor particularly edifying, these examples do give us a starting point for a REST-style web application, where we can create HTML forms that call the protocol-correct servlet methods depending upon the operation (more on that below).
Velocity is a templating engine I've written about before, and including a template engine with Jython makes a big difference in simplifying development.
To use Velocity with Jython, we'll need to add a few more .jar files to Jetty's ext directory: log4j, Velocity and commons-collections. Also, Velocity will not work out-of-the-box with Jython-generated objects, so we need to customize the Velocity engine slightly. JythonUberspect is the customizer in question, and should be compiled into a .jar and also added to $JETTY_HOME/ext as well. To make your life easier, I've created the jyvel.jar file for you (which just contains JythonUberspect.java and the class files it produces when compiled) and can be found with the sample code. See Resources.
Once JythonUberspect has been included, we can modify enhancedservlet as follows, adding an init method:
from javax.servlet.http import HttpServlet
from org.apache.velocity.app import VelocityEngine
from org.apache.velocity.tools.\
generic.introspection import JythonUberspect
class enhancedservlet(HttpServlet):
ve = None
def init(self, config=None):
if config:
HttpServlet.init(self, config)
else:
HttpServlet.init(self)
if enhancedservlet.ve is None:
ve = VelocityEngine()
ve.setProperty(VelocityEngine.\
FILE_RESOURCE_LOADER_PATH,
self.getServletConfig().\
getServletContext().getRealPath('/') \
+ '/WEB-INF/templates')
ve.setProperty(VelocityEngine.\
FILE_RESOURCE_LOADER_CACHE, 'true')
ve.setProperty('input.encoding', 'UTF-8')
ve.setProperty(VelocityEngine.\
RUNTIME_LOG_LOGSYSTEM_CLASS,
'org.apache.velocity.runtime.log.\
SimpleLog4JLogSystem')
ve.setProperty(\
'runtime.log.logsystem.log4j.category',
VelocityEngine.getName())
ve.setProperty(VelocityEngine.\
UBERSPECT_CLASSNAME,
JythonUberspect.getName())
ve.init()
enhancedservlet.ve = ve
One point to note in this excerpt is that ve is a variable of the class, and therefore similar to a Java static. So rather than creating a new Velocity engine per servlet, we'll have one global engine. Templates are served from a templates directory in WEB-INF (i.e., ${YOUR_WEBAPP_DIR}/WEB-INF/templates). Keeping them in the WEB-INF directory keeps nosy surfers out of your template code. The completed enhancedservlet can be found in the sample code.
Now I want to create a (reasonably) standards-compliant servlet, using the correct HTTP methods for my operations. I'll start with a simple screen to display a data list, and then a screen to display a single record in editable form.
list.vm (see Resources) is the template for displaying lists of my data:
<html>
<body>
<table border="1">
#foreach ( $row in $rows )
<tr>
#foreach ( $col in $row.cols )
<td>
#if ( $col == $row.key )
<a href="test5.py?key=${col}">
${col}</a>
#else${col}#end</td>
#end
</tr>
#end
</table>
<a href="test5.py?key=None">Add</a>
</body>
</html>
You'll notice that I have a $rows object (which is a list), and each $row object has attributes for columns and its key. If the column matches the key, then I create a link for editing that row using the column value.
edit.vm is the template for editing a row of data:
<html>
<head>
<body>
<form action="test5.py" method="POST">
<table border="1">
#foreach ( $col in $obj.cols )
<tr>
<td>Column #${velocityCount}</td>
<td>
<input name="col${velocityCount}"
type="text"
#if ( $col == $obj.key )
disabled="disabled"
#end value="${col}" /></td>
</tr>
#end
</table>
<br />
<input type="hidden" name="key"
value="${obj.key}" />
<input type="hidden" name="method"
value="${method}" />
<input type="submit" value="Save" />
</form>
#if ( $method == 'POST' )
<form action="test5.py" method="GET">
<input type="hidden" name="key"
value="${obj.key}" />
<input type="hidden" name="method"
value="DELETE" />
<input type="submit" value="Delete" />
</form>
#end
<form action="test5.py" method="GET">
<input type="submit" value="Cancel" />
</form>
</body>
</html>
This displays the data columns, disabling the key value so it can't be edited. While I could use JavaScript to modify a form parameter for overriding the method, in this case I use multiple forms. The first gets a method parameter, which is passed from the servlet depending upon whether this is an existing record (therefore an UPDATE or doPost) or a new record (an INSERT or doPut). The second form--only displayed if this is an existing record, and therefore with the method set to POST--has the method override parameter set to DELETE, while the last is just a call back to the servlet with no parameters so we can display the list again.
The servlet (with the file name test5.py) looks like this, so far:
from javax.servlet.http import HttpServlet
from org.apache.velocity import VelocityContext
from utils import *
# a simple data object with a key and some columns
class dataobj:
def __init__(self, key, cols):
self.key = key
self.cols = cols
global sequence
sequence = 1
# a map containing data objects
mydata = { }
# prepopulate with a few rows
for sequence in xrange(1, 4):
mydata['row%s_key' % sequence] =
dataobj('row%s_key' % sequence,
[ 'row%s_key' % sequence,
'row%s_col2' % sequence,
'row%s_col3' % sequence ])
class test5(enhancedservlet):
def doGet(self, request, response):
ctx = VelocityContext()
key = request.getParameter('key')
if key:
t = enhancedservlet.ve.\
getTemplate('edit.vm')
if key != 'None':
ctx.put('obj', mydata[key])
ctx.put('method','POST')
else:
ctx.put('obj', dataobj('None',
[ 'None', '', '' ]))
ctx.put('method','PUT')
else:
t = enhancedservlet.ve.\
getTemplate('list.vm')
ctx.put('rows', mydata.values())
response.setContentType(\
'text/html;charset=UTF-8')
pw = response.getWriter()
t.merge(ctx, pw)
pw.close()
From the code above you can see that if the parameter key is present we use the template edit.vm; otherwise, we use list.vm. The Velocity context is populated with data depending upon whether key is an actual key value or set to None. In the case of None, we construct a blank data object and put that in the context. This much allows us to display a list of rows, and display a single row for editing.
Next I'll implement a doDelete method:
def doDelete(self, request, response):
key = request.getParameter('key')
if not key or key == '':
response.sendError(\
response.SC_BAD_REQUEST,
'no key specified')
return
if not mydata.has_key(key):
response.sendError(response.SC_NOT_FOUND,
'%s was not found' % key)
return
del mydata[key]
wrappedrequest = modifiablerequest(request)
wrappedrequest.delParameter('key')
self.doGet(wrappedrequest, response)
This method performs some simple validation (checking for the presence of a key parameter, and checking for the existence of that key), before deleting the data from the map. modifiablerequest (also found in utils.py) is a subclass of HttpServletRequestWrapper, and provides set and delete parameter methods, so a request may be modified and then pushed on to another method for processing. (In the above example, we perform the delete, then pass the request on to doGet after deleting the parameter key, so that doGet displays the main data list.)
The doPut method again performs some simple validation (also checking for the existence of a key parameter), before creating a data object and then adding it to the map. Again, processing is passed on to doGet:
def doPut(self, request, response):
key = request.getParameter('key')
if key and key != 'None':
response.sendError(\
response.SC_BAD_REQUEST,
'there is an existing key')
return
# generate a new key
global sequence
sequence = sequence + 1
key = 'row%s_key' % sequence
# create the data object
data = dataobj( key, [ key,
request.getParameter('col2'),
request.getParameter('col3') ])
mydata[key] = data
wrappedrequest = modifiablerequest(request)
wrappedrequest.delParameter('key')
self.doGet(wrappedrequest, response)
Finally, the doPost method checks for the existence of a key, and updates the requisite data object, before calling doGet:
def doPost(self, request, response):
key = request.getParameter('key')
if not key or key == 'None' or \
not mydata.has_key(key):
response.sendError(\
response.SC_BAD_REQUEST,
'invalid or missing key')
return
data = mydata[key]
data.cols[1] = request.getParameter('col2')
data.cols[2] = request.getParameter('col3')
wrappedrequest = modifiablerequest(request)
wrappedrequest.delParameter('key')
self.doGet(wrappedrequest, response)
Figures 1 to 3 show the final result when running the Jython servlet under Jetty. Figure 1 shows the initial list of data rows provided by the doGet, Figure 2 shows the edit screen when adding a record, and Figure 3 shows the list screen again after the row has been added.
Figure 1. The list data screen
Figure 2. The edit screen
Figure 3. Back to the list screen with a new row
This is a simple example, but hopefully gives you some idea of the flexibility of this approach. There is a clean delineation of operations and responsibilities within the servlet: Velocity gives you a nice separation of view and, combined with Jython, gives the flexibility of rapid web development. The amount of code you are required to write for a typical web app, particularly traditional GET/POST servlets handling a variety of different operations, can be prodigious, so sticking to the HTTP protocol does force you to cut to the essentials. But certainly, in my experience, simplifying your code to basic HTTP operations does not necessarily mean losing functionality for your end users, and it can help focus your efforts on the important fundamentals.
Jason R. Briggs is an architect/developer working in the United Kingdom.
Return to ONJava.com.
Copyright © 2009 O'Reilly Media, Inc.
|
redelap
Réponses : 5
Bonjour à tous (et à toutes)
Je viens d'installer dans VirtualBox une version Ubuntu 14.04 (avec le bureau Unity) et une version Ubuntu 14.04 Gnome
Ces deux versions se sont parfaitement bien installées (dans un but de tests divers... (sur Mac) après les téléchargements "iso" correspondants
Au lancement l'affichage de chaque version se réalise dans une fenêtre 640 x 480, obstruant une partie d'écran proposé par ubuntu
Dans "Affichage" de "Paramètres système" il n'y a que cette option 640 x 480 de définie
Et je ne sais pas si je dois agir au niveau d'Ubuntu ou au niveau de VirtualBox pour obtenir une fenêtre de travail digne de ce nom...
je me souviens l'avoir déjà réalisé.. mais mon vieux neurone semble vite se fatiguer...
Une piste ?
Merci de vos lumières
redelap
Réponses : 5
merci de répondre.
Non... pas de "détecter les écrans" . Mais comme les affichages ne sont visibles qu'en partie, je ne peux appercevoir ce qui est proposé plus bas et plus à droite de la partie visible...
Dans les autres virtualisations que j'ai déjà réalisé, il n'y avait aucun problème... et je pouvais afficher plusieurs formats d'écrans. (avec le même Mac donc avec la même carte graphique
Là j'ai une fenêtre d'affichage presque carrée.
Dans la barre de menu de VirtualBox, j'ai "Ecran" --> passer en mode redimentionné , qui est coché... mais aucune autre option.
Les caractères lisibles sont "tirés" en hauteur, et les cercles ovales... Beurk...
redelap
Réponses : 5
Après réflexion, et quelques essais...je me rends compte qu'au lancement de Virtualbox, la fenêtre a déjà pris sa taille pas conforme...
D'ailleurs sur une des machines virtuelles, l'option "taille de l'écran automatique" est Cochée ET en grisée.. donc inaccessible...
Il doit manquer à VirtualBox un paramètre pour ces nouvelles versions d'Ubuntu...
Et très difficile (voir impossible pour moi) d'afficher dans le terminal le caractère " | "... je ne peux donc répondre à la question posée par alca94
Peut-etre que des utilisateurs de virtualbox utilisant la 14.04 pourraient m'orienter (ou m'informer)
Merci de votre aide.
redelap
Réponses : 5
Très curieux..
Allez savoir pourquoi !
La fenêtre de la version 14.04 Gnome est passée (juste en relançant la machine virtuelle) en 1024 x 768, et propose aussi le 800 x 600
L'autre fenêtre (de la version Unity) reste en 640 x 480 avec vue partielle..
On va continuer à chercher !
Mais je pense que c'est VirtualBox qui est la cause de ce petit bug... sauf erreur.
Sinon, j'utilise un petit laptop eePC avec écran secondaire 17" sous débian, et c'est le top !
Bonne soirée à tous
et merci !
redelap
Réponses : 1
Bonjour !
Avec FireFox...
Sur un compte Mail Yahoo, se glisse depuis quelque temps UN email de PUB en première ligne qui ne possède pas de case à cocher et qu'il n'est pas possible d'effacer.
Sur Mac, on peut le faire disparaître en allant dans une autre boite (("envoyés" ou "brouillons") et en revenant dans la bite de réception... En général il disparait ou en affiche un autre
Par contre sur une machine avec Ubuntu 12.04 impossible d'effacer ce mail quelque peu intrusif...
Cette intrusion m'incommode assez...
En fait ce mail n'est qu'un bouton qui renvoi à un site de pub...
j'ai pu en copier un
https://beap.gemini.yahoo.com/mbclk?bv=1.0.0&es=oXca2gMGIS.Wnsb8BtMC8CSxeaM2VgWeaeD2tynvQu.mEKtDjmsVmo8UmOEhcY0Y
g90VN2Vkwn7oPyltl0HIlmapBMuPPZNC7BKEEgJQdXauU6No.kNXDAB5PUzMQLc1_wEPf8uBYotG0FajUYn3q3R_EqPtDoiY2OmIqVS0Ga1
WYCCBNVNIaQT2Dpx4lCXDb.OzuN60w66CwmosDsr5rNcsy3Na4pZ2NZlBMx7u2xxc9awEgFXkFHNDP0K.1GIzRjKmQ54Mc7wY0jxs
Tq_oblraKmU2boz5jhs4AjSK._5pBHxxtIRs4CQG7y_qxZQ_XevNWMEjdDDBT5SoRn2XSczE8SraO3Fpy31WV0dIgSS86cwohM0F.Svz
2BlZzz.y7aMy_miofaAOGPCKNruj367FzpewLtR4NHsIU8lHel9VaXGiDHDpCDpLivLitdSFV8n72ZfnULfLv9e3dYryA2hKJkJFgdbJQ8Js
2NYs_t5OazOxtVEvKyLDgoKraDH96du90X8niWqeReGPCfW6S6rTsoW0cu4.2o5wK75OTTp4JT2yxA--%26lp=
.
En fait plusieurs copies du lien pointent vers le site suivanthttps://beap.gemini.yahoo.com/mbclk
Avez-vous eu ce genre de problème ?
Si oui, l'avez-vous résolu ?
Et si oui, comment ?
Merci de vos lumières
redelap
Réponses : 4
Bonjour.
Sur mon Laptop EeePC 1005HA, j'ai procédé à la MàJ 12.04 --> 13.10 puis 13.10 --> 14.04
Tout semble s'être parfaitement bien passé...
Sauf que l'ensemble est devenu très lent, si lent que je le crois parfois planté...
Les messageries et les sites FireFox, Dropbox, et les logiciels spécifiques Ubuntu (mise à jour, synapsis, etc...) sont tous devenus très lents...
Une idée ?
merci d'avance de vos lumières....
redelap
Réponses : 36
Voici le résultat demandé:
Effectivement je crois que de nombreux site "archives" seraient peut-etre obsoletes
linux@linux-laptop:~$ cat /etc/apt/sources.list
# deb cdrom:[Ubuntu 10.04 LTS _Lucid Lynx_ - Release i386 (20100429)]/ lucid main restricted
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://fr.archive.ubuntu.com/ubuntu/ precise main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://fr.archive.ubuntu.com/ubuntu/ precise-updates main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-updates main restricted
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://fr.archive.ubuntu.com/ubuntu/ precise universe
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise universe
deb http://fr.archive.ubuntu.com/ubuntu/ precise-updates universe
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-updates universe
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://fr.archive.ubuntu.com/ubuntu/ precise multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ precise-updates multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-updates multiverse
## Uncomment the following two lines to add software from the 'backports'
## repository.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
# deb-src http://fr.archive.ubuntu.com/ubuntu/ lucid-backports main restricted universe multiverse
## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
deb http://archive.canonical.com/ubuntu precise partner
deb-src http://archive.canonical.com/ubuntu precise partner
deb http://security.ubuntu.com/ubuntu precise-security main restricted
deb-src http://security.ubuntu.com/ubuntu precise-security main restricted
deb http://security.ubuntu.com/ubuntu precise-security universe
deb-src http://security.ubuntu.com/ubuntu precise-security universe
deb http://security.ubuntu.com/ubuntu precise-security multiverse
deb-src http://security.ubuntu.com/ubuntu precise-security multiverse
# deb http://packages.medibuntu.org/ precise free non-free # désactivé pour la mise à niveau vers precise
deb http://fr.archive.ubuntu.com/ubuntu/ precise-proposed restricted main multiverse universe
Je pense qu'il va me falloir modifier ce fichier selon le tuto cité plus haut...
Peut-etre un fichier "sources" type ?
redelap
Réponses : 36
Je n'arrive pas à modifier ce fichier "sources.list"
la commande
sudo nano /etc/apt/sources.list/
m'ouvre un fichier vierge..
Et l'ouverture de ce même fichier directement avec gedit m'interdit la sauvegarde après modification (root)
Désolé... mais y'a plein de trucs que je ne sais pas faire... dans la pratique..
Je sais que cela doit en agacer quelques uns..
Dans le dossier "apt" j'ai 2 "sources.list": un "sources.list" et un "sources.list.distUpgrade"
redelap
Réponses : 36
Je confirme que
gksudo gedit /etc/apt/sources.list
m'ouvre un fichier vierge... dans " /etc/apt/sources.list/gksudo"
??????
OUPS ! je suis arrivé à le modifier.. je vais maintenant voir ce que cela donne.
Merci de votre patience..
redelap
Réponses : 36
J'arrive maintenant à ouvrir et à modifier le fichier "sources.list"
J'ai neutralisé (#) les lignes ".....restricted"
Sauvegarde..
Vérification que la sauvegarde à bien été effective
...
Redemarrage
"L'application "Sources de logiciels" a quitté de façon inatendue"
Je ne comprends pas...
redelap
Réponses : 36
J'ai retenté un
sudo apt-get install --reinstall software-properties-gtk
Mais il me répond que la réinstallation n'a pas été possible car "le fichier ne peut être telechargé"...
Je suis connecté...
Encore un serveur mal désigné ?
redelap
Réponses : 36
Il s'agit d'un laptop en 12.04 (pas celui qui est dans ma signature)
J'ai peut-être trouvé la cause du problème mais je ne sais pas le résoudre...
J'ai tapé
software-properties-gtk
dans le terminal
D'une part il affiche une fenêtre comme quoi l'application a planté
Mai j'obtiens sur le terminal l'info suivante
linux@linux-laptop:~$ software-properties-gtk
Traceback (most recent call last):
File "/usr/bin/software-properties-gtk", line 38, in <module>
from softwareproperties.gtk.SoftwarePropertiesGtk import SoftwarePropertiesGtk
File "/usr/lib/python2.7/dist-packages/softwareproperties/gtk/SoftwarePropertiesGtk.py", line 45, in <module>
from softwareproperties.SoftwareProperties import SoftwareProperties
File "/usr/lib/python2.7/dist-packages/softwareproperties/SoftwareProperties.py", line 54, in <module>
from cloudarchive import shortcut_handler as ca_shortcut_handler
ValueError: bad marshal data (unknown type code)
La dernière ligne est probablement la cause du problème...
Mais je ne sais pas du tout ce que cela veut dire...
Donc je n'accède pas à l'interface graphique qui me permetrait de gérer les serveurs malgré la réinstall de "software-properties-gtk"
redelap
Réponses : 36
Alors j'ai donc tapé ces commandes (corrigé deux erreur de frappe)
résultat total avant essai
linux@linux-laptop:~$ sudo apt-get remove --purge software-properties-gtk
[sudo] password for linux:
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-43-generic-pae python-renderpm
linux-headers-3.2.0-34-generic linux-headers-3.2.0-60-generic
linux-headers-3.2.0-60-generic-pae gir1.2-ubuntuoneui-3.0
linux-headers-3.2.0-34 linux-headers-3.2.0-43 linux-headers-3.2.0-44
linux-headers-3.2.0-45 linux-headers-3.2.0-51 linux-headers-3.2.0-53
linux-headers-3.2.0-54 linux-headers-3.2.0-60 linux-headers-3.2.0-59
linux-headers-3.2.0-45-generic python-reportlab-accel
linux-headers-3.2.0-44-generic-pae linux-headers-3.2.0-59-generic-pae
linux-headers-3.2.0-53-generic firefox-globalmenu
linux-headers-3.2.0-34-generic-pae libubuntuoneui-3.0-1
linux-headers-3.2.0-53-generic-pae linux-headers-3.2.0-43-generic
linux-headers-3.2.0-59-generic linux-headers-3.2.0-45-generic-pae
linux-headers-3.2.0-51-generic linux-headers-3.2.0-54-generic
linux-headers-3.2.0-54-generic-pae python-reportlab
linux-headers-3.2.0-44-generic linux-headers-3.2.0-51-generic-pae
Veuillez utiliser « apt-get autoremove » pour les supprimer.
Les paquets suivants seront ENLEVÉS :
apturl* nautilus-share* software-properties-gtk* ubuntu-desktop*
0 mis à jour, 0 nouvellement installés, 4 à enlever et 0 non mis à jour.
Après cette opération, 639 ko d'espace disque seront libérés.
Souhaitez-vous continuer [O/n] ? o
(Lecture de la base de données... 1111749 fichiers et répertoires déjà installés.)
Suppression de nautilus-share ...
Suppression de apturl ...
Suppression de ubuntu-desktop ...
Suppression de software-properties-gtk ...
Purge des fichiers de configuration de software-properties-gtk ...
Traitement des actions différées (« triggers ») pour « gconf2 »...
Traitement des actions différées (« triggers ») pour « man-db »...
Traitement des actions différées (« triggers ») pour « bamfdaemon »...
Rebuilding /usr/share/applications/bamf.index...
Traitement des actions différées (« triggers ») pour « desktop-file-utils »...
Traitement des actions différées (« triggers ») pour « gnome-menus »...
Traitement des actions différées (« triggers ») pour « shared-mime-info »...
Unknown media type in type 'all/all'
Unknown media type in type 'all/allfiles'
Unknown media type in type 'uri/mms'
Unknown media type in type 'uri/mmst'
Unknown media type in type 'uri/mmsu'
Unknown media type in type 'uri/pnm'
Unknown media type in type 'uri/rtspt'
Unknown media type in type 'uri/rtspu'
Traitement des actions différées (« triggers ») pour « hicolor-icon-theme »...
linux@linux-laptop:~$
linux@linux-laptop:~$
linux@linux-laptop:~$
linux@linux-laptop:~$
linux@linux-laptop:~$
linux@linux-laptop:~$ sudo apt-get autoclean
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
Del unity-greeter 0.2.9-0ubuntu1.3 [90,2 kB]
Del libsane-dev 1.0.22-7ubuntu1 [4 208 kB]
Del libsensors4-dev 1:3.3.1-2ubuntu1 [37,7 kB]
Del update-manager-core 1:0.156.14.13 [181 kB]
Del libqt4-declarative 4:4.8.1-0ubuntu4.8 [1 086 kB]
Del update-manager-kde 1:0.156.14.14 [5 486 B]
Del libgegl-0.0-0 0.0.22-2ubuntu3 [350 kB]
Del libgphoto2-2-dev 2.4.13-1ubuntu1.2 [2 464 kB]
Del linux-headers-3.2.0-61-generic 3.2.0-61.92 [978 kB]
Del python-dev 2.7.3-0ubuntu2.2 [1 098 B]
Del update-manager-kde 1:0.156.14.13 [5 484 B]
Del libqt4-sql-mysql 4:4.8.1-0ubuntu4.8 [30,3 kB]
Del libv4l-dev 0.8.6-1ubuntu2 [7 888 B]
Del g++-4.6 4.6.3-1ubuntu5 [6 745 kB]
Del whoopsie 0.1.34 [26,2 kB]
Del lightdm 1.2.3-0ubuntu2.5 [98,8 kB]
Del libbabl-0.0-0 0.0.22-1.1 [78,3 kB]
Del libieee1284-3-dev 0.2.11-10build1 [49,0 kB]
Del libqt4-scripttools 4:4.8.1-0ubuntu4.8 [229 kB]
Del icedtea-6-jre-jamvm 6b30-1.13.1-1ubuntu2~0.12.04.3 [549 kB]
Del libqt4-assistant 4:4.8.1-0ubuntu4.8 [8 016 B]
Del linux-headers-generic-pae 3.2.0.61.72 [2 394 B]
Del gnome-control-center 1:3.4.2-0ubuntu0.13.2 [664 kB]
Del bluez-alsa 4.98-2ubuntu7.2 [133 kB]
Del libalgorithm-diff-xs-perl 0.04-2build2 [12,9 kB]
Del libqt4-sql 4:4.8.1-0ubuntu4.8 [100 kB]
Del libgpg-error-dev 1.10-2ubuntu1 [23,1 kB]
Del liblightdm-gobject-1-0 1.2.3-0ubuntu2.5 [31,9 kB]
Del bluez 4.98-2ubuntu7.2 [979 kB]
Del linux-generic 3.2.0.61.72 [1 724 B]
Del python-ubuntuone-client 3.0.2-0ubuntu2.1 [228 kB]
Del libqt4-xmlpatterns 4:4.8.1-0ubuntu4.8 [1 057 kB]
Del libpng12-dev 1.2.46-3ubuntu4 [207 kB]
Del linux-image-3.2.0-61-generic 3.2.0-61.92 [38,2 MB]
Del libcups2 1.5.3-0ubuntu8.1 [172 kB]
Del libavahi-client-dev 0.6.30-5ubuntu2.1 [36,7 kB]
Del libtool 2.4.2-1ubuntu1 [302 kB]
Del libqt4-opengl 4:4.8.1-0ubuntu4.8 [300 kB]
Del openssh-client 1:5.9p1-5ubuntu1.4 [960 kB]
Del libqt4-webkit 4:4.8.1-0ubuntu4.8 [8 008 B]
Del libavahi-common-dev 0.6.30-5ubuntu2.1 [42,5 kB]
Del icedtea-6-jre-cacao 6b30-1.13.1-1ubuntu2~0.12.04.3 [770 kB]
Del libqt4-svg 4:4.8.1-0ubuntu4.8 [140 kB]
Del libcupsppdc1 1.5.3-0ubuntu8.1 [53,3 kB]
Del bluez-alsa 4.98-2ubuntu7.1 [133 kB]
Del libltdl-dev 2.4.2-1ubuntu1 [203 kB]
Del linux-headers-3.2.0-61-generic-pae 3.2.0-61.92 [979 kB]
Del libcupscgi1 1.5.3-0ubuntu8.1 [30,2 kB]
Del openjdk-6-jre-lib 6b30-1.13.1-1ubuntu2~0.12.04.3 [6 211 kB]
Del libqt4-network 4:4.8.1-0ubuntu4.8 [556 kB]
Del libqt4-dbus 4:4.8.1-0ubuntu4.8 [185 kB]
Del libusb-dev 2:0.1.12-20 [34,1 kB]
Del cups-client 1.5.3-0ubuntu8.1 [169 kB]
Del libbluetooth3 4.98-2ubuntu7.2 [63,5 kB]
Del update-manager 1:0.156.14.13 [609 kB]
Del libgnome-control-center1 1:3.4.2-0ubuntu0.13.2 [79,2 kB]
Del bluez-cups 4.98-2ubuntu7.1 [71,2 kB]
Del libqt4-core 4:4.8.1-0ubuntu4.8 [6 264 B]
Del libqtcore4 4:4.8.1-0ubuntu4.8 [2 061 kB]
Del iproute 20111117-1ubuntu2.3 [443 kB]
Del dpkg 1.16.1.2ubuntu7.3 [1 814 kB]
Del libqt4-qt3support 4:4.8.1-0ubuntu4.8 [1 044 kB]
Del bluez-gstreamer 4.98-2ubuntu7.1 [105 kB]
Del build-essential 11.5ubuntu2.1 [5 796 B]
Del libcupsmime1 1.5.3-0ubuntu8.1 [13,7 kB]
Del autotools-dev 20120210.1ubuntu1 [42,4 kB]
Del libcupsdriver1 1.5.3-0ubuntu8.1 [19,9 kB]
Del libqt4-script 4:4.8.1-0ubuntu4.8 [800 kB]
Del libbluetooth3 4.98-2ubuntu7.1 [63,6 kB]
Del openjdk-6-jre-headless 6b30-1.13.1-1ubuntu2~0.12.04.3 [35,0 MB]
Del bluez 4.98-2ubuntu7.1 [978 kB]
Del qdbus 4:4.8.1-0ubuntu4.8 [29,0 kB]
Del linux-libc-dev 3.2.0-61.92 [863 kB]
Del bluez-cups 4.98-2ubuntu7.2 [71,1 kB]
Del libcupsimage2 1.5.3-0ubuntu8.1 [52,4 kB]
Del ubuntuone-client 3.0.2-0ubuntu2.1 [45,4 kB]
Del libwrap0-dev 7.6.q-21 [23,6 kB]
Del libalgorithm-merge-perl 0.08-2 [12,7 kB]
Del libjpeg8-dev 8c-2ubuntu7 [1 544 B]
Del libp11-kit-dev 0.12-2ubuntu1 [45,6 kB]
Del libqt4-xml 4:4.8.1-0ubuntu4.8 [96,1 kB]
Del libusb-1.0-0-dev 2:1.0.9~rc3-2ubuntu1 [156 kB]
Del libsyncdaemon-1.0-1 3.0.2-0ubuntu2.1 [46,3 kB]
Del cups-ppdc 1.5.3-0ubuntu8.1 [29,8 kB]
Del unity-greeter 0.2.9-0ubuntu1.4 [90,3 kB]
Del openssh-server 1:5.9p1-5ubuntu1.4 [343 kB]
Del linux-image-generic 3.2.0.61.72 [2 388 B]
Del g++ 4:4.6.3-1ubuntu5 [1 444 B]
Del libqt4-sql-sqlite 4:4.8.1-0ubuntu4.8 [22,9 kB]
Del update-manager 1:0.156.14.14 [609 kB]
Del libstdc++6-4.6-dev 4.6.3-1ubuntu5 [1 643 kB]
Del fakeroot 1.18.2-1 [87,9 kB]
Del jockey-gtk 0.9.7-0ubuntu7.15 [9 122 B]
Del software-properties-gtk 0.82.7.7 [34,6 kB]
Del adobe-flashplugin 11.2.202.350-0precise1 [6 599 kB]
Del linux-headers-generic 3.2.0.61.72 [2 386 B]
Del zlib1g-dev 1:1.2.3.4.dfsg-3ubuntu4 [162 kB]
Del linux-headers-3.2.0-61 3.2.0-61.92 [11,7 MB]
Del ssh-askpass-gnome 1:5.9p1-5ubuntu1.4 [15,8 kB]
Del cups-common 1.5.3-0ubuntu8.1 [823 kB]
Del libqt4-designer 4:4.8.1-0ubuntu4.8 [3 653 kB]
Del linux-firmware 1.79.13 [28,0 MB]
Del libqt4-test 4:4.8.1-0ubuntu4.8 [61,8 kB]
Del libqt4-help 4:4.8.1-0ubuntu4.8 [211 kB]
Del adobe-flash-properties-gtk 11.2.202.350-0precise1 [132 kB]
Del gnome-control-center-data 1:3.4.2-0ubuntu0.13.2 [1 118 kB]
Del cups 1.5.3-0ubuntu8.1 [1 283 kB]
Del cups-bsd 1.5.3-0ubuntu8.1 [43,9 kB]
Del gnome-settings-daemon 3.4.2-0ubuntu0.6.6 [479 kB]
Del simple-scan 3.4.4-0ubuntu1 [118 kB]
Del libjpeg-dev 8c-2ubuntu7 [1 536 B]
Del comerr-dev 2.1-1.42-1ubuntu2 [42,4 kB]
Del bluez-gstreamer 4.98-2ubuntu7.2 [105 kB]
Del libqtgui4 4:4.8.1-0ubuntu4.8 [4 123 kB]
Del openjdk-6-jre 6b30-1.13.1-1ubuntu2~0.12.04.3 [236 kB]
Del python-qt4-dbus 4.9.1-2ubuntu1 [15,7 kB]
Del jockey-common 0.9.7-0ubuntu7.15 [133 kB]
Del libalgorithm-diff-perl 1.19.02-2 [50,7 kB]
Del update-manager-core 1:0.156.14.14 [181 kB]
linux@linux-laptop:~$ sudo apt-get update
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 Release
Atteint http://fr.archive.ubuntu.com precise-updates Release
Atteint http://archive.canonical.com precise Release.gpg
Atteint http://security.ubuntu.com precise-security Release.gpg
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/universe i386 Packages
Atteint http://fr.archive.ubuntu.com precise/multiverse i386 Packages
Atteint http://fr.archive.ubuntu.com precise/multiverse TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/universe TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-updates/universe Sources
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse Sources
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/multiverse TranslationIndex
Atteint http://archive.canonical.com precise Release
Atteint http://fr.archive.ubuntu.com precise-updates/universe TranslationIndex
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/universe Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/universe Translation-fr
Atteint http://security.ubuntu.com precise-security Release
Atteint http://fr.archive.ubuntu.com precise/universe Translation-en
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/universe Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/universe Translation-en
Atteint http://archive.canonical.com precise/partner Sources
Atteint http://security.ubuntu.com precise-security/main Sources
Atteint http://archive.canonical.com precise/partner i386 Packages
Ign http://archive.canonical.com precise/partner TranslationIndex
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://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
Atteint http://security.ubuntu.com precise-security/restricted Translation-en
Atteint http://security.ubuntu.com precise-security/universe Translation-en
Ign http://archive.canonical.com precise/partner Translation-fr_FR
Ign http://archive.canonical.com precise/partner Translation-fr
Ign http://archive.canonical.com precise/partner Translation-en
Lecture des listes de paquets... Fait
et ...
linux@linux-laptop:~$ sudo apt-get install software-properties-gtk
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-43-generic-pae python-renderpm
linux-headers-3.2.0-34-generic linux-headers-3.2.0-60-generic
linux-headers-3.2.0-60-generic-pae gir1.2-ubuntuoneui-3.0
linux-headers-3.2.0-34 linux-headers-3.2.0-43 linux-headers-3.2.0-44
linux-headers-3.2.0-45 linux-headers-3.2.0-51 linux-headers-3.2.0-53
linux-headers-3.2.0-54 linux-headers-3.2.0-60 linux-headers-3.2.0-59
linux-headers-3.2.0-45-generic python-reportlab-accel
linux-headers-3.2.0-44-generic-pae linux-headers-3.2.0-59-generic-pae
linux-headers-3.2.0-53-generic firefox-globalmenu
linux-headers-3.2.0-34-generic-pae libubuntuoneui-3.0-1
linux-headers-3.2.0-53-generic-pae linux-headers-3.2.0-43-generic
linux-headers-3.2.0-59-generic linux-headers-3.2.0-45-generic-pae
linux-headers-3.2.0-51-generic linux-headers-3.2.0-54-generic
linux-headers-3.2.0-54-generic-pae python-reportlab
linux-headers-3.2.0-44-generic linux-headers-3.2.0-51-generic-pae
Veuillez utiliser « apt-get autoremove » pour les supprimer.
Les NOUVEAUX paquets suivants seront installés :
software-properties-gtk
0 mis à jour, 1 nouvellement installés, 0 à enlever et 0 non mis à jour.
Il est nécessaire de prendre 34,6 ko dans les archives.
Après cette opération, 326 ko d'espace disque supplémentaires seront utilisés.
Réception de : 1 http://security.ubuntu.com/ubuntu/ precise-security/main software-properties-gtk all 0.82.7.5 [34,6 kB]
34,6 ko réceptionnés en 0s (94,9 ko/s)
Sélection du paquet software-properties-gtk précédemment désélectionné.
(Lecture de la base de données... 1111675 fichiers et répertoires déjà installés.)
Dépaquetage de software-properties-gtk (à partir de .../software-properties-gtk_0.82.7.5_all.deb) ...
Traitement des actions différées (« triggers ») pour « bamfdaemon »...
Rebuilding /usr/share/applications/bamf.index...
Traitement des actions différées (« triggers ») pour « desktop-file-utils »...
Traitement des actions différées (« triggers ») pour « gnome-menus »...
Traitement des actions différées (« triggers ») pour « hicolor-icon-theme »...
Traitement des actions différées (« triggers ») pour « shared-mime-info »...
Unknown media type in type 'all/all'
Unknown media type in type 'all/allfiles'
Unknown media type in type 'uri/mms'
Unknown media type in type 'uri/mmst'
Unknown media type in type 'uri/mmsu'
Unknown media type in type 'uri/pnm'
Unknown media type in type 'uri/rtspt'
Unknown media type in type 'uri/rtspu'
Traitement des actions différées (« triggers ») pour « man-db »...
Paramétrage de software-properties-gtk (0.82.7.5) ...
Je remet en route et je teste..
redelap
Réponses : 36
je tapes les commandes du #28
linux@linux-laptop:~$ sudo apt-get install ubuntu-desktop
[sudo] password for linux:
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
Aucune version du paquet ubuntu-desktop n'est disponible, mais il existe dans la base
de données. Cela signifie en général que le paquet est manquant, qu'il est devenu obsolète
ou qu'il n'est disponible que sur une autre source
E: Le paquet « ubuntu-desktop » n'a pas de version susceptible d'être installée
suivi de...
linux@linux-laptop:~$ sudo apt-get install nautilus-share
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
Aucune version du paquet nautilus-share n'est disponible, mais il existe dans la base
de données. Cela signifie en général que le paquet est manquant, qu'il est devenu obsolète
ou qu'il n'est disponible que sur une autre source
E: Le paquet « nautilus-share » n'a pas de version susceptible d'être installée
et de ...
linux@linux-laptop:~$ sudo apt-get install apturl
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
Aucune version du paquet apturl 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
Cependant les paquets suivants le remplacent :
apturl-common
E: Le paquet « apturl » n'a pas de version susceptible d'être installée
et enfin le dernier...
linux@linux-laptop:~$ sudo apt-get autoremove
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
Les paquets suivants seront ENLEVÉS :
firefox-globalmenu gir1.2-ubuntuoneui-3.0 libubuntuoneui-3.0-1
linux-headers-3.2.0-34 linux-headers-3.2.0-34-generic
linux-headers-3.2.0-34-generic-pae linux-headers-3.2.0-43
linux-headers-3.2.0-43-generic linux-headers-3.2.0-43-generic-pae
linux-headers-3.2.0-44 linux-headers-3.2.0-44-generic
linux-headers-3.2.0-44-generic-pae linux-headers-3.2.0-45
linux-headers-3.2.0-45-generic linux-headers-3.2.0-45-generic-pae
linux-headers-3.2.0-51 linux-headers-3.2.0-51-generic
linux-headers-3.2.0-51-generic-pae linux-headers-3.2.0-53
linux-headers-3.2.0-53-generic linux-headers-3.2.0-53-generic-pae
linux-headers-3.2.0-54 linux-headers-3.2.0-54-generic
linux-headers-3.2.0-54-generic-pae linux-headers-3.2.0-59
linux-headers-3.2.0-59-generic linux-headers-3.2.0-59-generic-pae
linux-headers-3.2.0-60 linux-headers-3.2.0-60-generic
linux-headers-3.2.0-60-generic-pae python-renderpm python-reportlab
python-reportlab-accel
0 mis à jour, 0 nouvellement installés, 33 à enlever et 0 non mis à jour.
Après cette opération, 713 Mo d'espace disque seront libérés.
Souhaitez-vous continuer [O/n] ? o
(Lecture de la base de données... 1111714 fichiers et répertoires déjà installés.)
Suppression de firefox-globalmenu ...
Suppression de gir1.2-ubuntuoneui-3.0 ...
Suppression de libubuntuoneui-3.0-1 ...
Suppression de linux-headers-3.2.0-34-generic-pae ...
Suppression de linux-headers-3.2.0-34-generic ...
Suppression de linux-headers-3.2.0-34 ...
Suppression de linux-headers-3.2.0-43-generic-pae ...
Suppression de linux-headers-3.2.0-43-generic ...
Suppression de linux-headers-3.2.0-43 ...
Suppression de linux-headers-3.2.0-44-generic-pae ...
Suppression de linux-headers-3.2.0-44-generic ...
Suppression de linux-headers-3.2.0-44 ...
Suppression de linux-headers-3.2.0-45-generic-pae ...
Suppression de linux-headers-3.2.0-45-generic ...
Suppression de linux-headers-3.2.0-45 ...
Suppression de linux-headers-3.2.0-51-generic-pae ...
Suppression de linux-headers-3.2.0-51-generic ...
Suppression de linux-headers-3.2.0-51 ...
Suppression de linux-headers-3.2.0-53-generic-pae ...
Suppression de linux-headers-3.2.0-53-generic ...
Suppression de linux-headers-3.2.0-53 ...
Suppression de linux-headers-3.2.0-54-generic-pae ...
Suppression de linux-headers-3.2.0-54-generic ...
Suppression de linux-headers-3.2.0-54 ...
Suppression de linux-headers-3.2.0-59-generic-pae ...
Suppression de linux-headers-3.2.0-59-generic ...
Suppression de linux-headers-3.2.0-59 ...
Suppression de linux-headers-3.2.0-60-generic-pae ...
Suppression de linux-headers-3.2.0-60-generic ...
Suppression de linux-headers-3.2.0-60 ...
Suppression de python-renderpm ...
Suppression de python-reportlab-accel ...
Suppression de python-reportlab ...
Traitement des actions différées (« triggers ») pour « libc-bin »...
ldconfig deferred processing now taking place
Je redemarre ?
redelap
Réponses : 36
J'ai relancé, cliqué sur ignorer
Dans ce cas je n'ai plus la petite fenêtre.. mais il ne se passe rien : pas d'accès aux paramètres...
Je vais arrêter là et rendre la machine..
Je te remercie de m'avoir aidé...
Je règlerai le problème en procédant à une sauvegarde de ses documents, et j'installerai un système neuf avec une partition "home-data" à part..
Merci à vous tous .
|
I have a self-signed root certificate and an intermediate certificated signed by that root. Basically something like this:
.
└── master (CA)
└── servant1 (CA)
I have a few client certificates which are derived from the master->servant1 certificate chain:
.
└── master (CA)
└── servant1 (CA)
├── client1
├── client2
└── client3
I'm looking to authenticate these client certificates in nginx and I'm having a lot of trouble doing so.
Here's my nginx configuration:
upstream luci {
server localhost:8080;
}
server {
listen 127.0.0.1:80;
server_name myserver;
return 301 https://$host$request_uri;
}
server {
listen 127.0.0.1:443;
server_name myserver;
ssl on;
ssl_certificate /etc/nginx/certs/myserver.crt;
ssl_certificate_key /etc/nginx/certs/myserver.key;
ssl_session_timeout 5m;
ssl_prefer_server_ciphers on;
ssl_protocols TLSv1.2 TLSv1.1;
ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AES:!ECDH+3DES:!DH+3DES:!RSA+3DES:!aNULL:!MD5:!DSS;
ssl_client_certificate /etc/nginx/certs/servant1-ca-chain.crt;
ssl_verify_client on;
ssl_verify_depth 2;
location / {
proxy_pass http://luci;
}
}
This should be pretty straightforward. All client certificates signed by the intermediate servant1 CA should be allowed to connect to nginx.
However, when I attempt to access the server with these client certificates, I get this:
(obviously an incredibly detailed and helpful error)
I find this in my logs:
2013/12/01 22:46:18 [alert] 7478#0: *5 ignoring stale global SSL error (SSL: error:0407006A:lib(4):func(112):reason(106) error:04067072:lib(4):func(103):reason(114) error:0D0C5006:lib(13):func(197):reason(6)) while reading client request line, client: 192.168.1.208, server: myserver
Useful information here is:
ignoring stale global SSL error
What's going wrong and how can I fix it?
|
What is the best style for a Python method that requires the keyword argument 'required_arg':
def test_method(required_arg, *args, **kwargs):
def test_method(*args, **kwargs):
required_arg = kwargs.pop('required_arg')
if kwargs:
raise ValueError('Unexpected keyword arguments: %s' % kwargs)
Or something else? I want to use this for all my methods in the future so I'm kind of looking for the best practices way to deal with required keyword arguments in Python methods.
|
Based on that, here's a code I came up with:
class KeyboardLocker:
def __init__(self, serio=0):
self._on = False
self.serio = serio
def on(self):
return self._on
def write_value(self,path, value):
with open(path, "a") as f:
f.write(value)
def toggle(self):
if self.on():
self.turn_off()
else:
self.turn_on()
def description(self):
path = '/sys/devices/platform/i8042/serio%d/description' % (self.serio,)
with open(path, "r") as f:
description = f.read()
return description
def turn_on(self):
try:
self.write_value('/sys/devices/platform/i8042/serio%d/bind_mode' % (self.serio,),
'auto')
except IOError, e:
self._on = False
raise
else:
self._on = True
return self.on()
def turn_off(self):
try:
self.write_value('/sys/devices/platform/i8042/serio%d/bind_mode' % (self.serio,),
'manual')
self.write_value('/sys/devices/platform/i8042/serio%d/drvctl' % (self.serio,),
'psmouse')
except IOError, e:
self._on = True
raise
else:
self._on = False
return self.on()
if __name__ == "__main__":
kl = KeyboardLocker(serio=0)
device = kl.description()
print "We got a lock on", device
proceed = raw_input("Do you want to proceed? (y/n)").lower().startswith("y")
import sys
if not proceed: sys.exit(1)
kl.turn_off()
import time
wait = 5
print "Sleeping few seconds...", wait
time.sleep(wait)
print "Voila!"
kl.turn_on()
raw_input("Does it work now?")
Tested on Linux Mint 12, X11, HP Laptop, Gnome. Not sure if any of that matters though :)
UPDATE Added an option to change the path, e.g. "serio0" or "serio1". And prints the description, for me serio0 gave me: i8042 KBD port, most likely if you have "KBD" in it, it's right, continue, otherwise I give you no guarantee :)
|
I am new to pytest and am trying to convert some functional test scripts into ones that play nicely with pytest. My module has custom error types and I'm trying to use the "with pytest.raises() as excinfo " method. This is a scientific/numerical package and I need to test that certain methods are consistent when called, so I can't just drill down to the lower-level stuff. Thanks
What is stopping you importing the specific exception and using it in your
# your code
class CustomError(Exception):
pass
def foo():
raise ValueError('everything is broken')
def bar():
raise CustomError('still broken')
#############
# your test
import pytest
# import your module, or functions from it, incl. exception class
def test_fooErrorHandling():
with pytest.raises(ValueError) as excinfo:
foo()
assert excinfo.value.message == 'everything is broken'
def test_barSimpleErrorHandling():
# don't care about the specific message
with pytest.raises(CustomError):
bar()
def test_barSpecificErrorHandling():
# check the specific error message
with pytest.raises(MyErr) as excinfo:
bar()
assert excinfo.value.message == 'oh no!'
def test_barWithoutImportingExceptionClass():
# if for some reason you can't import the specific exception class,
# catch it as generic and verify it's in the str(excinfo)
with pytest.raises(Exception) as excinfo:
bar()
assert 'MyErr:' in str(excinfo)
|
spyke
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
jerhum oki mais alors je ny arrive pas a les faire tourner justement est ce normale comme wolfenstein , quake4 etc.....
Hors ligne
foxylechou
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
il faut autoriser le fichier a être exécuter dans propriétés
ofwgkta
------------------------------------------------------------------
Hors ligne
andycam
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
Bonjour,
Quel est le(s) jeux (toute catégories confondues) qui est unique Linux et que l'on ne retrouve donc nul part ?
Merci,
Andycam
Hors ligne
gayelene
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
bonjour svp je veux installer le jeu MONOPOLY sur mon pc
aidez moisvp comment faire?
merci davance
Hors ligne
forficule
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
@andycam : un jeu que sous linux, ça colle pas avec ce qu'est linux, si tu as le code source (c'est le cas de beaucoup de jeux sous linux), tu peux le compiler pour d'autres plateformes (macosx, win32...). Honnêtement un jeu qui ne tournerait QUE sous linux, je ne vois pas...
Hors ligne
Calinou
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
Ouais c'est bien mumble, mais Ya pas la 1.2.0...
Hors ligne
ArnaudK
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
Bonjour, est-il possible de poster un lien vers un site de revente de jeux linux qui fait des promos ? Je sais que c'est mal vu car certains penseraient que c'est du SPAM
Hors ligne
ArnaudK
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
Ne serait il pas bon d'ajouter les sites revendeurs de jeux Linux, qu'ils soient français ou internationaux ? ça se compte sur les doigts des deux mains, mais ça pourrait être intéressant.
Hors ligne
KazukyAkayashi
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
Il y a LGP : http://www.linuxgamepublishing.com/
Sinon j'en parlerai, mais le mieux est de venir faire des propositions sur le forum jeuxlinux
Mon Blog --> http://kazuky.homelinux.net/blog
Hors ligne
Crone123
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
Bonjour,
Moi j'ai ce message qui s'affiche tout le temps:
Traceback (most recent call last):
File "djl_main.py", line 747, in timerEvent
self.maj_liste()
File "/home/valentin/djl/djl/diff.py", line 1125, in maj_liste
self.etat(self.nom_jeu_depot())
File "djl_main.py", line 809, in etat
self.verif_maj_jeu(nom_jeu)
File "/home/valentin/djl/djl/diff.py", line 295, in verif_maj_jeu
version = self.detail_jeux(no_description, type_info = 'version')
File "/home/valentin/djl/djl/diff.py", line 72, in detail_jeux
sortie = self.parse_detailjeux(no_jeu, 0)
File "/home/valentin/djl/djl/depot.py", line 72, in parse_detailjeux
return self.detailjeux['item'][val]['value']
AttributeError: 'Ui_Djl' object has no attribute 'detailjeux'
Quelqu'un sait ce que c'est?
Merci
Hors ligne
waston
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
salut a tous
je suis nouveau sur ubuntu et sur le forum.
j'ai un petit coup de gueule a pousser parce que la je me sent tout perdu et pas une personne pour me répondre clairement
j' ai viré w7 de mon pc parce qu'il faisait planter ma machine. j'installe ubuntu 64 bits, super.
mais voila que sa ce complique. je sais pas ouvrir un seul programme .exe. j'installe donc wine et wintricks. (il m'as fallu chercher pour trouver sa) ensuite je m'aperçois que fsx pas moyen de l'installer et football manager 2009 non plus ( j'ai était sur la page d'explication pour installer fm2009 et franchement sa marche pas) l'installe ne bouge plus, pourtant je tape tout ce qu'il demande avec E=enter et S et T etc et sa marche pas. j'ai toujours une page grise même après avoir installer direct3d comme demander dans l'explication, et je sais même pas quand l'instal sera finie, bref deux jeux, deux problème. je précise que j'ai ce pc pour moi jouer( le pc pour travailler reste au travail lol)
si sous w7 je sais rien installer et maintenant sous ubuntu non plus. j'ai des jeux que je peux mettre a la poubelle et bref mon pc aussi. alors si quelqu'un a une solution miracle , merci de m'aider parce que franchement ras le bol. la seul excuse que ubuntu as par rapport a windows c'est que lui, il est gratuit. sinon c'est le même problème. les créateur de système d'exploitation oublie un peu beaucoup les gamer je trouve. (je suis gamer mais pas informaticien, alors si vous savais m'aider expliquer moi sans mot trop technique s'il vous plait. merci)
Hors ligne
atichu
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
LEs fichier .EXE c'est des fichiers Windows pas linux/ubuntu... donc tu veux installer des roues de 2CV sur une porche. Tu comprend le bléme?
en général les jeu ubuntu sont dans des dêpot ou sont des .deb qui installe le jeu.
sinon voir la documention sur le forum /jeu ou le site
Alors pour les gamers, faut se plaindre au fabriquand de jeu qui ne fond pas tout des version linux. mais si tu cherche il y en a quand même. certain gros gamers jour a WOW sous linux mais vu qu'il y a pas de version linux c'est pas tout les jours facile.
Dernière modification par atichu (Le 31/03/2011, à 16:14)
Je ne suis pas un geek ni un informaticien mais j'aime linux/ubuntu.
acer aspire5741G (unity 12.04))+une vieillebousse(xfce 12.04)
+teste de la version instable
Hors ligne
keld
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
la seul excuse que ubuntu as par rapport a windows c'est que lui, il est gratuit. sinon c'est le même problème. les créateur de système d'exploitation oublie un peu beaucoup les gamer je trouve. (je suis gamer mais pas informaticien, alors si vous savais m'aider expliquer moi sans mot trop technique s'il vous plait. merci)
Je te comprends tout a fait, moi aussi raz le cul, la dernière fois j'ai voulu mettre le dvd, fraichement payé, de Gran Turismo 5 sur ma Wii, bah tu sais quoi? Ça ne voulais pas marché!!! Y'en a marre de ces fabriquant de console qui ne s'occupe pas des gamer!!!
L122-1 Powaaaa!!!!!
Hors ligne
waston
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
je pense que ubuntu est quand même très intéressent; vue que c'est asse facile de l'utiliser. maintenant je vais chercher de mon cote mais.... les jeux linux on les a ou? et franchement es qu'il en val le coup? je suis curieux . maintenant je vais essayer quand meme d'obtenir un windows xp pro 64 bits( w7 c'est vraiment de la M... ) pour pouvoir jouer a mes jeux favoris. en dual boot avec ubuntu je devrais être comblé.
merci pour vos réponse. en effet je comprend mieux le problème vue la comparaison avec la deudeuche.
Hors ligne
goahead
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
Salut Waston,j'ai eu le meme probleme que toi au début mais maintenant ca va, la facons simple avec Wine c'est que quand tu veux installer un jeu tu va dans la CONFIGURATION de Wine et tu vas dans l'onglet (LECTEUR) situé en haut,
une page apparait de tous tes lecteur tu clics sur la lettre de ton lecteur que tu as incerré ton jeu et tu fais (PARCOURIRE) situé un peu plus bas.
La une fenetre s'ouvre avec tout tes fichier,tu choisi MEDIA tu double clic dessus,apres le nom de ton jeu apparait tu double clic dessus et tu fais OK.ensuite la fenetre se ferme, apres tu fais APPLIQUER.
Tu ouvre WINE tu fais désinstaller un logiciel WINE, tu tappes sur installer tu clic sur la petite fleche verte,jusqua tant de voir ceci / tu vas voir la page est pleinne de fichiers tu trouve MEDIA tu double clic dessus le fichier de ton jeu apparait,
tu double clic dessus et tu vas voir apparaitre les fichiers du jeu avec SETUP.EXE tu double clic dessus et l'installation commence. c'est de meme que je procede c'est une facon simple.
Ca c'est bon pour les DVDROM.
Ce qui est des jeux avec plusieurs CD ex: DIABLO 2 tu vas encore dans CONFIGURATION de Wine tu vas dans LECTEUR tu clic sur la lettre de ton LECTEUR,et tu inscis en bas dans la bar /media/cdrom0 et tu fais APPLIQUER.
Tu ouvre Wine et tu fais comme je t'ai dit un peu plus haut tu clic sur la fleche verte et tu va chercher MEDIA tu double clic dessus apres le nom de ton jeux apparait tu double clic dessud et tu fais SETUP.EXE.
Lorsequ'il te demande d'incerer le DISC 2 tu vas dans ton terminal (ca c'est important) tu tape sudo eject -a
sinon ca na marchera pas entout cas pas pour moi,il faut que je fasse cela pour que ca fonctionne.Tu n'éjecte pas ton jeux manuellement.
Si tu suit ce que je t'ai écris ca devrais fonctionner.
Bonne chance.
Dernière modification par goahead (Le 28/05/2011, à 07:44)
Hors ligne
Crone123
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
Ouais, mais Wine, ça reste léger, pour ne pas dire complètement nul...
Hors ligne
goahead
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
Pourquoi est-ce que tu dis ca?
Hors ligne
SlimGary
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
les créateur de système d'exploitation oublie un peu beaucoup les gamer je trouve.
! C'est pas les développeurs d'OS les fautifs, au contraire, ils mettent des outils de développement à disposition ! Non, les vrais fautifs sont clairement et simplement les éditeurs de jeux ... Et si tu trouves que les développeurs d'OS ne sont pas assez compétents, vas t'acheter une PS3 ou une XboX 360 !
Ouais, mais Wine, ça reste léger, pour ne pas dire complètement nul...
Rien a dire ... ah si, scandaleux !
Hors ligne
Nemr0D
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
Merci ! C'est très interresent !
Hors ligne
Crone123
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
Pourquoi est-ce que tu dis ca?
C'est la vérité, 90% des programmes ne marchent pas, ou marchent mal, et ça crée des tonnes de raccourcis dans la liste de lancement de programmes (donc quand on choisis une application avec laquelle ouvrir un fichier, c'est mort.. [Wine affiche 90programmes supplémentaires dans la liste et c'est souvent 20fois le meme..]), bon, en plus l'affichage est pas Super Joli... (dans le programme, il pourrais y avoir un design Windows plus beau, ou le design de GNOME..)
Bref, en tout cas, tous les jeux que j'ai testé sur Wine, qui sont pourtant certifiés, fonctionne bien sur Wine (depuis le site officiel), j'ai eu des désastres....
Pour être franc je ne l'utilise plus, si j'ai vraiment besoin d'un programme Windows, je lance Windows (env 1fois par mois..), mais sinon, je trouve toujours ce que je cherche en natif. (surtout pour développer..)
J'utilise surtout mon PC le développement (donc j'ai tout ce qu'il faut en natif) et pour les jeux libres (même si je pense que les développeurs libres devraient faire plus souvent des .deb parce qu'un développeur php "amateur" français ne sait pas forcément compiler un programme C++ en lisant des instructions en anglais, surtout quand il viens d'avoir son brevet.. [Oui je suis encore étudiant...])
Donc, Linux reste Linux, pour des programmes Linux, et Windows reste Windows avec des programmes Windows, c'est sûrement la meilleure chose quand on a pas envie d'encombrer son PC avec des tonnes de trucs qui marchent a moitié, et dont on ne vas pas forcément se servir du coup.
Et effectivement, si les développeurs pensaient un peu plus aux autres OS, ça serait mieux. (voir normal.), remarquez, il y a de plus en plus de jeux payants natifs dans la logithèque, peut être que la tendance va changer du coté des gros jeux (Call Of Duty, Crysis, Trackmania, ...) et peut être que l'on pourra les trouver en natif dans la Logithèque
→Il faudrait faire une loi qui indique ceci:
"Lorsque un développeur sort un programme payant (ou logiciel d'installation [je pense aux imprimantes, scanner par exemple]), il doit en fournir un version pour chaque OS (donc, une Windows, une Linux, et une Mac OS), si il ne veut pas la compiler pour X raison, il doit proposer les sources du logiciel de façon a ce que les utilisateurs (ou communautés) puissent les compiler pour leurs OS (et donc, en faire des .deb pour les dépôts)"
Et ça, ça serait normal, pourquoi privilégier un OS instable payant, plutôt qu'un OS stable libre?
Hors ligne
goahead
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
Oui je suis daccord avec toi,mais si il venait a faire une loi du genre se qui est peu probable pour les raison de droit faudrait que Linux déboursse d'importante somme d'argent pour avoir c'est jeu natif.
Comme Wine est une petite communauté il n'ont pas l'argent nécéssaiore pour faire se qu'ils aimerrait faire c'est pour ca que faire un don a ces programmes aide a la communauté de se développer.
Hors ligne
Rαiden
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
Désolé de casser votre réflexion mais je ne suis pas d'accord pour ce genre de loi. Chacun fait ce qu'il veut, si les éditeurs n'ont envie de sortir leurs jeux et logiciels que pour Windows grand bien leur fasse mais hors de question d'obliger les gens à le faire. Sinon Je trouve que cela va à l'encontre des principes de liberté qui animent GNU/Linux à la base ce serait dommage, quand on force les gens à faire quelque chose on sait tous ce que ça donne des choses bâclées voir inutilisables.
Concernant Wine en fait Wine existe en premier lieu à travers Crossover qui est une entreprise commerciale c'est vrai qu'ils n'ont pas énormément d'argent mais ils ont un statut d'entreprise qui peut au moins peut faire écho dans le milieu. Comme ils ont un pied dans le propriétaire ça serait cool qu'il prennent au moins la place laissez vacante par Cedega vis à vis de certains éditeurs.
Hors ligne
goahead
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
Je suis d'accord avec toi aussi,mais ne serrait-il pas le temps pour Linux de vouloir faire plaisir au Linuxiens d'avoir des jeux qu'ont pourraient jouer sans se casser la tete, a savoir si Wine va l'accepter je sais que le sujet c'est déjà parlé,mais la on est en 2011 et c'est le temps que Linux fasse le saut.Je sais que ca couterait des sous mais les jeux ont les achetent,donc un revenu pour Linux.
Hors ligne
Rαiden
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
En fait le problème (pour moi ça n'en est pas un mais bon) vient du fait que Linux est un noyau et seulement un Noyau il n'a qu'une fonction technique et pas franchement politique à part celle le concernant. Là ou le lobbying doit être fait c'est au niveau des distributions Ubuntu par exemple et comme on a 50 000 distributions ça n'aide pas à créer de grosses structures influentes qui peuvent rivaliser avec Microsoft et Apple. Du fait qu' il n'y ai pas de grosse structure la pression sur les éditeurs de jeux-vidéos est nulle c'est donc les développeurs qui choisissent en leur âme et conscience de développer pour GNU/Linux, moi je préfère honnêtement car c'est un acte en général altruiste et ça le reste. Quand un jeu sort sous GNU/Linux tu sais que c'est parce que le développeur à un attachement particulier à notre plateforme, qu'il a voulu faire plaisir à tous les utilisateurs et ça ça fait chaud au coeur. Parfois pour les développeurs indépendant c'est pour des raisons financières mais même si c'est le cas ce sont des gens qu'il faut encourager car ils sont l'avenir du secteur.
Comme tu vois ce n'est pas à Linux de faire plaisir aux Linuxiens, Linux n'est qu'un noyau c'est aux éditeurs/développeurs de se bouger le cul car tous les outils existent pour développer correctement sous GNU/Linux c'est juste le choix de ne pas le faire pour des raisons financières en ce qui les concerne.
Dernière modification par Rαίdeη (Le 23/07/2011, à 08:10)
Hors ligne
goahead
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
Merci de ton idée,je viens d'en apprendre beaucoup,se qui reste le mieux pour les jeux c'est un bon Xbox 360 ou un Playstation.Mais il reste que et j'espere, que Linux devienne plus qu'un simple Noyau.Il disent que Linux Mint est le 4eme systeme d'exploitation le plus utilisé au monde,il pourrait sen doute grossire la machine,mais c'est un peu comme si on voudrait changer la mentalité de LInux et je ne pense pas qu'il sont pret pour cela. Je me trompe peut-etre j'en suis sure que quelqu'un saura me le dire.
Hors ligne
|
chaoswizard
Re : TVDownloader: télécharger les médias du net !
Une idée ca pourrait sympas aussi de récupérer a partir de daylimotion ou youtube : vous savez genre des chaines de groupe :
http://www.youtube.com/user/ProdigyChannel
exemple france inter : http://www.dailymotion.com/franceinter
C'est jouable.
Dans ce cas là, il faudrait faire en sorte que l'utilisateur rentre les liens RSS des pages en question.
Ubuntu ==> Debian ==> Archlinux
Hors ligne
BmD_Online
Re : TVDownloader: télécharger les médias du net !
Je suis en train de bosser sur un plugin Arte.
Pour l'instant, j'ai repris le principe d'Arte Live Web, presque terminé.
Ensuite je regarderai pour Arte+7.
Hors ligne
chaoswizard
Re : TVDownloader: télécharger les médias du net !
Super !
Inspire toi des autres plugins.
Dernière modification par chaoswizard (Le 26/07/2010, à 14:04)
Ubuntu ==> Debian ==> Archlinux
Hors ligne
inbox
Re : TVDownloader: télécharger les médias du net !
Salut,
Abonnement.
Un problème résolu ? Indiquez le en modifiant le titre du sujet.
Linux user 449594
Hors ligne
BmD_Online
Re : TVDownloader: télécharger les médias du net !
Super !
Inspire toi des autres plugins.
Yep, c'est ce que j'ai fait.
C'est bon ça marche :
j'obtiens la liste des catégories, les émissions par catégorie (lien, date, titre).
Par contre, les téléchargements ne marchent pas. Les liens rtmp://.... sont valides mais pas téléchargés.
Hors ligne
Litteul-Korrigan
Re : TVDownloader: télécharger les médias du net !
Yop, un p'tit message juste pour dire que tout fonctionne impec chez moi.
J'ai du lancer la première fois par terminal, depuis, no problem.
Linux: Si les Gendarmes y arrivent, tout le monde peut y arriver.
Hors ligne
chaoswizard
Re : TVDownloader: télécharger les médias du net !
Pour l'instant, le programme utilise flvstreamer pour les liens rtmp.
Tu l'as bien d'installé (si oui, quelle version) ?
Dernière modification par chaoswizard (Le 26/07/2010, à 14:20)
Ubuntu ==> Debian ==> Archlinux
Hors ligne
BmD_Online
Re : TVDownloader: télécharger les médias du net !
Pour l'instant, le programme utilise flvstreamer pour les liens rtmp.
Tu l'as bien d'installé (si oui, quelle version) ?
Pour un lien du type :
rtmp://arte.fcod.llnwd.net/a2306/o25/MP4:liveweb/stream/680_chanson_du_dimanche_hd.mp4
J'utilise généralement rtmpdump (j'ai la version 2.2e), avec cette syntaxe :
rtmpdump --host arte.fcod.llnwd.net -a a2306/o25 -y MP4:liveweb/stream/680_chanson_du_dimanche_hd.mp4 -o chanson_du_dimanche.mp4
A coté, j'ai la version 1.9 de flvstreamer.
flvstreamer -r rtmp://arte.fcod.llnwd.net/a2306/o25/MP4:liveweb/stream/680_chanson_du_dimanche_hd.mp4 -o chanson_du_dimanche.mp4
En mode verbose, j'ai cette erreur :
NetStream.Play.StreamNotFound>
Hors ligne
BmD_Online
Re : TVDownloader: télécharger les médias du net !
Tiens, une question.
Par défaut, c'est le plugin de Canal qui s'affiche. On peut modifier ça, pour avoir un autre plugin (de son choix) par défaut ?
Hors ligne
chaoswizard
Re : TVDownloader: télécharger les médias du net !
Tiens, une question.
Par défaut, c'est le plugin de Canal qui s'affiche. On peut modifier ça, pour avoir un autre plugin (de son choix) par défaut ?
Pour l'instant non, un jour, sans doute !
rtmpdump marche mieux que flvstreamer ?
Il n'est pas possible de faire directement un
rtpmdump rtmp://arte.fcod.llnwd.net/a2306/o25/MP4:liveweb/stream/680_chanson_du_dimanche_hd.mp4 -o chanson_du_dimanche.mp4
Sinon, ta version de flvstreamer me parait vieille, il faudrait sans doute faire une mise à jour.
Mais si rtpmdump est dans les dépôts, on va sans doute basculer sur celui ci !
EDIT : Il semble bien dans les dépôts
Dernière modification par chaoswizard (Le 26/07/2010, à 15:02)
Ubuntu ==> Debian ==> Archlinux
Hors ligne
BmD_Online
Re : TVDownloader: télécharger les médias du net !
Pour rtmpdump/flvstreamer, je vais regarder un peu.
Coté développement des plugins, j'ai une suggestion à faire :
On a, d'une part, la fonction qui liste les émissions d'une chaine
listerEmissions( self, chaine )
D'autre part, on a ensuite la fonction qui liste les fichiers d'une émission
listerFichiers( self, emission )
Lorsqu'on arrive au moment de lister les fichiers de l'émission, il serait utile de connaitre également la chaine en question (de rajouter le paramètre chaine à la fonction listeFichiers).
Dans le cas du plugin Arte que je prépare, j'ai besoin de savoir sur quelle "chaine" je suis (Arte+7 ou ArteLive) pour fonctionner différemment.
A part retrouver la chaine par rapport au nom de l'émission, je n'ai aucune solution pour l'instant.
Il se pourrait d'ailleurs qu'on ait une même émission sur plusieurs chaines (qui sait).
Hors ligne
rudy1210
Re : TVDownloader: télécharger les médias du net !
Saludos
Je m'abonne et je suis ça...
Comme Litteul Korrigan, premier lancement depuis terminal puis OK...
Je trouve que la recherche d'émissions sur Pluzz lag...
a+
Intel® Core™ i7 920 - Noctua NH-U9B SE2 - Asus P6T Deluxe V2 - G.Skill Kit Extreme3 3 x 1 Go PC12800 NQ - Nvidia Geforce 7300GT fanless - OCZ Vertex Series SSD 30 Go 64 Mo - Seagate Barracuda 7200.12 - 1 To - Samsung SpinPoint F1 - HD103UJ - 1 To 7200 RPM (X2) - X-Fi Platinum Fatal1ty Champion Series - AverMedia dvb-T 771 - Natty Narwhal 11.04
Hors ligne
Vermouth
Re : TVDownloader: télécharger les médias du net !
Yop, un p'tit message juste pour dire que tout fonctionne impec chez moi.
J'ai du lancer la première fois par terminal, depuis, no problem.
c'est parce que:
Je trouve que la recherche d'émissions sur Pluzz lag...
Oui ça je vous avais avertie que ça prenais du temps. C'est juste pour le premier démarrage, après la liste des émissions sont sauvegardé.
Ça devrai s'améliorer avec les prochaines versions.
Hors ligne
chaoswizard
Re : TVDownloader: télécharger les médias du net !
Coté développement des plugins, j'ai une suggestion à faire :
On a, d'une part, la fonction qui liste les émissions d'une chaine<metadata lang=Batchfile prob=0.04 />
listerEmissions( self, chaine )
D'autre part, on a ensuite la fonction qui liste les fichiers d'une émission
listerFichiers( self, emission )
Lorsqu'on arrive au moment de lister les fichiers de l'émission, il serait utile de connaitre également la chaine en question (de rajouter le paramètre chaine à la fonction listeFichiers).
Dans le cas du plugin Arte que je prépare, j'ai besoin de savoir sur quelle "chaine" je suis (Arte+7 ou ArteLive) pour fonctionner différemment.
A part retrouver la chaine par rapport au nom de l'émission, je n'ai aucune solution pour l'instant.
Il se pourrait d'ailleurs qu'on ait une même émission sur plusieurs chaines (qui sait).
J'ai eu ce problème pour RadioFrance et j'ai résolu ça facilement.
def listerEmissions( self, chaine ):
self.derniereChaine = chaine
Comme l'ordre d'appel est tjrs : Site => Chaine => Emission => Fichier, ça roule !
Dernière modification par chaoswizard (Le 26/07/2010, à 17:07)
Ubuntu ==> Debian ==> Archlinux
Hors ligne
BmD_Online
Re : TVDownloader: télécharger les médias du net !
J'ai eu ce problème pour RadioFrance et j'ai résolu ça facilement.
def listerEmissions( self, chaine ):
self.derniereChaine = chaine
Comme l'ordre d'appel est tjrs : Site => Chaine => Emission => Fichier, ça roule !
Effectivement, je vais faire ça.
Hors ligne
Vermouth
Re : TVDownloader: télécharger les médias du net !
Ouai mais c'est pas propre car l'appel à listerFichiers dépend du précédent appel à lesterEmissions.
Le plus simple c'est de mémoriser:
-la liste des émissions pour chaque chaîne
-la liste des fichiers pour chaque émission (au fur et à mesure des appels à listerFichiers, juste pour pas faire deux fois de suite la même requette sur le web si on revient sur une émission déjà sélectionnée précédemment).
Si vous avez besoin de méthode pour effectuer des tâches répétitive (qui peut servir pour plus d'un plugin), faite moi signe (mail). Le but à la fin c'est qu'il y est plein de méthode générique sur la classe Plugin (qui sert à faire les plugins). Le reste du code ne devrais pas avoir à être utilisée.
Si vos plugins on des problèmes d'accent, la version qu'on va mettre ce soir va résoudre définitivement le problème.
Hors ligne
BmD_Online
Re : TVDownloader: télécharger les médias du net !
Ouai mais c'est pas propre car l'appel à listerFichiers dépend du précédent appel à lesterEmissions.
Le plus simple c'est de mémoriser:
-la liste des émissions pour chaque chaîne
-la liste des fichiers pour chaque émission (au fur et à mesure des appels à listerFichiers, juste pour pas faire deux fois de suite la même requette sur le web si on revient sur une émission déjà sélectionnée précédemment).
Si vous avez besoin de méthode pour effectuer des tâches répétitive (qui peut servir pour plus d'un plugin), faite moi signe (mail). Le but à la fin c'est qu'il y est plein de méthode générique sur la classe Plugin (qui sert à faire les plugins). Le reste du code ne devrais pas avoir à être utilisée.
Si vos plugins on des problèmes d'accent, la version qu'on va mettre ce soir va résoudre définitivement le problème.
Pour l'histoire de la chaine à mémoriser, je vais essayer de revoir mon code.
Pour les accents, j'ai bien galéré entre les iso8859-1, les utf8... mais je m'en suis sorti en faisant les bonnes conversions là où il faut. Enfin... j'espère.
Hors ligne
mydjey
Re : TVDownloader: télécharger les médias du net !
Abonnement.
Mon site : http://mydjey.eu/
Hors ligne
Vermouth
Re : TVDownloader: télécharger les médias du net !
Pour les accents, j'ai bien galéré entre les iso8859-1, les utf8... mais je m'en suis sorti en faisant les bonnes conversions là où il faut. Enfin... j'espère.
Dans la prochaine version (demain au plus tard je pense) il n'y aura plus ce genre de problème. Suffira d'éclaircir ton code et de remplacé une méthode (tu parle du contenu téléchargé je suppose).
Puisque t'a utilisé la classe Web je suppose ?
Utiliser le code de l'application (autre que les méthodes de Plugin) ça pose des problèmes de compatibilité dans le future (genre si on supprime la classe Web bein ton plugin marche plus). A proscrire donc (comme j'ai dit juste avant, faire une demande).
Si tu l'as pas utilisé bein c'est tant mieux ^^ !
Dernière modification par Vermouth (Le 26/07/2010, à 18:39)
Hors ligne
chaoswizard
Re : TVDownloader: télécharger les médias du net !
BmD_Online, tu peux poster ton code qu'on l’intègre dans la prochaine version ?
Ubuntu ==> Debian ==> Archlinux
Hors ligne
pascal92
Re : TVDownloader: télécharger les médias du net !
Il n'est pas possible de faire directement un
rtpmdump rtmp://arte.fcod.llnwd.net/a2306/o25/MP4:liveweb/stream/680_chanson_du_dimanche_hd.mp4 -o chanson_du_dimanche.mp4
Bonsoir,
Non ce n'est pas possible, RtmpDump (et je suppose Flvstreamer) n'arrive pas à parser l'URL si elle n'est pas découpée.
J'avais étudié ce problème en mettant au point Arte Live Web pour TVO.
Bon courage pour votre projet
Hors ligne
BmD_Online
Re : TVDownloader: télécharger les médias du net !
Oui j'utilise la classe web.
J'utilise aussi la classe fichier, évidemment.
Pour l'instant, j'utilise aussi des fonctions de conversions d'encodage, ainsi que de nettoyage des entités html.
Je suppose que ça sera fait automatiquement avec ta future version.
Pour le plugin, je continue un peu d'avancer avant de poster.
J'ai fini Arte Live Web et je bosse sur Arte+7.
Si c'est bon, ça donnera une pré-version assez propre (mais à faire évoluer).
Dernière modification par BmD_Online (Le 26/07/2010, à 19:32)
Hors ligne
Vermouth
Re : TVDownloader: télécharger les médias du net !
Oui j'utilise la classe web.
J'utilise aussi la classe fichier, évidemment.
Pour l'instant, j'utilise aussi des fonctions de conversions d'encodage, ainsi que de nettoyage des entités html.
Je suppose que ça sera fait automatiquement avec ta future version.
Pour le plugin, je continue un peu d'avancer avant de poster.
J'ai fini Arte Live Web et je bosse sur Arte+7.
Si c'est bon, ça donnera une pré-version assez propre (mais à faire évoluer).
Alors pour l'encodage comme je t'ai dit c'est réglé, j'ai fait une fonction sur Plugin.getPage qui renvoie que de l'utf8 (faire les plugins dans cette encodage).
Par contre je ne sais pas ce que tu appel "nettoyage" ^^ .
Hors ligne
BmD_Online
Re : TVDownloader: télécharger les médias du net !
Par contre je ne sais pas ce que tu appel "nettoyage" ^^ .
Remplacement des é & etc... par les caractères respectifs.
J'ai trouvé 2 codes qui font ça. Le plus sympa est celui là
from htmlentitydefs import name2codepoint
def htmlentitydecode(self, s):
# http://wiki.python.org/moin/EscapingHtml
return re.sub('&(%s);' % '|'.join(name2codepoint),
lambda m: unichr(name2codepoint[m.group(1)]), s)
Hors ligne
chaoswizard
Re : TVDownloader: télécharger les médias du net !
Vermouth a écrit :
Par contre je ne sais pas ce que tu appel "nettoyage" ^^ .
Remplacement des é & etc... par les caractères respectifs.
J'ai trouvé 2 codes qui font ça. Le plus
sympaest celui là<metadata lang=Python prob=0.35 />
from htmlentitydefs import name2codepoint
def htmlentitydecode(self, s):
# http://wiki.python.org/moin/EscapingHtml
return re.sub('&(%s);' % '|'.join(name2codepoint),
lambda m: unichr(name2codepoint[m.group(1)]), s)
Est-ce que tu ne peux pas aussi le faire avec :
import urllib
urllib.unquote( chaine )
Dernière modification par chaoswizard (Le 26/07/2010, à 19:59)
Ubuntu ==> Debian ==> Archlinux
Hors ligne
|
I would like to plot in R using an existing pdf file as the background. The reason I don't want to use another format (png, jpg, gif), is that I don't want to lose any quality of the image in my (already existing) pdf file. Any recommendations? Many thanks!
Thanks a lot tim riffe! I found the answer in that document:
First convert the pdf to ps. Then do the rest with the grImport package:
#convert the ps to xml:
PostScriptTrace("image.ps")
# store the xml info in RGML format (R Graphics Markup Language):
NLmap <- readPicture("image.ps.xml")
#plot the image
plot(etc...)
par(new=T)
plot(grid.picture(NLmap[-1]),etc...)
|
I write a function which sets system time in linux. I write next code:
import time
import subprocess
def SetSystemTime(val):
try:
val = float(val)
except ValueError:
return
command = 'date -s"' + time.ctime(val) + '"'
subprocess.call(command)
On calling of that i get:
File "crc.py", line 96, in SetSystemTime(0) File "crc.py", line 12, in SetSystemTime subprocess.call(command) File "/usr/lib/python2.7/subprocess.py", line 493, in call return Popen(*popenargs, **kwargs).wait() File "/usr/lib/python2.7/subprocess.py", line 679, in
initerrread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1239, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory
|
plugin idea: “report this post”
I’m gonna need this one in a hurry so if there’s nothing similar in existance, looks like I have a weekend project.
For now I’m going to keep it simple, add a text link somewhere in the template and that will popup a javascript query for a description why it should be moderated and then an email will be fired off to the admin. What I really want it to do is create a new post in the moderator forum so one of the mods will see it and take action, but that might have to wait until the next version.
Am I the only one (other than the few documented examples) who’s using bbpress for something other than a micro-forum and needs these kinds of tools?
ps. the examples page needs to be updated, over 200,000 registered members now
It might not be what you are working on, but all the major forums that I use have users tag threads as “modlook” to do this very thing and that is what I want users to do on this forum.
Trent
Interesting, but I want something more direct.
Actually, I have a working prototype now and will post a very early beta in an hour or so.
And a report post plugin is born – tested working!
Needs a few features but gets the job done for now:
<?php
/*
Plugin Name: report post
Description: allows members to report a post to admin/moderators
Plugin URI: http://CKon.wordpress.com
Author: _ck_
Author URI: http://CKon.wordpress.com
Version: 0.1
*/
/*
instructions: install, activate and put <? report_post_link(); ?> in your post.php template where you want the link to be seen
optional in stylesheet: a.report_post {color:red;}
todo:
1. don't let them report more than once on a post - or more than too many times per minute/hour
2. auto-delete post if more than x reports from different members
3. auto-post report into a specified moderator's forum #
4. maybe ajax xmlhttp call instead of real form post so there's no page movement
5. it's technically possible to alert a browing mod with a popup directing to the reported post, no email needed
*/
function report_post_link($post_id=0) {
if (bb_current_user_can('participate') ) :
$post_id= get_post_id( $post_id );
if (get_post_author_id($post_id) != bb_get_current_user_info( 'id' )) {
echo '<a class=report_post title="report post to moderator" href="#post-'.$post_id.'" onClick="report_post('.$post_id.');return false;">Report</a>';
}
endif;
}
function report_post_form() {
if (bb_current_user_can('participate')) :
if (isset($_POST['report_post_id']) && isset($_POST['report_post_reason'])) {
echo '<scr'.'ipt type="text/javascript">alert("Thank you for the report. A moderator has been notified.");</scr'.'ipt>';
$post_id=intval($_POST['report_post_id']);
// todo: custom response if invalid id, problem sending email - maybe flush output buffer so member gets alert faster
$to = bb_get_option('admin_email');
$subject = " reported post by member for moderation";
$headers = "From: ".bb_get_option('admin_email');
$message ="report by: ".bb_get_current_user_info( 'name' )." (".bb_get_current_user_info( 'id' ).") email: ".bb_get_current_user_info( 'email' )."rnrn";
$message.="report: ".wordwrap(strip_tags(substr($_POST['report_post_reason'],0,255)),70)."rnrn".get_post_link($post_id)."rn";
$message.="post by: ". get_post_author($post_id)."rn"; // add "member since", total posts, blah blah
$message.="rnrnReport Trace:rn";
$message.="IP: ".$_SERVER['REMOTE_ADDR']."rn";
$message.="Host: ".gethostbyaddr($_SERVER['REMOTE_ADDR'])."rn"; // useful but can add a few seconds
$message.="Agent: ".$_SERVER['HTTP_USER_AGENT']."rn";
$message.="Refer: ". $_REQUEST['refer']."rn";
$message.="URL: http://".$_SERVER['HTTP_HOST'].$GLOBALS["HTTP_SERVER_VARS"]["REQUEST_URI"]."rn";
mail( $to, $subject, $message,$headers);
}
echo '<form method="POST" name="report_post_form" id="report_post_form" style="display:none;visibility:hidden"><input type=hidden name="report_post_id"><input type=hidden name="report_post_reason"></form>';
echo '<scr'.'ipt type="text/javascript">
function report_post(post_id) {
var report_post_reason = prompt("Please enter a short but descriptive reason why a moderator needs to review this post:", "");
if (report_post_reason && report_post_reason.length>9) {
document.report_post_form.report_post_id.value=post_id;
document.report_post_form.action="#post-"+post_id;
document.report_post_form.report_post_reason.value=report_post_reason;
document.report_post_form.submit();
} else {alert("report cancelled, incomplete description"); }
}
</scr'.'ipt>';
endif;
}
add_action('bb_foot', 'report_post_form');
?>
Coming soon:
don't allow reports on moderators
don't allow reports from members less than x days old
security check if user is in the right topic for the post being reported
hum i upload it and active it and insert <? report_post_link(); ?> in post but nothing apeaer .8.2.1
what is the problem?
Sorry I didn’t see your bug report until just now.
I am working on this tonight and will have a working version posted soon (including translation hooks for you).
I’ve tested this now up to the bbpress trunk and it seems to work fine.
Try the latest:
Make sure you are editing post.php in your bb-templates or my-templates?
Unfortunately there is no hook for me to place it automatically in post.php on that info line. Wish there was.
It’s working for me…
I think the problem mazdakam is having is that moderators won’t see the link… you have to login as a regular user.
Which is the correct behavior, of course.
Moderators do see the link, you just don’t see it on your own posts, there’s no point in reporting yourself, LOL!
Ohhhhh
My test site has nothing but posts from me, no wonder I didn’t see it
And to answer your question at the very top of this thread, I’m trying to use bbPress for a serious forum… I just opened my forum a little over a week ago. Not as much traffic as I’d like, of course, but decent.
Yeah you should always create a non-moderator test user to see how other things interact compared to mod/admin. It’s important to see what’s hidden from regular members and sometimes admin can do things we take for granted that regular members cannot (ie. like my admin-can-post-anything plugin)
You must be logged in to reply to this topic.
|
You are here: Home ‣ Dive Into Python 3 ‣
Difficulty level: ♦♦♦♢♢
❝ My spelling is Wobbly. It’s good spelling but it Wobbles, and the letters get in the wrong places. ❞
— Winnie-the-Pooh
Having grown up the son of a librarian and an English major, I have always been fascinated by languages. Not programming languages. Well yes, programming languages, but also natural languages. Take English. English is a schizophrenic language that borrows words from German, French, Spanish, and Latin (to name a few). Actually, “borrows” is the wrong word; “pillages” is more like it. Or perhaps “assimilates” — like the Borg. Yes, I like that.
We are the Borg. Your linguistic and etymological distinctiveness will be added to our own. Resistance is futile.
In this chapter, you’re going to learn about plural nouns. Also, functions that return other functions, advanced regular expressions, and generators. But first, let’s talk about how to make plural nouns. (If you haven’t read the chapter on regular expressions, now would be a good time. This chapter assumes you understand the basics of regular expressions, and it quickly descends into more advanced uses.)
If you grew up in an English-speaking country or learned English in a formal school setting, you’re probably familiar with the basic rules:
(I know, there are a lot of exceptions. Man becomes men and woman becomes women, but human becomes humans. Mouse becomes mice and louse becomes lice, but house becomes houses. Knife becomes knives and wife becomes wives, but lowlife becomes lowlifes. And don’t even get me started on words that are their own plural, like sheep, deer, and haiku.)
Other languages, of course, are completely different.
Let’s design a Python library that automatically pluralizes English nouns. We’ll start with just these four rules, but keep in mind that you’ll inevitably need to add more.
⁂
So you’re looking at words, which, at least in English, means you’re looking at strings of characters. You have rules that say you need to find different combinations of characters, then do different things to them. This sounds like a job for regular expressions!
[download plural1.py]
import re
def plural(noun):
if re.search('[sxz]$', noun): ①
return re.sub('$', 'es', noun) ②
elif re.search('[^aeioudgkprt]h$', noun):
return re.sub('$', 'es', noun)
elif re.search('[^aeiou]y$', noun):
return re.sub('y$', 'ies', noun)
else:
return noun + 's'
[sxz] means “s, or x, or z”, but only one of them. The $ should be familiar; it matches the end of string. Combined, this regular expression tests whether s, x, or z.re.sub() function performs regular expression-based string substitutions.
Let’s look at regular expression substitutions in more detail.
>>>import re>>>re.search('[abc]', 'Mark')① <_sre.SRE_Match object at 0x001C1FA8>>>>re.sub('[abc]', 'o', 'Mark')②'Mork'>>>re.sub('[abc]', 'o', 'rock')③'rook'>>>re.sub('[abc]', 'o', 'caps')④'oops'
Mark contain a, b, or c? Yes, it contains a.a, b, or c, and replace it with o. Mark becomes Mork.rock into rook.caps into oaps, but it doesn’t. re.sub replaces caps into oops, because both the c and the a get turned into o.
And now, back to the plural() function…
def plural(noun):
if re.search('[sxz]$', noun):
return re.sub('$', 'es', noun) ①
elif re.search('[^aeioudgkprt]h$', noun): ②
return re.sub('$', 'es', noun)
elif re.search('[^aeiou]y$', noun): ③
return re.sub('y$', 'ies', noun)
else:
return noun + 's'
$) with the string es. In other words, adding es to the string. You could accomplish the same thing with string concatenation, for example noun + 'es', but I chose to use regular expressions for each rule, for reasons that will become clear later in the chapter.^ as the first character inside the square brackets means something special: negation. [^abc] means “any single character a, b, or c”. So [^aeioudgkprt] means any character except a, e, i, o, u, d, g, k, p, r, or t. Then that character needs to be followed by h, followed by end of string. You’re looking for words that end in H where the H can be heard.a, e, i, o, or u. You’re looking for words that end in Y that sounds like I.
Let’s look at negation regular expressions in more detail.
>>>import re>>>re.search('[^aeiou]y$', 'vacancy')① <_sre.SRE_Match object at 0x001C1FA8>>>>re.search('[^aeiou]y$', 'boy')②>>>>>>re.search('[^aeiou]y$', 'day')>>>>>>re.search('[^aeiou]y$', 'pita')③>>>
vacancy matches this regular expression, because it ends in cy, and c is not a, e, i, o, or u.boy does not match, because it ends in oy, and you specifically said that the character before the y could not be o. day does not match, because it ends in ay.pita does not match, because it does not end in y.
>>>re.sub('y$', 'ies', 'vacancy')①'vacancies'>>>re.sub('y$', 'ies', 'agency')'agencies'>>>re.sub('([^aeiou])y$', r'\1ies', 'vacancy')②'vacancies'
vacancy into vacancies and agency into agencies, which is what you wanted. Note that it would also turn boy into boies, but that will never happen in the function because you did that re.search first to find out whether you should do this re.sub.y. Then in the substitution string, you use a new syntax, \1, which means “hey, that first group you remembered? put it right here.” In this case, you remember the c before the y; when you do the substitution, you substitute c in place of c, and ies in place of y. (If you have more than one remembered group, you can use \2 and \3 and so on.)
Regular expression substitutions are extremely powerful, and the \1 syntax makes them even more powerful. But combining the entire operation into one regular expression is also much harder to read, and it doesn’t directly map to the way you first described the pluralizing rules. You originally laid out rules like “if the word ends in S, X, or Z, then add ES”. If you look at this function, you have two lines of code that say “if the word ends in S, X, or Z, then add ES”. It doesn’t get much more direct than that.
⁂
Now you’re going to add a level of abstraction. You started by defining a list of rules: if this, do that, otherwise go to the next rule. Let’s temporarily complicate part of the program so you can simplify another part.
[download plural2.py]
import re
def match_sxz(noun):
return re.search('[sxz]$', noun)
def apply_sxz(noun):
return re.sub('$', 'es', noun)
def match_h(noun):
return re.search('[^aeioudgkprt]h$', noun)
def apply_h(noun):
return re.sub('$', 'es', noun)
def match_y(noun): ①
return re.search('[^aeiou]y$', noun)
def apply_y(noun): ②
return re.sub('y$', 'ies', noun)
def match_default(noun):
return True
def apply_default(noun):
return noun + 's'
rules = ((match_sxz, apply_sxz), ③
(match_h, apply_h),
(match_y, apply_y),
(match_default, apply_default)
)
def plural(noun):
for matches_rule, apply_rule in rules: ④
if matches_rule(noun):
return apply_rule(noun)
re.search() function.re.sub() function to apply the appropriate pluralization rule.plural()) with multiple rules, you have the rules data structure, which is a sequence of pairs of functions.plural() function can be reduced to a few lines of code. Using a for loop, you can pull out the match and apply rules two at a time (one match, one apply) from the for loop, match_sxz, and apply_sxz. On the second iteration (assuming you get that far), match_h, and apply_h. The function is guaranteed to return something eventually, because the final match rule (match_default) simply returns True, meaning the corresponding apply rule (apply_default) will always be applied.
The reason this technique works is that everything in Python is an object, including functions. The rules data structure contains functions — not names of functions, but actual function objects. When they get assigned in the for loop, then matches_rule and apply_rule are actual functions that you can call. On the first iteration of the for loop, this is equivalent to calling matches_sxz(noun), and if it returns a match, calling apply_sxz(noun).
If this additional level of abstraction is confusing, try unrolling the function to see the equivalence. The entire for loop is equivalent to the following:
def plural(noun):
if match_sxz(noun):
return apply_sxz(noun)
if match_h(noun):
return apply_h(noun)
if match_y(noun):
return apply_y(noun)
if match_default(noun):
return apply_default(noun)
The benefit here is that the plural() function is now simplified. It takes a sequence of rules, defined elsewhere, and iterates through them in a generic fashion.
The rules could be defined anywhere, in any way. The plural() function doesn’t care.
Now, was adding this level of abstraction worth it? Well, not yet. Let’s consider what it would take to add a new rule to the function. In the first example, it would require adding an if statement to the plural() function. In this second example, it would require adding two functions, match_foo() and apply_foo(), and then updating the rules sequence to specify where in the order the new match and apply functions should be called relative to the other rules.
But this is really just a stepping stone to the next section. Let’s move on…
⁂
Defining separate named functions for each match and apply rule isn’t really necessary. You never call them directly; you add them to the rules sequence and call them through there. Furthermore, each function follows one of two patterns. All the match functions call re.search(), and all the apply functions call re.sub(). Let’s factor out the patterns so that defining new rules can be easier.
[download plural3.py]
import re
def build_match_and_apply_functions(pattern, search, replace):
def matches_rule(word): ①
return re.search(pattern, word)
def apply_rule(word): ②
return re.sub(search, replace, word)
return (matches_rule, apply_rule) ③
build_match_and_apply_functions() is a function that builds other functions dynamically. It takes matches_rule() function which calls re.search() with the build_match_and_apply_functions() function, and the matches_rule() function you’re building. Whoa.re.sub() with the build_match_and_apply_functions() function, and the apply_rule() function you’re building. This technique of using the values of outside parameters within a dynamic function is called build_match_and_apply_functions() function returns a tuple of two values: the two functions you just created. The constants you defined within those functions (matches_rule() function, and apply_rule() function) stay with those functions, even after you return from build_match_and_apply_functions(). That’s insanely cool.
If this is incredibly confusing (and it should be, this is weird stuff), it may become clearer when you see how to use it.
patterns = \ ①
(
('[sxz]$', '$', 'es'),
('[^aeioudgkprt]h$', '$', 'es'),
('(qu|[^aeiou])y$', 'y$', 'ies'),
('$', '$', 's') ②
)
rules = [build_match_and_apply_functions(pattern, search, replace) ③
for (pattern, search, replace) in patterns]
re.search() to see if this rule matches. The second and third strings in each group are the search and replace expressions you would use in re.sub() to actually apply the rule to turn a noun into its plural.match_default() function simply returned True, meaning that if none of the more specific rules matched, the code would simply add an s to the end of the given word. This example does something functionally equivalent. The final regular expression asks whether the word has an end ($ matches the end of a string). Of course, every string has an end, even an empty string, so this expression always matches. Thus, it serves the same purpose as the match_default() function that always returned True: it ensures that if no more specific rule matches, the code adds an s to the end of the given word.build_match_and_apply_functions() function. That is, it takes each triplet of strings and calls the build_match_and_apply_functions() function with those three strings as arguments. The build_match_and_apply_functions() function returns a tuple of two functions. This means that re.search(), and the second function is the apply function that calls re.sub().
Rounding out this version of the script is the main entry point, the plural() function.
def plural(noun):
for matches_rule, apply_rule in rules: ①
if matches_rule(noun):
return apply_rule(noun)
plural() function hasn’t changed at all. It’s completely generic; it takes a list of rule functions and calls them in order. It doesn’t care how the rules are defined. In the previous example, they were defined as separate named functions. Now they are built dynamically by mapping the output of the build_match_and_apply_functions() function onto a list of raw strings. It doesn’t matter; the plural() function still works the same way.
⁂
You’ve factored out all the duplicate code and added enough abstractions so that the pluralization rules are defined in a list of strings. The next logical step is to take these strings and put them in a separate file, where they can be maintained separately from the code that uses them.
First, let’s create a text file that contains the rules you want. No fancy data structures, just whitespace-delimited strings in three columns. Let’s call it plural4-rules.txt.
[download plural4-rules.txt]
[sxz]$ $ es[^aeioudgkprt]h$ $ es[^aeiou]y$ y$ ies$ $ s
Now let’s see how you can use this rules file.
[download plural4.py]
import re
def build_match_and_apply_functions(pattern, search, replace): ①
def matches_rule(word):
return re.search(pattern, word)
def apply_rule(word):
return re.sub(search, replace, word)
return (matches_rule, apply_rule)
rules = []
with open('plural4-rules.txt', encoding='utf-8') as pattern_file: ②
for line in pattern_file: ③
pattern, search, replace = line.split(None, 3) ④
rules.append(build_match_and_apply_functions( ⑤
pattern, search, replace))
build_match_and_apply_functions() function has not changed. You’re still using closures to build two functions dynamically that use variables defined in the outer function.open() function opens a file and returns a file object. In this case, the file we’re opening contains the pattern strings for pluralizing nouns. The with statement creates what’s called a with block ends, Python will automatically close the file, even if an exception is raised inside the with block. You’ll learn more about with blocks and file objects in the Files chapter.for line in <fileobject> idiom reads data from the open file, one line at a time, and assigns the text to the split() string method. The first argument to the split() method is None, which means “split on any whitespace (tabs or spaces, it makes no difference).” The second argument is 3, which means “split on whitespace 3 times, then leave the rest of the line alone.” A line like [sxz]$ $ es will be broken up into the list ['[sxz]$', '$', 'es'], which means that '[sxz]$', '$', and 'es'. That’s a lot of power in one little line of code.pattern, search, and replace to the build_match_and_apply_functions() function, which returns a tuple of functions. You append this tuple to the plural() function expects.
The improvement here is that you’ve completely separated the pluralization rules into an external file, so it can be maintained separately from the code that uses it. Code is code, data is data, and life is good.
⁂
Wouldn’t it be grand to have a generic plural() function that parses the rules file? Get rules, check for a match, apply appropriate transformation, go to next rule. That’s all the plural() function has to do, and that’s all the plural() function should do.
[download plural5.py]
def rules(rules_filename):
with open(rules_filename, encoding='utf-8') as pattern_file:
for line in pattern_file:
pattern, search, replace = line.split(None, 3)
yield build_match_and_apply_functions(pattern, search, replace)
def plural(noun, rules_filename='plural5-rules.txt'):
for matches_rule, apply_rule in rules(rules_filename):
if matches_rule(noun):
return apply_rule(noun)
raise ValueError('no matching rule for {0}'.format(noun))
How the heck does that work? Let’s look at an interactive example first.
>>>def make_counter(x):...print('entering make_counter')...while True:...yield x①...print('incrementing x')...x = x + 1...>>>counter = make_counter(2)②>>>counter③ <generator object at 0x001C9C10>>>>next(counter)④entering make_counter 2>>>next(counter)⑤incrementing x 3>>>next(counter)⑥incrementing x 4
yield keyword in make_counter means that this is not a normal function. It is a special kind of function which generates values one at a time. You can think of it as a resumable function. Calling it will return a make_counter generator, just call it like any other function. Note that this does not actually execute the function code. You can tell this because the first line of the make_counter() function calls print(), but nothing has been printed yet.make_counter() function returns a generator object.next() function takes a generator object and returns its next value. The first time you call next() with the make_counter() up to the first yield statement, then returns the value that was yielded. In this case, that will be 2, because you originally created the generator by calling make_counter(2).next() with the same generator object resumes exactly where it left off and continues until it hits the next yield statement. All variables, local state, yield and restored on next(). The next line of code waiting to be executed calls print(), which prints x = x + 1. Then it loops through the while loop again, and the first thing it hits is the statement yield x, which saves the state of everything and returns the current value of 3).next(counter), you do all the same things again, but this time 4.
Since make_counter sets up an infinite loop, you could theoretically do this forever, and it would just keep incrementing x and spitting out values. But let’s look at more productive uses of generators instead.
[download fibonacci.py]
def fib(max):
a, b = 0, 1 ①
while a < max:
yield a ②
a, b = b, a + b ③
1, goes up slowly at first, then more and more rapidly. To start the sequence, you need two variables: 1.a + b) and assign that to 3 and 5, then a, b = b, a + b will set 5 (the previous value of 8 (the sum of the previous values of
So you have a function that spits out successive Fibonacci numbers. Sure, you could do that with recursion, but this way is easier to read. Also, it works well with for loops.
>>>from fibonacci import fib>>>for n in fib(1000):①...print(n, end=' ')②0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987>>>list(fib(1000))③[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]
fib() in a for loop directly. The for loop will automatically call the next() function to get values from the fib() generator and assign them to the for loop index variable (for loop, yield statement in fib(), and all you have to do is print it out. Once fib() runs out of numbers (1000), then the for loop exits gracefully.list() function, and it will iterate through the entire generator (just like the for loop in the previous example) and return a list of all the values.
Let’s go back to plural5.py and see how this version of the plural() function works.
def rules(rules_filename):
with open(rules_filename, encoding='utf-8') as pattern_file:
for line in pattern_file:
pattern, search, replace = line.split(None, 3) ①
yield build_match_and_apply_functions(pattern, search, replace) ②
def plural(noun, rules_filename='plural5-rules.txt'):
for matches_rule, apply_rule in rules(rules_filename): ③
if matches_rule(noun):
return apply_rule(noun)
raise ValueError('no matching rule for {0}'.format(noun))
line.split(None, 3) to get the three “columns” and assign them to three local variables.build_match_and_apply_functions(), which is identical to the previous examples. In other words, rules() is a generator that spits out match and apply functions rules() is a generator, you can use it directly in a for loop. The first time through the for loop, you will call the rules() function, which will open the pattern file, read the first line, dynamically build a match function and an apply function from the patterns on that line, and yield the dynamically built functions. The second time through the for loop, you will pick up exactly where you left off in rules() (which was in the middle of the for line in pattern_file loop). The first thing it will do is read the next line of the file (which is still open), dynamically build another match and apply function based on the patterns on that line in the file, and yield the two functions.
What have you gained over stage 4? Startup time. In stage 4, when you imported the plural4 module, it read the entire patterns file and built a list of all the possible rules, before you could even think about calling the plural() function. With generators, you can do everything lazily: you read the first rule and create functions and try them, and if that works you don’t ever read the rest of the file or create any other functions.
What have you lost? Performance! Every time you call the plural() function, the rules() generator starts over from the beginning — which means re-opening the patterns file and reading from the beginning, one line at a time.
What if you could have the best of both worlds: minimal startup cost (don’t execute any code on import), and maximum performance (don’t build the same functions over and over again). Oh, and you still want to keep the rules in a separate file (because code is code and data is data), just as long as you never have to read the same line twice.
To do that, you’ll need to build your own iterator. But before you do that, you need to learn about Python classes.
⁂
☜ ☞
© 2001–11 Mark Pilgrim
|
This problem looked familiar so I thought I'd see if I could replicate from the limited amount of information.
A quick search turned up an entry in James Bennett's blog here which mentions that when working with the UserProfile to extend the User model a common mistake in settings.py can cause Django to throw this error.
To quote the blog entry:
The value of the setting is not "appname.models.modelname", it's just "appname.modelname". The reason is that Django is not using this to do a direct import; instead, it's using an internal model-loading function which only wants the name of the app and the name of the model. Trying to do things like "appname.models.modelname" or "projectname.appname.models.modelname" in the AUTH_PROFILE_MODULE setting will cause Django to blow up with the dreaded "too many values to unpack" error, so make sure you've put "appname.modelname", and nothing else, in the value of AUTH_PROFILE_MODULE.
If the OP had copied more of the traceback I would expect to see something like the one below which I was able to duplicate by adding "models" to my AUTH_PROFILE_MODULE setting.
TemplateSyntaxError at /
Caught an exception while rendering: too many values to unpack
Original Traceback (most recent call last):
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 71, in render_node
result = node.render(context)
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 87, in render
output = force_unicode(self.filter_expression.resolve(context))
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 535, in resolve
obj = self.var.resolve(context)
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 676, in resolve
value = self._resolve_lookup(context)
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 711, in _resolve_lookup
current = current()
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/contrib/auth/models.py", line 291, in get_profile
app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
ValueError: too many values to unpack
This I think is one of the few cases where Django still has a bit of import magic that tends to cause confusion when a small error doesn't throw the expected exception.
You can see at the end of the traceback that I posted how using anything other than the form "appname.modelname" for the AUTH_PROFILE_MODULE would cause the line "app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')" to throw the "too many values to unpack" error.
I'm 99% sure that this was the original problem encountered here.
|
When I try to import the scipy module (version 0.11.0b1) in the Python interpreter (version 2.6.1), I receive the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in module
File "/Users/...long path.../Desktop/scipy-0.11.0b1/scipy/\__init__.py", line 114, in module
ImportError: Error importing scipy: you cannot import scipy while
being in scipy source directory; please exit the scipy source
tree first, and relaunch your python intepreter.
The problem is that python is reading from a file that doesn't exist. I deleted the scipy directory from my Desktop a while ago and have since tried restarting the interpreter (and the computer) several times. Why does the traceback continue to refer to a file that doesn't exist?
|
Information on groups, servers and shards are stored in a MySQL Instance called state store or backing store. This instance is a repository for all this information and the engine used might be any supported by MySQL, although a transactional engine must be picked to truly provide fault-tolerance. Note though that we have been testing MySQL Fabric with Innodb and currently this the only official engine supported.
Built upon the repository there are several functions that, besides being used to retrieve information from and update the repository, are responsible for the execution of some administrative tasks. For example, adding a server into a group has two steps: creating an entry into the state store and making the server point to the current primary, if there is any.
Promoting a new primary requires to:
choose among a set of candidates which one will become the new primary when a candidate is not promptly specified;
stop accepting writes on the current primary;
synchronize the primary with the secondaries and reconfigure replication;
update the repository with the new information.
However, there might be users who want to use their own scripts to execute these administrative tasks and want to update MySQL Fabric to reflect the changes made to the servers. For these users, we have introduce the --update_only option into some commands so that they might continue using their own scripts and take advantage of MySQL Fabric at the same time as well.
Executing commands
MySQL Fabric's command might be invoked as a command-line script as follow:
mysqlfabric group add my_group localhost:13001 --update_only
Or using a MySQL Fabric-aware connector (e.g. Connector Python) through a direct call to a XML-RPC function as follows:
ERROR, SUCCESS = range(1, 3)
conn = mysql.connector.connect(
fabric={"host" : "localhost",
"username": "admin", "password" : "adminpass"
},
user="webuser", password="webpass"
)
proxy = conn._fabric.get_instance().proxy
status = proxy.group.add("my_group", "localhost:13001", 5, True)
if status[1][-1]["success"] == ERROR:
raise Error("Something bad happened %s." % (str(status), ))
Note that the
"mysqlfabric"script uses XML-RPC to call the appropriate functions and both examples try to add
"localhost:13001"server into the
"my_group"group. In the latter case, besides setting the group's name, server's address and the update only arguments, we also need to set the timeout argument as the XML-RPC does not support named/keyword arguments. For a complete list of commands available check the documentation or execute the following command:
mysqlfabric help commands
Currently the command-line solution has two issues:
Adding a server into a group
Users must set up replication on a new MySQL Server and inform MySQL Fabric about its existence as follows:
mysqlfabric group add group-name server-id --update_only
To avoid cluttering the post with unnecessary details, we are going to write examples using the command-line script. Note though that there are issues with this solution as aforementioned. The group-name and server-id must be replaced by the group which the server belongs to and its real UUID or address, respectively. The remove command does have the option --update_only as it only removes a reference to the server from the repository and does not try to access the server or reconfigure replication.
Promoting a new primary
If users want to promote a new primary, they must first demote the current one as follows:
mysqlfabric group demote group-name --update_only
After that, they should forbid any attempt to write to the old primary, make sure that the primary and secondaries are synchronized, elect a new primary and then reconfigure replication accordingly. How these is done depends on the particularities of their environments and scripts. Finally to inform the connectors that there is a new primary, they should execute the following:
mysqlfabric group promote group-name --slave_id=server-id --update_only
|
Is there a list somewhere of recommendations of different Python-based REST frameworks for use on the serverside to write your own RESTful APIs? Preferably with pros and cons.
Please feel free to add recommendations here. :)
Something to be careful about when designing a RESTful API is the conflation of GET and POST, as if they were the same thing. It's easy to make this mistake with Django's function-based views and CherryPy's default dispatcher, although both frameworks now provide a way around this problem (class-based views and MethodDispatcher, respectively).
import web
import json
from mimerender import mimerender
render_xml = lambda message: '<message>%s</message>'%message
render_json = lambda **args: json.dumps(args)
render_html = lambda message: '<html><body>%s</body></html>'%message
render_txt = lambda message: message
urls = (
'/(.*)', 'greet'
)
app = web.application(urls, globals())
class greet:
@mimerender(
default = 'html',
html = render_html,
xml = render_xml,
json = render_json,
txt = render_txt
)
def GET(self, name):
if not name:
name = 'world'
return {'message': 'Hello, ' + name + '!'}
if __name__ == "__main__":
app.run()
The service's logic is implemented only once, and the correct representation selection (Accept header) + dispatch to the proper render function (or template) is done in a tidy, transparent way.
$ curl localhost:8080/x
<html><body>Hello, x!</body></html>
$ curl -H "Accept: application/html" localhost:8080/x
<html><body>Hello, x!</body></html>
$ curl -H "Accept: application/xml" localhost:8080/x
<message>Hello, x!</message>
$ curl -H "Accept: application/json" localhost:8080/x
{'message':'Hello, x!'}
$ curl -H "Accept: text/plain" localhost:8080/x
Hello, x!
Surprised no one mentioned flask.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
We're using Django for RESTful web services.
Note that -- out of the box -- Django did not have fine-grained enough authentication for our needs. We used the Django-REST interface, which helped a lot. [We've since rolled our own because we'd made so many extensions that it had become a maintenance nightmare.]
We have two kinds of URL's: "html" URL's which implement the human-oriented HTML pages, and "json" URL's which implement the web-services oriented processing. Our view functions often look like this.
def someUsefulThing( request, object_id ):
# do some processing
return { a dictionary with results }
def htmlView( request, object_id ):
d = someUsefulThing( request, object_id )
render_to_response( 'template.html', d, ... )
def jsonView( request, object_id ):
d = someUsefulThing( request, object_id )
data = serializers.serialize( 'json', d['object'], fields=EXPOSED_FIELDS )
response = HttpResponse( data, status=200, content_type='application/json' )
response['Location']= reverse( 'some.path.to.this.view', kwargs={...} )
return response
The point being that the useful functionality is factored out of the two presentations. The JSON presentation is usually just one object that was requested. The HTML presentation often includes all kinds of navigation aids and other contextual clues that help people be productive.
The
See Python Web Frameworks wiki.
You probably do not need the
I really like CherryPy. Here's an example of a restful web service:
import cherrypy
from cherrypy import expose
class Converter:
@expose
def index(self):
return "Hello World!"
@expose
def fahr_to_celc(self, degrees):
temp = (float(degrees) - 32) * 5 / 9
return "%.01f" % temp
@expose
def celc_to_fahr(self, degrees):
temp = float(degrees) * 9 / 5 + 32
return "%.01f" % temp
cherrypy.quickstart(Converter())
This emphasizes what I really like about CherryPy; this is a completely working example that's very understandable even to someone who doesn't know the framework. If you run this code, then you can immediately see the results in your web browser; e.g. visiting http://localhost:8080/celc_to_fahr?degrees=50 will display
I don't see any reason to use Django just to expose a REST api, there are lighter and more flexible solutions. Django carries a lot of other things to the table, that are not always needed. For sure not needed if you only want to expose some code as a REST service.
My personal experience, fwiw, is that once you have a one-size-fits-all framework, you'll start to use its ORM, its plugins, etc. just because it's easy, and in no time you end up having a dependency that is very hard to get rid of.
Choosing a web framework is a tough decision, and I would avoid picking a full stack solution just to expose a REST api.
Now, if you really need/want to use Django, then Piston is a nice REST framework for django apps.
That being said, CherryPy looks really nice too, but seems more RPC than REST.
Looking at the samples (I never used it), probably web.py is the best and cleanest if you only need REST.
Here is a discussion in CherryPy docs on REST: http://docs.cherrypy.org/dev/progguide/REST.html
In particular it mentions a built in CherryPy dispatcher called MethodDispatcher, which invokes methods based on their HTTP-verb identifiers (GET, POST, etc...).
In 2010, the Pylons and repoze.bfg communities "joined forces" to create Pyramid, a web framework based most heavily on repoze.bfg. It retains the philosophies of its parent frameworks, and can be used for RESTful services. It's worth a look.
Piston is very flexible framework for wirting RESTful APIs for Django applications.
Seems all kinds of python web frameworks can implement RESTful interfaces now.
For Django, besides tastypie and piston, django-rest-framework is a promising one worth to mention. I've already migrated one of my project on it smoothly.
Quick example:
from django.conf.urls.defaults import patterns, url
from djangorestframework.resources import ModelResource
from djangorestframework.views import ListOrCreateModelView, InstanceModelView
from myapp.models import MyModel
class MyResource(ModelResource):
model = MyModel
urlpatterns = patterns('',
url(r'^$', ListOrCreateModelView.as_view(resource=MyResource)),
url(r'^(?P<pk>[^/]+)/$', InstanceModelView.as_view(resource=MyResource)),
)
Take the example from official site, all above codes provide api, self explained document(like soap based webservice) and even sandbox to test a bit. Very convenience.
I am not an expert on the python world but I have been using django which is an excellent web framework and can be used to create a restful framework.
web2py includes support for easily building RESTful API's, described here and here (video). In particular, look at
I strongly recommend TurboGears or Bottle:
TurboGears:
Bottle:
We are working on a framework for strict REST services, check out http://prestans.googlecode.com
Its in early Alpha at the moment, we are testing against mod_wsgi and Google's AppEngine.
Looking for testers and feedback. Thanks.
|
Jx7
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
J'ai l'impression que tu as un problème de droits d'écritures.
Hors ligne
Jx7
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
Où as-tu placer le script?
Hors ligne
Jx7
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
Et les droits du répertoire et du script?
Mets toi dans ton home et exécute les commande suivantes pour être sûr:
chmod +w ./cplus
chmod +x ./cplus/cplus.py
Hors ligne
Jx7
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
Changelog:
# v0.5
# 19/11/2012 : Optimisations
# 2 modes: verbose et test
#
# Syntaxe: cplus.py [--verbose] [--test]
#
# verbose: affiche les infos à l'écran en + des logs
# test: ne lance pas les téléchargements et ne met donc pas à jour le fichier d'historique
#
# Les émissions non commentées sont celles que j'ai testée et qui dont les téléchargements fonctionnent
# Les autres sont à tester (emplacement de la date inclu)
Dernière modification par Jx7 (Le 20/11/2012, à 00:07)
Hors ligne
Xun
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
Je viens d'essayer sur mon pc portable avec ubuntu, tout marche normalement, c'est super !
Pour le moment ça télécharge
EDIT: Quand je veux télécharger le Grand journal, ça télécharge une première fois en créant un fichier. Sauf qu'après, en voulant télécharger un autre fichier de la même émission, il en télécharge une en reprenant le même nom que le fichier précédant. Du coup je perds le premier. Tu vois le souci ?
Dernière modification par Xun (Le 20/11/2012, à 08:25)
Hors ligne
Jx7
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
En effet certaines émissions semblent être découpées en plusieurs parties.
J'ai fait une v0.7 qui devrait gérer ça.
v0.7
20/11/2012:
Ajout d'un paramètre dans la syntaxe pour choisir la qualité par des vidéos sans avoir à éditer le script.
Ajout d'explications en début de script sur son utilisation.
Ajout de la gestion des émissions en plusieurs parties (attention, il est nécessaire de télécharger toutes les parties en une seule commande, le script ne gèrera pas les différentes parties si certaines ont déjà été téléchargées).
Toujours à la même adresse: http://pastebin.com/U0WuqhrK
Hors ligne
L3R4F
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
L3R4F a écrit :
Qqun aurait le numéro xml pour télécharger le supplément de Maïténa?
http://service.canal-plus.com/video/res … cplus/1063
pour les émissions complètes.
http://service.canal-plus.com/video/res … cplus/1059
pour les segments.
Super, merci!
Je m'étais arrêté aux 500 premiers xml
Hors ligne
Jx7
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
S00000 a écrit :L3R4F a écrit :
Qqun aurait le numéro xml pour télécharger le supplément de Maïténa?
http://service.canal-plus.com/video/res … cplus/1063
pour les émissions complètes.
http://service.canal-plus.com/video/res … cplus/1059
pour les segments.
Super, merci!
Je m'étais arrêté aux 500 premiers xml
J'ai mis à dispo un fichier Excel avec toutes les émissions un peu plus haut...
Hors ligne
aspu
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
Sans rentrer dans les cripts et autres lignes j'ai installer flvstreamer et Rtmpdump .
Puis installer : http://olaf.10.free.fr/urecorder/urecor … -1_all.deb
Ça marche du tonnerre !
Hors ligne
Jx7
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
Sans rentrer dans les cripts et autres lignes j'ai installer flvstreamer et Rtmpdump .
Puis installer : http://olaf.10.free.fr/urecorder/urecor … -1_all.deb
Ça marche du tonnerre !
À priori Urecorder est INCOMPATIBLE avec Ubuntu 12.04 faut voir avec les autres...
Est-ce qu'on peut démarrer un téléchargement avec une seule ligne de commande? Le but étant d'automatiser
Dernière modification par Jx7 (Le 26/11/2012, à 01:36)
Hors ligne
Xun
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
Salut !
Je fais une petite remontée de la mise à jour de ton script J'ai mis du temps à refaire des essais, période occupée
Apparemment les émissions en plusieurs parties sont bien gérées (je parle pour le grand journal ) mais du coup je me disais, ça serait sympa de générer une playlist (un fichier texte en extension m3u ou autre) par date d'émission. Pourquoi pas ?
Encore merci pour la maintenance de ce script.
Hors ligne
jlemaire
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
Excusez mon ignorance, mais je ne comprends pas comment utiliser ce script. Est-ce du python ?
Y a-t-il quelqu'un qui peut aiguiller les nouveaux venus pour le faire fonctionner ?
Merci de votre aide !
Hors ligne
Xun
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
Salut,
C'est effectivement du python. Il faut cependant le modifier avant de pouvoir l'executer; à savoir les lignes suivantes :
# Répertoires (à créer avant)
HomeDir = os.path.expanduser('/home/hope/Downloads/Canal+Replay/canal')
DownloadsDir = HomeDir + "/downloads"
Et il faut créer les fichiers LogFile, HistoryFile, et UnwantedFile
#Fichiers
LogFile = HomeDir + "/cplus_log"
HistoryFile = HomeDir + "/cplus_history"
UnwantedFile = HomeDir + "/cplus_unwanted"
Ayant un Raspberry Pi, je voulais automatiser quotidiennement l’exécution de ce script.
Seulement, j'obtiens ces erreurs:
[hope@Hope Canal+Replay]$ python2 canal.py
Traceback (most recent call last):
File "canal.py", line 404, in <module>
r = Execute(params, target_)
File "canal.py", line 171, in Execute
p = subprocess.Popen(_Params,stdout=_File)
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
malgré de nombreux 'chmod 777' ou encore chown ....
Je suis dans le dossier /home/hope/Downloads/Canal+Replay possédant le dossier canal et le 'canal.py'....
Hors ligne
Jx7
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
Bizarre ça... tu n'avais pas dis que ça fonctionnait sur un autre Linux? Ne serait-ce pas le nom du répertoire qui possède un '+' ?
Je vais voir pour les .m3u ;-)
Concernant les paramètres du script dont tu parles, je devrais aussi les externaliser dans un fichier de config, ce serait plus propre.
Hors ligne
Hors ligne
jlemaire
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
Merci, j'ai réussi à faire fonctionner le script.
Par contre, il semble ne pas fonctionner pour Le Meilleur Du Hier.
Une idée ?
Dernière modification par jlemaire (Le 16/12/2012, à 16:47)
Hors ligne
Jx7
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
Merci, j'ai réussi à faire fonctionner le script.
Par contre, il semble ne pas fonctionner pourLe Meilleur Du Hier.
Une idée ?
As-tu précisé les infos de cette émissions?
Dans le script il y a la liste des émissions de Canal + (ou du moins une partie) et en entête il est précisé qu'il faut renseigner:
L'ID de l'émission,
L'emplacement de la date,
Le nom de l'émission,
Le nom supposé du fichier
Je n'ai pas renseigné tous les champs pour toutes les émissions de Canal +, j'ai mis simplement les noms d'émission et les "supposés" ID de celles-ci.
Chacun doit renseigner les champs en fonction des émissions qui l'intéressent en attendant une évolution du script.
Dans ton cas, les infos devraient être les suivantes:
L'ID de l'émission: 215
Ensuite, comme les fichiers de cette émission ressemblent à ça sur le site:
LE_MEILLEUR_DU_HIER_EMISSION_121123_CAN_297682_video_HD.mp4
on devrait avoir:
L'emplacement de la date: 5 (0: LE, 1: MEILLEUR, 2: DU, 3: HIER, 4: EMISSION et 5: 121123 donc la date)
Le nom de l'émission: "Le meilleur du hier"
Le nom supposé du fichier: "LE_MEILLEUR_DU_HIER"
Donc tu dois remplacer la ligne:
#ShowList.append([215,4,"Le meilleur du hier"]) # 63 107 110 112 ?
par:
ShowList.append([215,5,"Le meilleur du hier","LE_MEILLEUR_DU_HIER"]) # 63 107 110 112 ?
Hors ligne
aspu
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
Retour après quelques jours d'utilisation !
Comme c'était juste " la revue de presse" des deux allumées du petit journal de canal+ que je voulais télécharger j'ai mis du temps à regarder plus dans les menus .
Pour les autres chaines ça ne fonctionne pas , je me retrouve avec un fichier téléchargé instantanément mais vide .
Hors ligne
aspu
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
aspu a écrit :
Sans rentrer dans les cripts et autres lignes j'ai installer flvstreamer et Rtmpdump .
Puis installer : http://olaf.10.free.fr/urecorder/urecor … -1_all.deb
Ça marche du tonnerre !
À priori Urecorder est INCOMPATIBLE avec Ubuntu 12.04 faut voir avec les autres...
Est-ce qu'on peut démarrer un téléchargement avec une seule ligne de commande? Le but étant d'automatiser
Suis sous 11.04 ...
Hors ligne
urustu
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
La version graphique avec CANAL+, ARTE, M6 et W9 :
http://olaf.10.free.fr/urecorder/urecor … -1_all.deb (version 0.9-1 par olaf.10 - 22/08/2010)
Bonjour,
J'ai tenté l'installation mais voici le message d'erreur :
dpkg: error processing /tmp/urecorder_0.9-1_all.deb (--install):
parsing file '/var/lib/dpkg/tmp.ci/control' near line 11 package 'urecorder':
blank line in value of field 'Description'
Ce programme peut/pourra-t-il aussi récupérer les programmes de D8/D17 ?
HP Pavilion 17-e027sf | CPU AMD A4-5000 alias Kabini | Graphique Radeon HD 8330 | Wifi Realtek RTL8188EE > Ubuntu Precise 12.04.4 LTS | Trusty 14.04 LTS | Fedora 20 | Mint 17Samsung 300E7A nVidia Optimus > Ubuntu Precise 12.04 LTS
Hors ligne
arthurd
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
Xun : Il te manque le paquet flvstreamer je pense, c'est ce qui me donnait cette erreur sur mon arch.
(pour trouver : python2 -m pdb cplus.py pour débugger, cont au début pour lancer le script, puis quand il bug tu passes en mode post mortem et tu peux remonter dans la pile d'appel avec "up" jusqu'à arriver à l'endroit du script qui a bugger et afficher avec "p _Params" la variable _Params qui commence par "flvstreamer…" et te donne le problème)
Hors ligne
Xun
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
C'est fort possible que ça soit ça ... Mais flvstreamer n'est pas disponible pour architecture ARM de ce que j'ai vu... Je voulais faire télécharger les vidéos par mon raspberry pi ...
hope@Hope canalReplay]$ python2 -m pdb cplus.py
> /home/hope/Downloads/canalReplay/cplus.py(73)<module>()
-> import os, urllib, subprocess, time, sys
(Pdb) cont
Traceback (most recent call last):
File "/usr/lib/python2.7/pdb.py", line 1314, in main
pdb._runscript(mainpyfile)
File "/usr/lib/python2.7/pdb.py", line 1233, in _runscript
self.run(statement)
File "/usr/lib/python2.7/bdb.py", line 387, in run
exec cmd in globals, locals
File "<string>", line 1, in <module>
File "cplus.py", line 73, in <module>
import os, urllib, subprocess, time, sys
File "cplus.py", line 171, in Execute
p = subprocess.Popen(_Params,stdout=_File)
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> /usr/lib/python2.7/subprocess.py(1249)_execute_child()
-> raise child_exception
(Pdb) postmortem
*** NameError: name 'postmortem' is not defined
(Pdb) up
> /usr/lib/python2.7/subprocess.py(679)__init__()
-> errread, errwrite)
(Pdb) post_mortem
*** NameError: name 'post_mortem' is not defined
(Pdb) pm
*** NameError: name 'pm' is not defined
Hors ligne
mulder29
Re : [script] Télécharger de nombreuses quotidiennes de canal+ (suite)
Ah d'accord, c'est donc ici qu'il faut aller pour demander des renseignemetns pour extraire les vidéos de Canal Replay ?
Faut-il utiliser python ? ou le terminal/konsol suffit ?
Hors ligne
|
abelthorne
The Humble Voxatron Debut
Après la concurrence de l'IndieRoyale Bundle pas pour Linux, Wolfire revient dans la course avec le Humble Voxatron Debut. C'est la saison des bundles !
Bon, après un bundle d'un seul jeu (Frozen Synapse) récemment, voilà qu'ils nous refont le coup du jeu unique (Voxatron, donc) et en plus en alpha. Je comprends pas bien leur stratégie...
Comme d'habitude : prix libre à répartir comme on l'entend, jeu(x) disponible(s) pour Windows / MaxOS X / Linux, deux semaines pour l'offre. Adresse habituelle : http://www.humblebundle.com/
EDIT : rajout de Blocks that Matter et The Binding of Isaac dans le bundle. Avec clés Steam pour ceux-ci si vous préférez jouer sous Windows (et Mac ?).
Dernière modification par abelthorne (Le 01/11/2011, à 19:50)
Hors ligne
Cowa
Re : The Humble Voxatron Debut
Encore un bundle pour un jeu unique... et en alpha en plus ! Décidément, le Humble Bundle grâce à son succès n'est devenu qu'un simple annonceur et producteur de jeu indépendant. Dommage !
Bref, la démarche reste intéressante toute de même et le cross-platform est toujours respecté :,)
C'est bien la première fois que j'hésite à l'acheter.
Hors ligne
Ypnose
Re : The Humble Voxatron Debut
Hum, avant d'acheter, je veux savoir si c'est encore à base de Java ou quelque chose dans le genre...
abelthorne
Re : The Humble Voxatron Debut
J'ai pas l'impression. Dans le dossier une fois décompressé, il y a une lib SDL, un exécutable et un fichier .dat.
Hors ligne
Hors ligne
david96
Re : The Humble Voxatron Debut
Tiens je j'avais loupé le dernier Humble (faute à une connexion pourri en ce moment). Donc un seul jeu, pourquoi pas s'il est canon.
Qq'un la testé d'ailleurs ?
Hors ligne
abelthorne
Re : The Humble Voxatron Debut
Qq'un la testé d'ailleurs ?
Y a des gens qui aiment bien là : http://forum.canardpc.com/threads/61961 … tron-Debut
Il y en a un qui a torché la "campagne" en une heure mais je rappelle que pour l'instant, c'est une alpha.
Hors ligne
david96
Re : The Humble Voxatron Debut
Merci
Hors ligne
Ypnose
Re : The Humble Voxatron Debut
Si quelqu'un qui l'a acheté, peux utiliser ldd et montrer que c'est du sdl, je l'achèterais peut-être.
abelthorne
Re : The Humble Voxatron Debut
Vous voulez que je fasse un ldd sur l'exécutable ? Ça donne ça :
linux-gate.so.1 => (0xf771d000)
libSDL-1.2.so.0 => /usr/lib32/libSDL-1.2.so.0 (0xf7662000)
libGL.so.1 => /usr/lib32/fglrx/libGL.so.1 (0xf7578000)
libc.so.6 => /lib32/libc.so.6 (0xf73fd000)
libm.so.6 => /lib32/libm.so.6 (0xf73d3000)
libdl.so.2 => /lib32/libdl.so.2 (0xf73ce000)
libpulse-simple.so.0 => /usr/lib32/libpulse-simple.so.0 (0xf73c9000)
libpulse.so.0 => /usr/lib32/libpulse.so.0 (0xf737b000)
libpthread.so.0 => /lib32/libpthread.so.0 (0xf7360000)
libXext.so.6 => /usr/lib32/libXext.so.6 (0xf734c000)
libgcc_s.so.1 => /usr/lib32/libgcc_s.so.1 (0xf732e000)
/lib/ld-linux.so.2 (0xf771e000)
libpulsecommon-1.0.so => /usr/lib32/libpulsecommon-1.0.so (0xf72c9000)
libjson.so.0 => /usr/lib32/libjson.so.0 (0xf72c1000)
libdbus-1.so.3 => /lib32/libdbus-1.so.3 (0xf7278000)
libX11.so.6 => /usr/lib32/libX11.so.6 (0xf7141000)
libxcb.so.1 => /usr/lib32/libxcb.so.1 (0xf7122000)
libwrap.so.0 => /lib32/libwrap.so.0 (0xf7118000)
libsndfile.so.1 => /usr/lib32/libsndfile.so.1 (0xf70a7000)
libasyncns.so.0 => /usr/lib32/libasyncns.so.0 (0xf70a0000)
librt.so.1 => /lib32/librt.so.1 (0xf7096000)
libXau.so.6 => /usr/lib32/libXau.so.6 (0xf7092000)
libXdmcp.so.6 => /usr/lib32/libXdmcp.so.6 (0xf708b000)
libnsl.so.1 => /lib32/libnsl.so.1 (0xf7072000)
libFLAC.so.8 => /usr/lib32/libFLAC.so.8 (0xf7024000)
libvorbisenc.so.2 => /usr/lib32/libvorbisenc.so.2 (0xf6eab000)
libvorbis.so.0 => /usr/lib32/libvorbis.so.0 (0xf6e80000)
libogg.so.0 => /usr/lib32/libogg.so.0 (0xf6e78000)
libresolv.so.2 => /lib32/libresolv.so.2 (0xf6e61000)
Dernière modification par abelthorne (Le 01/11/2011, à 17:15)
Hors ligne
Ypnose
Re : The Humble Voxatron Debut
Pour ceux qui achètent le bundle, essayez de poster les outputs de la commande ldd sur les exécutables (d'autres jeux ajoutés). Parce que j'ai "essayé" de demander dans la chatbox, si c'était à base de Java ou autres, et j'ai eu l'impression de passer pour un extra-terrestre.
Merci à vous.
Dernière modification par Ypnose (Le 01/11/2011, à 19:10)
Cowa
Re : The Humble Voxatron Debut
Ajout de deux jeux : The Binding of Isaac et Blocks That Matter
Le bundle devient très intéressant maintenant !
Hors ligne
abelthorne
Re : The Humble Voxatron Debut
Wolfire a annoncé via le twitter du HIB qu'une màj pour The Binding of Isaac (Linux) devait être mise en ligne il y a une dizaine de minutes. Si vous l'avez déjà téléchargé, il n'est peut-être pas à jour (je ne sais pas si la version actuellement en ligne est la bonne). EDIT : ah oui, il y a une version 20111101 qui remplace la 20111031.
Des paquets DEB et RPM pour Blocks That Matter doivent arriver par la suite.
Pour ceux qui achètent le bundle, essayez de poster les outputs de la commande ldd sur les exécutables (d'autres jeux ajoutés). Parce que j'ai "essayé" de demander dans la chatbox, si c'était à base de Java ou autres, et j'ai eu l'impression de passer pour un extra-terrestre.
Merci à vous.
C'est si important pour toi que ce ne soit pas du Java ?
EDIT : pour BTM, c'est un .jar, donc pas besoin de ldd. Pour Isaac :
linux-gate.so.1 => (0xf77d9000)
libX11.so.6 => /usr/lib32/libX11.so.6 (0xf7682000)
libXt.so.6 => /usr/lib32/libXt.so.6 (0xf7626000)
libgtk-x11-2.0.so.0 => /usr/lib32/libgtk-x11-2.0.so.0 (0xf71bc000)
libgdk-x11-2.0.so.0 => /usr/lib32/libgdk-x11-2.0.so.0 (0xf710e000)
libpthread.so.0 => /lib32/libpthread.so.0 (0xf70f3000)
libgthread-2.0.so.0 => /usr/lib32/libgthread-2.0.so.0 (0xf70ed000)
libsqlite3.so.0 => /usr/lib32/libsqlite3.so.0 (0xf704b000)
libidn.so.11 => /usr/lib32/libidn.so.11 (0xf7017000)
libXxf86vm.so.1 => /usr/lib32/libXxf86vm.so.1 (0xf7011000)
librt.so.1 => /lib32/librt.so.1 (0xf7008000)
libstdc++.so.6 => /usr/lib32/libstdc++.so.6 (0xf6f1d000)
libm.so.6 => /lib32/libm.so.6 (0xf6ef3000)
libgcc_s.so.1 => /usr/lib32/libgcc_s.so.1 (0xf6ed4000)
libc.so.6 => /lib32/libc.so.6 (0xf6d5a000)
libdl.so.2 => /lib32/libdl.so.2 (0xf6d55000)
libSM.so.6 => /usr/lib32/libSM.so.6 (0xf6d4c000)
libgdk_pixbuf-2.0.so.0 => /usr/lib32/libgdk_pixbuf-2.0.so.0 (0xf6d2c000)
libpango-1.0.so.0 => /usr/lib32/libpango-1.0.so.0 (0xf6ce3000)
libgobject-2.0.so.0 => /usr/lib32/libgobject-2.0.so.0 (0xf6c93000)
libglib-2.0.so.0 => /lib32/libglib-2.0.so.0 (0xf6b9a000)
libXinerama.so.1 => /usr/lib32/libXinerama.so.1 (0xf6b96000)
libxcb.so.1 => /usr/lib32/libxcb.so.1 (0xf6b77000)
libICE.so.6 => /usr/lib32/libICE.so.6 (0xf6b5d000)
libpangocairo-1.0.so.0 => /usr/lib32/libpangocairo-1.0.so.0 (0xf6b4f000)
libXfixes.so.3 => /usr/lib32/libXfixes.so.3 (0xf6b49000)
libatk-1.0.so.0 => /usr/lib32/libatk-1.0.so.0 (0xf6b29000)
libcairo.so.2 => /usr/lib32/libcairo.so.2 (0xf6a5e000)
libgio-2.0.so.0 => /usr/lib32/libgio-2.0.so.0 (0xf6918000)
libpangoft2-1.0.so.0 => /usr/lib32/libpangoft2-1.0.so.0 (0xf68ea000)
libfontconfig.so.1 => /usr/lib32/libfontconfig.so.1 (0xf68b5000)
libgmodule-2.0.so.0 => /usr/lib32/libgmodule-2.0.so.0 (0xf68b0000)
libXext.so.6 => /usr/lib32/libXext.so.6 (0xf689d000)
libXrender.so.1 => /usr/lib32/libXrender.so.1 (0xf6892000)
libXi.so.6 => /usr/lib32/libXi.so.6 (0xf6881000)
libXrandr.so.2 => /usr/lib32/libXrandr.so.2 (0xf6878000)
libXcursor.so.1 => /usr/lib32/libXcursor.so.1 (0xf686d000)
libXcomposite.so.1 => /usr/lib32/libXcomposite.so.1 (0xf6869000)
libXdamage.so.1 => /usr/lib32/libXdamage.so.1 (0xf6865000)
/lib/ld-linux.so.2 (0xf77da000)
libuuid.so.1 => /lib32/libuuid.so.1 (0xf685e000)
libffi.so.6 => /usr/lib32/libffi.so.6 (0xf6857000)
libpcre.so.3 => /lib32/libpcre.so.3 (0xf6818000)
libXau.so.6 => /usr/lib32/libXau.so.6 (0xf6814000)
libXdmcp.so.6 => /usr/lib32/libXdmcp.so.6 (0xf680d000)
libfreetype.so.6 => /usr/lib32/libfreetype.so.6 (0xf6775000)
libpixman-1.so.0 => /usr/lib32/libpixman-1.so.0 (0xf66f2000)
libpng12.so.0 => /lib32/libpng12.so.0 (0xf66c8000)
libxcb-shm.so.0 => /usr/lib32/libxcb-shm.so.0 (0xf66c4000)
libxcb-render.so.0 => /usr/lib32/libxcb-render.so.0 (0xf66ba000)
libz.so.1 => /usr/lib32/libz.so.1 (0xf66a4000)
libselinux.so.1 => /lib32/libselinux.so.1 (0xf6686000)
libresolv.so.2 => /lib32/libresolv.so.2 (0xf666f000)
libexpat.so.1 => /lib32/libexpat.so.1 (0xf6645000)
Dernière modification par abelthorne (Le 01/11/2011, à 19:32)
Hors ligne
wido
Re : The Humble Voxatron Debut
The Binding of Isaac:
$ ldd ./isaac
linux-gate.so.1 => (0xf7736000)
libX11.so.6 => /usr/lib32/libX11.so.6 (0xf75bd000)
libXt.so.6 => /usr/lib32/libXt.so.6 (0xf756c000)
libgtk-x11-2.0.so.0 => /usr/lib32/libgtk-x11-2.0.so.0 (0xf7113000)
libgdk-x11-2.0.so.0 => /usr/lib32/libgdk-x11-2.0.so.0 (0xf7064000)
libpthread.so.0 => /lib32/libpthread.so.0 (0xf7048000)
libgthread-2.0.so.0 => /usr/lib32/libgthread-2.0.so.0 (0xf7042000)
libsqlite3.so.0 => /usr/lib32/libsqlite3.so.0 (0xf6fbd000)
libidn.so.11 => not found
libXxf86vm.so.1 => /usr/lib32/libXxf86vm.so.1 (0xf6fb8000)
librt.so.1 => /lib32/librt.so.1 (0xf6fae000)
libstdc++.so.6 => /usr/lib32/libstdc++.so.6 (0xf6ebf000)
libm.so.6 => /lib32/libm.so.6 (0xf6e95000)
libgcc_s.so.1 => /usr/lib32/libgcc_s.so.1 (0xf6e7a000)
libc.so.6 => /lib32/libc.so.6 (0xf6cfe000)
libdl.so.2 => /lib32/libdl.so.2 (0xf6cf9000)
libSM.so.6 => /usr/lib32/libSM.so.6 (0xf6cf1000)
libgdk_pixbuf-2.0.so.0 => /usr/lib32/libgdk_pixbuf-2.0.so.0 (0xf6cce000)
libpango-1.0.so.0 => /usr/lib32/libpango-1.0.so.0 (0xf6c84000)
libgobject-2.0.so.0 => /usr/lib32/libgobject-2.0.so.0 (0xf6c35000)
libglib-2.0.so.0 => /usr/lib32/libglib-2.0.so.0 (0xf6b3d000)
libXinerama.so.1 => /usr/lib32/libXinerama.so.1 (0xf6b39000)
libxcb.so.1 => /usr/lib32/libxcb.so.1 (0xf6b21000)
libICE.so.6 => /usr/lib32/libICE.so.6 (0xf6b0a000)
libXext.so.6 => /usr/lib32/libXext.so.6 (0xf6afc000)
libXi.so.6 => /usr/lib32/libXi.so.6 (0xf6aef000)
libXrandr.so.2 => /usr/lib32/libXrandr.so.2 (0xf6ae7000)
libXcursor.so.1 => /usr/lib32/libXcursor.so.1 (0xf6ade000)
libpangocairo-1.0.so.0 => /usr/lib32/libpangocairo-1.0.so.0 (0xf6ad1000)
libXcomposite.so.1 => /usr/lib32/libXcomposite.so.1 (0xf6ace000)
libXdamage.so.1 => /usr/lib32/libXdamage.so.1 (0xf6acb000)
libXfixes.so.3 => /usr/lib32/libXfixes.so.3 (0xf6ac5000)
libatk-1.0.so.0 => /usr/lib32/libatk-1.0.so.0 (0xf6aa4000)
libcairo.so.2 => /usr/lib32/libcairo.so.2 (0xf6a04000)
libpixman-1.so.0 => /usr/lib32/libpixman-1.so.0 (0xf6998000)
libpng14.so.14 => /usr/lib32/libpng14.so.14 (0xf696b000)
libXrender.so.1 => /usr/lib32/libXrender.so.1 (0xf6962000)
libz.so.1 => /usr/lib32/libz.so.1 (0xf694d000)
libgio-2.0.so.0 => /usr/lib32/libgio-2.0.so.0 (0xf6809000)
libpangoft2-1.0.so.0 => /usr/lib32/libpangoft2-1.0.so.0 (0xf67db000)
libfreetype.so.6 => /usr/lib32/libfreetype.so.6 (0xf6742000)
libfontconfig.so.1 => /usr/lib32/libfontconfig.so.1 (0xf6713000)
libgmodule-2.0.so.0 => /usr/lib32/libgmodule-2.0.so.0 (0xf670e000)
/lib/ld-linux.so.2 (0xf7737000)
libpcre.so.0 => /usr/lib32/libpcre.so.0 (0xf66cf000)
libuuid.so.1 => /usr/lib32/libuuid.so.1 (0xf66cb000)
libffi.so.5 => /usr/lib32/libffi.so.5 (0xf66c3000)
libXau.so.6 => /usr/lib32/libXau.so.6 (0xf66c0000)
libXdmcp.so.6 => /usr/lib32/libXdmcp.so.6 (0xf66bb000)
libresolv.so.2 => /lib32/libresolv.so.2 (0xf66a4000)
libbz2.so.1.0 => /usr/lib32/libbz2.so.1.0 (0xf6693000)
libexpat.so.1 => /usr/lib32/libexpat.so.1 (0xf666a000)
Hors ligne
Ypnose
Re : The Humble Voxatron Debut
C'est si important pour toi que ce ne soit pas du Java ?
Bah ouais. Le java c'est pas optimisé. Minecraft fait stresser mon ordi plus qu'avec OilRush...
love2hate
Re : The Humble Voxatron Debut
WOW team meat boy port un jeux sous linux je suis sur le q ( vu se qu'ils pensent de linux) et sinon isaac doit être en flahs me semble ?
1984 was not supposed to be an instruction manual
Some "poor" wine screencast http://www.youtube.com/user/2m42hy/videos?view=0
Hors ligne
wido
Re : The Humble Voxatron Debut
abelthorne a écrit :
C'est si important pour toi que ce ne soit pas du Java ?
Bah ouais. Le java c'est pas optimisé. Minecraft fait stresser mon ordi plus qu'avec OilRush...
+1
sinon isaac doit être en flahs me semble ?
Non
Dernière modification par wido (Le 01/11/2011, à 21:25)
Hors ligne
david96
Re : The Humble Voxatron Debut
Bon, comme pour les autres Humble je vais mettre la main à la poche pour soutenir ce projet.
Par contre n'ayant plus d'adsl et une connexion minable (parfois 8ko/secondes), pour le moment, je ne pourrais pas en profiter de suite.
J'aurais aimé savoir si les liens de téléchargement avaient une durée longue dans le temps ? Je pense avoir l'adsl en mars 2012.
Hors ligne
abelthorne
Re : The Humble Voxatron Debut
J'aurais aimé savoir si les liens de téléchargement avaient une durée longue dans le temps ? Je pense avoir l'adsl en mars 2012.
Les pages resteront en place aussi longtemps que possible. Pour te donner une idée, les pages de téléchargement du premier Humble Indie Bundle sont encore fonctionnelles (et heureusement !).
Hors ligne
abelthorne
Re : The Humble Voxatron Debut
Ils ont ajouté les paquets DEB et RPM pour Blocks That Matter, ainsi que la BO.
Hors ligne
david96
Re : The Humble Voxatron Debut
Ok, merci à vous… Bon allez, on va cracher la carte
Cool pour les .deb
Hors ligne
love2hate
Re : The Humble Voxatron Debut
Dernière modification par love2hate (Le 01/11/2011, à 22:42)
1984 was not supposed to be an instruction manual
Some "poor" wine screencast http://www.youtube.com/user/2m42hy/videos?view=0
Hors ligne
david96
Re : The Humble Voxatron Debut
Ça flash effectivement
Bon, j'ai pu télécharger Voxatron, 2.5 Mo, c'est dans mes moyens, et franchement j'aime le genre… graphiquement j'adore… Pas aussi prenant que VVVVVVV… Mais très content du jeu.
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'm using Python with pywin32's adodbapi to write a script to create a SQL Server database and all its associated tables, views, and procedures. The problem is that Python's DBAPI requires that cursor.execute() be wrapped in a transaction that is only committed by cursor.commit(), and you can't execute a drop or create database statement in a user transaction. Any ideas on how to get around that?
EDIT:
There does not seem to be anything analogous to an autocommit parameter to either the connect() method of adodbapi or its cursor() method. I'd be happy to use pymssql instead of adodbapi, except that it truncates char and varchar datatypes at 255 characters.
I did try this before posting; here's the traceback.
Traceback (most recent call last):
File "demo.py", line 39, in <module>
cur.execute("create database dummydatabase")
File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 713, in execute
self._executeHelper(operation,False,parameters)
File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 664, in _executeHelper
self._raiseCursorError(DatabaseError,tracebackhistory)
File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 474, in _raiseCursorError
eh(self.conn,self,errorclass,errorvalue)
File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 60, in standardErrorHandler
raise errorclass(errorvalue)
adodbapi.adodbapi.DatabaseError:
--ADODBAPI
Traceback (most recent call last):
File "C:\Python26\lib\site-packages\adodbapi\adodbapi.py", line 650, in _executeHelper
adoRetVal=self.cmd.Execute()
File "<COMObject ADODB.Command>", line 3, in Execute
File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 258, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft SQL Native Client', u'CREATE DATABASE statement not allowed within multi-statement transaction.', None, 0, -2147217900), None)
-- on command: "create database dummydatabase"
-- with parameters: None
|
Use the preexec_fn parameter to subprocess.Popen, and the resource module. Example:
parent.py:
#!/usr/bin/env python
import os
import sys
import resource
import subprocess
def setlimits():
# Set maximum CPU time to 1 second in child process, after fork() but before exec()
print "Setting resource limit in child (pid %d)" % os.getpid()
resource.setrlimit(resource.RLIMIT_CPU, (1, 1))
print "CPU limit of parent (pid %d)" % os.getpid(), resource.getrlimit(resource.RLIMIT_CPU)
p = subprocess.Popen(["./child.py"], preexec_fn=setlimits)
print "CPU limit of parent (pid %d) after startup of child" % os.getpid(), resource.getrlimit(resource.RLIMIT_CPU)
p.wait()
print "CPU limit of parent (pid %d) after child finished executing" % os.getpid(), resource.getrlimit(resource.RLIMIT_CPU)
child.py:
#!/usr/bin/env python
import os
import sys
import resource
print "CPU limit of child (pid %d)" % os.getpid(), resource.getrlimit(resource.RLIMIT_CPU)
parent.py will fork into a new process. In the new process, it will call setlimits(), then exec child.py. This means the resource will be limited in the child process, but not in the parent.
Output when running program:
./parent.py
CPU limit of parent (pid 17404) (-1, -1)
Setting resource limit in child (pid 17405)
CPU limit of parent (pid 17404) after startup of child (-1, -1)
CPU limit of child (pid 17405) (1, 1)
CPU limit of parent (pid 17404) after child finished executing (-1, -1)
This is in many cases a better solution than trying to use ulimit, since it's not always a good idea to spawn subprocess via shell, especially since it often causes ugly parameter quoting trouble.
|
I am trying to use one-time passwords that can be generated using Google Authenticator application.
What Google Authenticator does
Basically, Google Authenticator implements two types of passwords:
HOTP- HMAC-based One-Time Password, which means the password is changed with each call, in compliance to RFC4226, and
TOTP- Time-based One-Time Password, which changes for every 30-seconds period (as far as I know).
Google Authenticator is also available as Open Source here: code.google.com/p/google-authenticator
Current code
I was looking for existing solutions to generate HOTP and TOTP passwords, but did not find much. The code I have is the following snippet responsible for generating HOTP:
import hmac, base64, struct, hashlib, time
def get_token(secret, digest_mode=hashlib.sha1, intervals_no=None):
if intervals_no == None:
intervals_no = int(time.time()) // 30
key = base64.b32decode(secret)
msg = struct.pack(">Q", intervals_no)
h = hmac.new(key, msg, digest_mode).digest()
o = ord(h[19]) & 15
h = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
return h
The problem I am facing is that the password I generate using the above code is not the same as generated using Google Authenticator app for Android. Even though I tried multiple intervals_no values (exactly first 10000, beginning with intervals_no = 0), with secret being equal to key provided within the GA app.
Questions I have
My questions are:
What am I doing wrong?
How can I generate HOTP and/or TOTP in Python?
Are there any existing Python libraries for this?
To sum up: please give me any clues that will help me implement Google Authenticator authentication within my Python code.
|
toto2849
Connexion VPN automatique (NetworkManager)
Bonjour,:D
-Actuellement en stage il met demandé de mettre en place une connexion VPN qui se lance automatiquement au démarrage du pc ne laissant juste à l'utilisateur une boite de dialogue demandant login+pass.:rolleyes:
-J'ai déjà installé le plugin "network-manager-pptp" tout est ok la connexion fonctionne ! Cependant j'aimerais que celle-ci se lance d'elle même au démarrage du système malheureusement j'ai beau cocher la case "connexion automatique" rien n'y fait ! Bref je me penche actuellement sur une solution qui puisse en ligne de commande lancer la connexion VPN !
-Le must serait que l'on affiche une boite de dialogue au démarrage demandant les login (user+pass) puis de lancer la connexion dans la foulé. Si la demande des identifiants se fait par l'intermédiaire d'un script shell en console cela me conviendra amplement.
Voila voila merci à ceux qui auront le courage de lire ce message jusqu'à la fin et merci à ceux qui pourrons m'éclairer ! (n'hésiter pas à me demander plus de précision si besoin...)
Cordialement,
Anthony
Hors ligne
toto2849
Re : Connexion VPN automatique (NetworkManager)
UP personne ?
J'ai vu ceci sur le site suivant... mais RIEN ! Je ne sais pas comment activer automatiquement cette connexion....
Quelques infos peu utile ... http://projects.gnome.org/NetworkManage … Connection
Dernière modification par toto2849 (Le 04/06/2009, à 22:19)
Hors ligne
toto2849
Re : Connexion VPN automatique (NetworkManager)
Décidément personne peut m'aider ??
Hors ligne
toto2849
Re : Connexion VPN automatique (NetworkManager)
hop un UP pour la route....:rolleyes:
Hors ligne
killman
Re : Connexion VPN automatique (NetworkManager)
je n' ai pas eu le temps de me pencher sur la question, mais tu devrais essayer de rédiger un script qui lance la connexion cliente sur le vpn, si tu veux automatiser ça.
Hors ligne
toto2849
Re : Connexion VPN automatique (NetworkManager)
-Tout d'abord merci d'avoir répondu à mon problème car j'ai cru que tout le monde s'en foutait...
-Donc pour te répondre, oui en effet c'est ce que j'ai pensé aussi; d'ailleurs j'en ai commencé un morceau mais je ne connait pas les raccourcis me permettant de lancer en shell la connexion vpn de NetworkManager... Bien entendu si quelqu'un peut me proposer une méthode alternative qui ne passerait pas par ce gestionnaire cela me conviendra aussi !
Voici pour le moment ce que j'ai pu faire....mais je connais pas grand chose en script:
#!/bin/sh
#saisie des login
echo "Saisir nom d'utilisateur : "
read utilisateur
echo "Saisir mot de passe : "
read -s passe
#lancement de la connexion vpn
org.freedesktop.NetworkManager.ppp_starter ...mais cela est faux...
Comme dit plus haut j'ai trouvé sur leur site 2/3 truc comme "org.freedesktop.NetworkManager.VPN.Connection" mais es applicable pour lancer une connexion par la console ? j'ai tenté mais rien...peut être un soucis de syntaxe ?
Hors ligne
coredump
Re : Connexion VPN automatique (NetworkManager)
Moi, j'ai une solution avec NetworkManager.
Il s'agit d'un service qui utilise d-bus pour piloter le NetworkManager.
Le principe est assez simple, mais le script est assez complexe.
...
Suite aux différents échanges qui ont été fait sur le sujet, j'utilise ce post, pour proposer une solution simple et accessible aux néophytes.
Cette solution permet de lancer automatiquement une connexion vpn et qu'elle se reconnecte automatiquement en cas de coupure.
Remarques :
- Cette solution n'est pas forcément compatible avec d'ancienne version d'ubuntu.
- Pour une utilisation avancée, voir les autres posts de cette discussion, en particulier le post #28 (http://forum.ubuntu-fr.org/viewtopic.ph … 7#p3225667) de Papou qui propose des scripts qui permettent de lancer la connexion automatique "à la demande".
- Pour ceux qui auraient déjà mis en place le script connection-service, celui-ci a un peu évolué, il faut donc le mettre à jour.
Voici, la démarche, en deux étapes, à suivre :
- ajouter ce script exécutable 02-loop-vpn dans /etc/NetworkManager/dispatcher.d/ en ayant pris soin de renseigner le nom de la connexion vpn
/etc/NetworkManager/dispatcher.d/02-loop-vpn :
#!/bin/bash
# Script de lancement de connection VPN avec verification
CONNECTION_NAME="Connexion VPN 1"
while ! connection-service "$CONNECTION_NAME" status
do
connection-service "$CONNECTION_NAME" start
sleep 30
done
Soit, en ligne de commande :
sudo gedit /etc/NetworkManager/dispatcher.d/02-loop-vpn
copier/coller le code ci-dessus dans le fichier, et renseigner le champ CONNECTION_NAME avec le nom utilisé par le Network Manager pour votre connexion
sudo chmod +x /etc/NetworkManager/dispatcher.d/02-loop-vpn
- ajouter ce script exécutable connection-service dans /usr/local/bin/
/usr/local/bin/connection-service :
#!/bin/bash
############
# SETTINGS #
############
get_connections_paths()
{
dbus-send --system --print-reply --dest="$1" "/org/freedesktop/NetworkManagerSettings" "org.freedesktop.NetworkManagerSettings.ListConnections" \
| grep "object path" | cut -d '"' -f2
}
get_connection_settings()
{
dbus-send --system --print-reply --dest="$1" "$2" org.freedesktop.NetworkManagerSettings.Connection.GetSettings
}
get_connection_string_setting()
{
echo "$1" | grep -A 1 \""$2"\" | grep variant | cut -d '"' -f2
}
get_connection_id()
{
get_connection_string_setting "$1" "id"
}
get_connection_type()
{
get_connection_string_setting "$1" "type"
}
get_device_type_by_connection_type()
{
echo "$1" | grep -q "ethernet" && echo 1 && return
echo "$1" | grep -q "wireless" && echo 2 && return
echo 0
}
find_connection_path()
{
for connection_path in `get_connections_paths "$1"`
do
connection_settings=`get_connection_settings "$1" "$connection_path"`
connection_settings_id=`get_connection_id "$connection_settings"`
[ "$connection_settings_id" = "$2" ] && echo "$1" "$connection_path"
done
}
find_connection_path_everywhere()
{
find_connection_path "org.freedesktop.NetworkManagerSystemSettings" "$1"
find_connection_path "org.freedesktop.NetworkManagerUserSettings" "$1"
}
print_connections_ids()
{
for connection_path in `get_connections_paths "$1"`
do
connection_settings=`get_connection_settings "$1" "$connection_path"`
connection_settings_id=`get_connection_id "$connection_settings"`
echo "$connection_settings_id"
done
}
print_connections_ids_everywhere()
{
print_connections_ids "org.freedesktop.NetworkManagerSystemSettings"
print_connections_ids "org.freedesktop.NetworkManagerUserSettings"
}
###########
# DEVICES #
###########
get_devices_paths()
{
dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "/org/freedesktop/NetworkManager" "org.freedesktop.NetworkManager.GetDevices" \
| grep "object path" | cut -d '"' -f2
}
get_device_property()
{
dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "$1" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager.Device" string:"$2" \
| grep variant | awk '{print $3}'
}
get_device_type()
{
get_device_property "$1" "DeviceType"
}
get_device_path_by_device_type()
{
device_path_by_device_type="/"
for device_path in `get_devices_paths`
do
device_type=`get_device_type "$device_path"`
[ "$device_type" = "$1" ] && device_path_by_device_type="$device_path"
done
echo "$device_path_by_device_type"
}
#######################
# ACTIVES CONNECTIONS #
#######################
get_actives_connections_paths()
{
dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "/org/freedesktop/NetworkManager" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager" string:"ActiveConnections" \
| grep "object path" | cut -d '"' -f2
}
get_last_active_connection_path()
{
get_actives_connections_paths | tail -n 1
}
get_parent_connection_path_by_device_type()
{
parent_connection_path="/"
[ "$1" = 0 ] && parent_connection_path=`get_last_active_connection_path`
echo "$parent_connection_path"
}
get_active_connection_property()
{
dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "$1" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager.Connection.Active" string:"$2" \
| grep variant | awk -F '"' '{print $2}'
}
get_active_connection_service()
{
get_active_connection_property "$1" "ServiceName"
}
get_active_connection_path()
{
get_active_connection_property "$1" "Connection"
}
get_active_connection_path_by_connection_path()
{
for active_connection_path in `get_actives_connections_paths`
do
service=`get_active_connection_service $active_connection_path`
path=`get_active_connection_path $active_connection_path`
[ "$service" = "$1" ] && [ "$path" = "$2" ] && echo "$active_connection_path"
done
}
print_actives_connections_ids()
{
for active_connection_path in `get_actives_connections_paths`
do
service=`get_active_connection_service $active_connection_path`
path=`get_active_connection_path $active_connection_path`
connection_settings=`get_connection_settings "$service" "$path"`
connection_settings_id=`get_connection_id "$connection_settings"`
echo "$connection_settings_id"
done
}
##############
# START/STOP #
##############
start_connection()
{
my_connection_complete_path=`find_connection_path_everywhere "$1"`
my_connection_settings=`get_connection_settings $my_connection_complete_path`
my_connection_type=`get_connection_type "$my_connection_settings"`
my_connection_device_type=`get_device_type_by_connection_type "$my_connection_type"`
my_connection_service=`echo $my_connection_complete_path | awk '{print $1}'`
my_connection_path=`echo $my_connection_complete_path | awk '{print $2}'`
my_connection_device_path=`get_device_path_by_device_type "$my_connection_device_type"`
my_parent_connection_path=`get_parent_connection_path_by_device_type "$my_connection_device_type"`
echo "connection_service=$my_connection_service"
echo "connection_path=$my_connection_path"
echo "connection_device_path=$my_connection_device_path"
echo "parent_connection_path=$my_parent_connection_path"
dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" /org/freedesktop/NetworkManager "org.freedesktop.NetworkManager.ActivateConnection" string:"$my_connection_service" objpath:"$my_connection_path" objpath:"$my_connection_device_path" objpath:"$my_parent_connection_path"
}
stop_connection()
{
my_connection_complete_path=`find_connection_path_everywhere "$1"`
my_active_connection_path=`get_active_connection_path_by_connection_path $my_connection_complete_path`
echo "active_connection_path=$my_active_connection_path"
dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" /org/freedesktop/NetworkManager "org.freedesktop.NetworkManager.DeactivateConnection" objpath:"$my_active_connection_path"
}
########
# MAIN #
########
invalid_arguments()
{
echo "Usage: `basename "$0"` connexion_name start|stop"
echo "Connexion disponibles:"
print_connections_ids_everywhere
echo "Connexion actives:"
print_actives_connections_ids
exit 0
}
[ "$#" != 2 ] && invalid_arguments
case "$2" in
"start")
start_connection "$1"
;;
"stop")
stop_connection "$1"
;;
"restart")
stop_connection "$1"
start_connection "$1"
;;
"status")
if print_actives_connections_ids | grep -q -x "$1"
then
echo "Connexion \"$1\" active"
exit 0
else
echo "Connexion \"$1\" inactive"
exit 1
fi
;;
*)
invalid_arguments
;;
esac
Soit, en ligne de commande :
sudo gedit /usr/local/bin/connection-service
copier/coller le code ci-dessus dans le fichier, puis
sudo chmod +x /usr/local/bin/connection-service
Enjoy it!
Dernière modification par coredump (Le 30/01/2010, à 11:21)
Hors ligne
legrosschmoll
Re : Connexion VPN automatique (NetworkManager)
Ca n'a pas l'air d 'intéresser toto2849 mais moi oui. Si tu pouvais poster ta solution Merci d'avance
Precise sur W500
Hors ligne
coredump
Re : Connexion VPN automatique (NetworkManager)
Désolé, si je réponds un peu tard, ça fait un moment que je consulte pas le forum.
Voici ma solution, si ça t'intéresse toujours ou si ça intéresse quelqu'un d'autre.
L'origine du problème a deux sources par rapport au VPN avec Network Manager :
- quand on coche "Connecter automatiquement", ceci n'est pas pris en compte
- quand on coche "Disponible pour tous les utilisateurs", la connexion ne marche pas (à cause d'une histoire de clé quand on regarde les logs)
(En général, je trouve que le Network Manager a de légers disfonctionnements qui démontrent à mon avis quelques problèmes de conceptions ...)
Les scripts que je propose tente de remédier à cela.
Leur but est de connecter automatiquement le VPN et de le reconnecter automatiquement si il se déconnecte.
(Avec de légères modifications, ça pourrait se comporter différemment selon le besoin.)
Le principe est de se lancer et de s'arrêter en fonction d'une autre connexion parente (eth0 par exemple).
Puis de surveiller d-bus pour voir :
- si les paramètres de la connexion VPN sont disponibles (quand l'utilisateur se connecte)
- si la connexion VPN ne s'est pas déconnectée
Il y a deux scripts :
02-service-vpn -> à mettre dans /etc/NetworkManager/dispatcher.d/ (lance ou arrête "checkVPN" en fonction de la connexion parente)
checkVPN -> à mettre dans /usr/local/bin/ (script python qui surveille que la connexion VPN soit toujours bien connecter)
Tous deux doivent être exécutables.
checkVPN dépend d'un autre fichier :
nm_utils.py -> à mettre dans /usr/local/bin/ (outils pour piloter le nm en python)
Il y a deux champs à renseigner dans le script 02-service-vpn :
ETH_INTERFACE_NAME : l'interface de la connexion parente (par exemple : eth0)
VPN_CONNECTION_NAME : le nom de la connexion VPN qui a été renseigner dans le network manager
(Pour que ça marche pour plusieurs utilisateurs, il faut pour chacun définir la connexion VPN.)
(Il y a aussi la possibilité de décommenter des lignes pour avoir des traces.)
/etc/NetworkManager/dispatcher.d/02-service-vpn :
#!/bin/bash
ETH_INTERFACE_NAME="eth0"
# The name of the VPN connection to activate
VPN_CONNECTION_NAME="Connexion VPN"
# Or the uuid of the VPN connection to activate
#VPN_CONNECTION_NAME="UUID=abcf8915-bb27-4634-94e6-04c65261a73e"
SERVICE_VPN_LOG="/dev/null"
#SERVICE_VPN_LOG="/tmp/serviceVPN.log"
CHECK_VPN_LOG="/dev/null"
#CHECK_VPN_LOG="/tmp/checkVPN.log"
echo `date`": $0 $@" >> "$SERVICE_VPN_LOG"
[ "$1" != "$ETH_INTERFACE_NAME" ] && exit 0
case "$2" in
"up")
echo "Starting CheckVPN ... ("`which checkVPN`")" >> "$SERVICE_VPN_LOG"
# On vérifie que checkVPN ne tourne pas déjà
if [ "`pgrep checkVPN`" == "" ]
then
echo "CheckVPN started." >> "$SERVICE_VPN_LOG"
checkVPN "$VPN_CONNECTION_NAME" > "$CHECK_VPN_LOG" 2>&1 &
else
echo "CheckVPN already running !" >> "$SERVICE_VPN_LOG"
fi
;;
"down")
echo "Stoping checkVPN ..." >> "$SERVICE_VPN_LOG"
if [ "`pgrep checkVPN`" == "" ]
then
echo "CheckVPN not running !" >> "$SERVICE_VPN_LOG"
else
pkill checkVPN
echo "CheckVPN stopped." >> "$SERVICE_VPN_LOG"
fi
;;
*)
echo "Nothing to do" >> "$SERVICE_VPN_LOG"
;;
esac
/usr/local/bin/checkVPN :
#!/usr/bin/python -u
# coding=UTF-8
import sys
import dbus
from dbus.mainloop.glib import DBusGMainLoop
import gobject
from nm_utils import *
VPN_CONNECTION_UUID = VPN_CONNECTION_NAME = None
# Default values :
# The name of the VPN connection to activate
#VPN_CONNECTION_NAME = "Connexion VPN 1"
# or the uuid of the VPN connection to activate
#VPN_CONNECTION_UUID = "fabf8915-bb27-4634-94e6-04c65261a73e"
if len(sys.argv) > 1:
vpn_argument = sys.argv[1]
VPN_CONNECTION_UUID = VPN_CONNECTION_NAME = None
if (vpn_argument[:5] == "UUID="):
VPN_CONNECTION_UUID = vpn_argument[5:]
print "VPN_CONNECTION_UUID=%s" % (VPN_CONNECTION_UUID)
else:
VPN_CONNECTION_NAME = vpn_argument
print "VPN_CONNECTION_NAME=%s" % (VPN_CONNECTION_NAME)
if (not VPN_CONNECTION_UUID) and (not VPN_CONNECTION_NAME):
print "Usage : "+sys.argv[0]+" connexion_vpn_name"
print "Liste des connexions diponibles :"
print_connections_infos()
sys.exit(1)
vpn_connection_infos = {'vpn_connection_settings': None,
'vpn_connection_path': None}
def get_vpn_connection_settings():
if VPN_CONNECTION_UUID:
return get_connection_settings_by_uuid(VPN_CONNECTION_UUID)
if VPN_CONNECTION_NAME:
return get_connection_settings_by_name(VPN_CONNECTION_NAME)
return None
def get_vpn_connection_path():
if VPN_CONNECTION_UUID:
return get_active_connection_path_by_uuid(VPN_CONNECTION_UUID)
if VPN_CONNECTION_NAME:
return get_active_connection_path_by_name(VPN_CONNECTION_NAME)
return None
def get_eth_active_connection_path():
try:
active_connections_paths = get_active_connections_paths()
active_connections_paths_count = len(active_connections_paths)
if active_connections_paths_count == 0:
return None
return active_connections_paths[active_connections_paths_count-1]
except Exception as exception:
print exception
return None
def update_vpn_connection_settings():
vpn_connection_settings = get_vpn_connection_settings()
vpn_connection_infos['vpn_connection_settings'] = vpn_connection_settings
print "update_vpn_connection_settings=%s" % get_connection_infos(vpn_connection_settings)
def update_vpn_connection_path():
vpn_connection_path = get_vpn_connection_path()
vpn_connection_infos['vpn_connection_path'] = vpn_connection_path
print "update_vpn_connection_path: vpn_connection_path=%s" % vpn_connection_path
def start_connection(settings, active_connection_path):
def reply_handler(opath):
vpn_connection_path = opath
vpn_connection_infos['vpn_connection_path'] = vpn_connection_path
def error_handler(*args):
print args
proxy = dbus.SystemBus().get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager')
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager')
iface.ActivateConnection(get_connection_settings_type(settings),
get_connection_settings_path(settings),
dbus.ObjectPath("/"),
active_connection_path,
reply_handler=reply_handler,
error_handler=error_handler)
def checkVPN():
vpn_connection_settings = vpn_connection_infos['vpn_connection_settings']
# Do nothing if vpn connection settings don't exist
print "checkVPN: vpn_connection_settings=%s" % get_connection_infos(vpn_connection_settings)
if not vpn_connection_settings:
return
vpn_connection_path = vpn_connection_infos['vpn_connection_path']
# Do nothing if vpn connection already exist
print "checkVPN: vpn_connection_path=%s" % vpn_connection_path
if vpn_connection_path:
return
eth_connection_path = get_eth_active_connection_path()
print "checkVPN: eth_connection_path=%s" % eth_connection_path
# Do nothing if eth connection don't exist
if not eth_connection_path:
return
start_connection(vpn_connection_settings, eth_connection_path)
def handle_connection_settings_changed():
print "handle_connection_settings_changed"
update_vpn_connection_settings()
checkVPN()
def handle_connections_changed():
print "handle_connections_changed"
update_vpn_connection_path()
checkVPN()
def all_signal_receiver(*args, **kwargs):
if (kwargs['dbus_interface'] == "org.freedesktop.NetworkManagerSettings"):
handle_connection_settings_changed()
if (kwargs['dbus_interface'] == "org.freedesktop.NetworkManagerSettings.Connection")\
and (kwargs['signal_name'] == "Updated"):
handle_connection_settings_changed()
if (kwargs['dbus_interface'] == "org.freedesktop.NetworkManager")\
and (kwargs['signal_name'] == "PropertiesChanged")\
and args[0].has_key('ActiveConnections'):
handle_connections_changed()
DBusGMainLoop(set_as_default=True)
dbus.SystemBus().add_signal_receiver(all_signal_receiver,
interface_keyword='dbus_interface', member_keyword='signal_name')
update_vpn_connection_settings()
update_vpn_connection_path()
checkVPN()
gobject.MainLoop().run()
/usr/local/bin/nm_utils.py :
# coding=UTF-8
import dbus
# Get connection settings from settings type and settings path
# (settings type is 'org.freedesktop.NetworkManagerSystemSettings' or 'org.freedesktop.NetworkManagerUserSettings')
def get_connection_settings(settings_type, settings_path):
proxy = dbus.SystemBus().get_object(settings_type, settings_path)
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManagerSettings.Connection')
settings = iface.GetSettings()
settings['settings-type'] = settings_type
settings['settings-path'] = settings_path
return settings
# Get differents informations from connection settings
def get_connection_settings_type(settings):
return settings['settings-type']
def get_connection_settings_path(settings):
return settings['settings-path']
def get_connection_settings_uuid(settings):
return settings['connection']['uuid']
def get_connection_settings_name(settings):
return settings['connection']['id']
# Get all settings paths associated to a type of settings
def get_connections_settings_paths(settings_type):
try:
proxy = dbus.SystemBus().get_object(settings_type, '/org/freedesktop/NetworkManagerSettings')
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManagerSettings')
return iface.ListConnections()
except Exception as exception:
print " !!! get_connections_settings_paths:"
print exception
return []
# Get all connections settings associated to a type of settings
def get_connections_settings_by_type(settings_type):
connections_settings = []
for settings_path in get_connections_settings_paths(settings_type):
connection_settings = get_connection_settings(settings_type, settings_path)
connections_settings.append(connection_settings)
return connections_settings
# Get all connections settings
def get_all_connections_settings():
return get_connections_settings_by_type('org.freedesktop.NetworkManagerUserSettings') + \
get_connections_settings_by_type('org.freedesktop.NetworkManagerSystemSettings')
# Get the esssential informations of the connection
def get_connection_infos(settings):
if settings:
conn = settings['connection']
return "%s (type=%s, UUID=%s)" % (conn['id'], conn['type'], conn['uuid'])
else:
return None
# Print the list of connections
def print_connections_infos():
for connection_settings in get_all_connections_settings():
print get_connection_infos(connection_settings)
# Get connection settings from the settings UUID
def get_connection_settings_by_uuid(uuid):
try:
for settings in get_all_connections_settings():
if get_connection_settings_uuid(settings) == uuid:
return settings
except Exception as exception:
print exception
return None
# Get connection settings from the settings UUID
def get_connection_settings_by_name(name):
try:
for settings in get_all_connections_settings():
if get_connection_settings_name(settings) == name:
return settings
except Exception as exception:
print exception
return None
# Get list of active connections paths
def get_active_connections_paths():
proxy = dbus.SystemBus().get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager')
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties')
return iface.Get('org.freedesktop.NetworkManager', 'ActiveConnections')
# Get connection settings from the connection path
def get_connection_settings_by_connection_path(connection_path):
proxy = dbus.SystemBus().get_object('org.freedesktop.NetworkManager', connection_path)
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties')
settings_type = iface.Get('org.freedesktop.NetworkManager.Connection.Active', 'ServiceName')
settings_path = iface.Get('org.freedesktop.NetworkManager.Connection.Active', 'Connection')
return get_connection_settings(settings_type, settings_path)
# Get list of active connections paths
def get_active_connections_settings():
actives_connections_settings = []
for connection_path in get_active_connections_paths():
settings = get_connection_settings_by_connection_path(connection_path)
settings['connection-path'] = connection_path
actives_connections_settings.append(settings)
return actives_connections_settings
# Look for connexion path in active connexions with particular uuid
def get_active_connection_path_by_uuid(uuid):
try:
for connection_path in get_active_connections_paths():
settings = get_connection_settings_by_connection_path(connection_path)
if get_connection_settings_uuid(settings) == uuid:
return connection_path
except Exception as exception:
print exception
return None
# Look for connexion path in active connexions with particular name
def get_active_connection_path_by_name(name):
try:
for connection_path in get_active_connections_paths():
settings = get_connection_settings_by_connection_path(connection_path)
if get_connection_settings_name(settings) == name:
return connection_path
except Exception as exception:
print exception
return None
Voilà, ça peut certainement être amélioré ou généralisé, mais j'espère au moins que ça pourra te dépanner.
Hors ligne
ElFabio
Re : Connexion VPN automatique (NetworkManager)
En tout cas, ca en dépanne d'autres ! merci bp pour ce boulot coredump, ca marche nickel, et c'est en plus trés propre, pas grand chose à redire, si ce n'est merci !
Hors ligne
coredump
Re : Connexion VPN automatique (NetworkManager)
Merci ElFabio pour ton soutien et content que ça puisse te servir.
Une solution plus propre serait de trouver une correction au niveau du network manager ou de l'applet (est-ce que l'applet KDE marche ?).
Si j'avais un peu de temps et plus d'expérience dans la rédaction d'articles, j'aurais bien fait un tuto sur l'utilisation de d-bus pour contrôler le NM, car la documentation à ce sujet est assez maigre sur le net.
Voici quand même quelques liens qui m'ont été utiles :
- http://doc.ubuntu-fr.org/networkmanager … e_commande
- http://doc.ubuntu-fr.org/dbus
- http://old.nabble.com/dbus-and-OpenVPN- … 05375.html
- http://projects.gnome.org/NetworkManage … /spec.html
- http://linuxfr.org/forums/15/27406.html
- http://dbus.freedesktop.org/doc/dbus-py … orial.html
Je recommande aussi l'interface graphique d-feet pour s'exercer à utiliser d-bus (pratique aussi pour retrouver les API des services).
(Quand on veut être "listener" - à l'écoute - d'un service, la commande dbus-monitor aussi est pratique.)
Et pour ceux qui voudraient piloter NM à l'aide de d-bus, voici quelques exemples de lignes de commande qui permettent de le faire :
Afficher la liste des chemins des définitions des connexion selon leurs appartenances (système - disponibles pour tous les utilisateurs / personnel - propre à l'utilisateur) :
dbus-send --system --print-reply --dest=org.freedesktop.NetworkManagerSystemSettings "/org/freedesktop/NetworkManagerSettings" \
org.freedesktop.NetworkManagerSettings.ListConnections
(ou --dest="org.freedesktop.NetworkManagerUserSettings")
Afficher les paramètres d'une connexion selon son appartenance et connaissant son chemin
dbus-send --system --print-reply --dest=org.freedesktop.NetworkManagerSystemSettings "/org/freedesktop/NetworkManagerSettings/0" \
org.freedesktop.NetworkManagerSettings.Connection.GetSettings
(ou --dest="org.freedesktop.NetworkManagerUserSettings")
Afficher la liste des chemins des connexions actives :
dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager" \
org.freedesktop.DBus.Properties.Get string:"org.freedesktop.NetworkManager" string:"ActiveConnections"
Afficher une propriété d'une connexion active connaissant son chemin :
dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager/ActiveConnection/2" \
org.freedesktop.DBus.Properties.Get string:"org.freedesktop.NetworkManager.Connection.Active" string:"nom_de_la_propriete"
"nom_de_la_propriete" est à renseigner.
Par exemple, "nom_de_la_propriete" peut-être "ServiceName" ou "Connection" pour connaître l'appartenance et le chemin de la définition de la connexion.
Arrêter une connection active connaissant son chemin :
dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager" \
org.freedesktop.NetworkManager.DeactivateConnection objpath:"/org/freedesktop/NetworkManager/ActiveConnection/2"
Démarrer une connexion :
dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager" \
org.freedesktop.NetworkManager.ActivateConnection string:"org.freedesktop.NetworkManagerSystemSettings" objpath:"/org/freedesktop/NetworkManagerSettings/0" objpath:"/org/freedesktop/NetworkManager/Devices/0" objpath:"/"
ou dans le cas d'une connection vpn :
dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager" \
org.freedesktop.NetworkManager.ActivateConnection string:"org.freedesktop.NetworkManagerUserSettings" objpath:"/org/freedesktop/NetworkManagerSettings/1" objpath:"/" objpath:"/org/freedesktop/NetworkManager/ActiveConnection/2"
Le problème de cette commande est qu'il faut passer en argument de la commande le chemin du device (ethN ou rien pour le vpn) et le chemin de la connexion active dont elle dépend (si elle n'utilise pas de device). Malheureusement ces informations ne sont pas évidentes à déduire.
Pour terminer voici un exemple de script utilisant ces commandes et permettant de démarrer ou d'arrêter une connexion en lui passant le nom de la connexion.
Pour l'utiliser, nommer le fichier "connection-service", le rendre exécutable et placer le dans "/usr/local/bin/", puis taper :
connection-service "nom_de_la_connexion" start|stop
Par exemple :
connection-service "Connection VPN 1" start
/usr/local/bin/connection-service :
#!/bin/bash
############
# SETTINGS #
############
get_connections_paths()
{
dbus-send --system --print-reply --dest="$1" "/org/freedesktop/NetworkManagerSettings" "org.freedesktop.NetworkManagerSettings.ListConnections" \
| grep "object path" | cut -d '"' -f2
}
get_connection_settings()
{
dbus-send --system --print-reply --dest="$1" "$2" org.freedesktop.NetworkManagerSettings.Connection.GetSettings
}
get_connection_string_setting()
{
echo "$1" | grep -A 1 \""$2"\" | grep variant | cut -d '"' -f2
}
get_connection_id()
{
get_connection_string_setting "$1" "id"
}
get_connection_type()
{
get_connection_string_setting "$1" "type"
}
get_device_type_by_connection_type()
{
echo "$1" | grep -q "ethernet" && echo 1 && return
echo "$1" | grep -q "wireless" && echo 2 && return
echo 0
}
find_connection_path()
{
for connection_path in `get_connections_paths "$1"`
do
connection_settings=`get_connection_settings "$1" "$connection_path"`
connection_settings_id=`get_connection_id "$connection_settings"`
[ "$connection_settings_id" = "$2" ] && echo "$1" "$connection_path"
done
}
find_connection_path_everywhere()
{
find_connection_path "org.freedesktop.NetworkManagerSystemSettings" "$1"
find_connection_path "org.freedesktop.NetworkManagerUserSettings" "$1"
}
print_connections_ids()
{
for connection_path in `get_connections_paths "$1"`
do
connection_settings=`get_connection_settings "$1" "$connection_path"`
connection_settings_id=`get_connection_id "$connection_settings"`
echo "$connection_settings_id"
done
}
print_connections_ids_everywhere()
{
print_connections_ids "org.freedesktop.NetworkManagerSystemSettings"
print_connections_ids "org.freedesktop.NetworkManagerUserSettings"
}
###########
# DEVICES #
###########
get_devices_paths()
{
dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "/org/freedesktop/NetworkManager" "org.freedesktop.NetworkManager.GetDevices" \
| grep "object path" | cut -d '"' -f2
}
get_device_property()
{
dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "$1" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager.Device" string:"$2" \
| grep variant | awk '{print $3}'
}
get_device_type()
{
get_device_property "$1" "DeviceType"
}
get_device_path_by_device_type()
{
device_path_by_device_type="/"
for device_path in `get_devices_paths`
do
device_type=`get_device_type "$device_path"`
[ "$device_type" = "$1" ] && device_path_by_device_type="$device_path"
done
echo "$device_path_by_device_type"
}
#######################
# ACTIVES CONNECTIONS #
#######################
get_actives_connections_paths()
{
dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "/org/freedesktop/NetworkManager" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager" string:"ActiveConnections" \
| grep "object path" | cut -d '"' -f2
}
get_last_active_connection_path()
{
get_actives_connections_paths | tail -n 1
}
get_parent_connection_path_by_device_type()
{
parent_connection_path="/"
[ "$1" = 0 ] && parent_connection_path=`get_last_active_connection_path`
echo "$parent_connection_path"
}
get_active_connection_property()
{
dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "$1" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager.Connection.Active" string:"$2" \
| grep variant | awk -F '"' '{print $2}'
}
get_active_connection_service()
{
get_active_connection_property "$1" "ServiceName"
}
get_active_connection_path()
{
get_active_connection_property "$1" "Connection"
}
get_active_connection_path_by_connection_path()
{
for active_connection_path in `get_actives_connections_paths`
do
service=`get_active_connection_service $active_connection_path`
path=`get_active_connection_path $active_connection_path`
[ "$service" = "$1" ] && [ "$path" = "$2" ] && echo "$active_connection_path"
done
}
print_actives_connections_ids()
{
for active_connection_path in `get_actives_connections_paths`
do
service=`get_active_connection_service $active_connection_path`
path=`get_active_connection_path $active_connection_path`
connection_settings=`get_connection_settings "$service" "$path"`
connection_settings_id=`get_connection_id "$connection_settings"`
echo "$connection_settings_id"
done
}
##############
# START/STOP #
##############
start_connection()
{
my_connection_complete_path=`find_connection_path_everywhere "$1"`
my_connection_settings=`get_connection_settings $my_connection_complete_path`
my_connection_type=`get_connection_type "$my_connection_settings"`
my_connection_device_type=`get_device_type_by_connection_type "$my_connection_type"`
my_connection_service=`echo $my_connection_complete_path | awk '{print $1}'`
my_connection_path=`echo $my_connection_complete_path | awk '{print $2}'`
my_connection_device_path=`get_device_path_by_device_type "$my_connection_device_type"`
my_parent_connection_path=`get_parent_connection_path_by_device_type "$my_connection_device_type"`
echo "connection_service=$my_connection_service"
echo "connection_path=$my_connection_path"
echo "connection_device_path=$my_connection_device_path"
echo "parent_connection_path=$my_parent_connection_path"
dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" /org/freedesktop/NetworkManager "org.freedesktop.NetworkManager.ActivateConnection" string:"$my_connection_service" objpath:"$my_connection_path" objpath:"$my_connection_device_path" objpath:"$my_parent_connection_path"
}
stop_connection()
{
my_connection_complete_path=`find_connection_path_everywhere "$1"`
my_active_connection_path=`get_active_connection_path_by_connection_path $my_connection_complete_path`
echo "active_connection_path=$my_active_connection_path"
dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" /org/freedesktop/NetworkManager "org.freedesktop.NetworkManager.DeactivateConnection" objpath:"$my_active_connection_path"
}
########
# MAIN #
########
invalid_arguments()
{
echo "Usage: `basename "$0"` connexion_name start|stop"
echo "Connexion disponibles:"
print_connections_ids_everywhere
echo "Connexion actives:"
print_actives_connections_ids
exit 0
}
[ "$#" != 2 ] && invalid_arguments
case "$2" in
"start")
start_connection "$1"
;;
"stop")
stop_connection "$1"
;;
"restart")
stop_connection "$1"
start_connection "$1"
;;
"status")
if print_actives_connections_ids | grep -q -x "$1"
then
echo "Connexion \"$1\" active"
exit 0
else
echo "Connexion \"$1\" inactive"
exit 1
fi
;;
*)
invalid_arguments
;;
esac
Dernière modification par coredump (Le 28/01/2010, à 13:21)
Hors ligne
ElFabio
Re : Connexion VPN automatique (NetworkManager)
effectivement, tu as bien potassé ton d-bus ! et de rien pour le soutien, c'est le moins que je puisse faire, surtout que j'utilise maintenant ton script tous les jours ! vraiment exactement ce que je recherchais !
Hors ligne
coredump
Re : Connexion VPN automatique (NetworkManager)
Par les temps qui courent, il vaut mieux surfer bien couvert
Hors ligne
Brunod
Re : Connexion VPN automatique (NetworkManager)
Salut,
Je te félicite anticipativement parce que là, en congé, je n'en ai pas besoin; mais à la rentrée, faudra que je me penche dessus !
Merci !
Wanted : >>> un emploi dans la sécurité informatique et réseau <<<
Windows est un système d'exploitation de l'homme par l'ordinateur.
Linux, c'est le contraire ... --> état de la conversion : 36 pc linux
Hors ligne
coredump
Re : Connexion VPN automatique (NetworkManager)
À noter, que le script "connection-service" défini dans mon post #11 ci-dessus peut aussi être utilisé pour connecter automatiquement le VPN.
Pour cela, créer un script "vpn-autostart" exécutable dans "/usr/local/bin/",
/usr/local/bin/vpn-autostart :
#!/bin/bash
# Délai de 10 secondes pour laisser le temps à nm-applet de démarrer
sleep 10 && connection-service "Connection VPN 1" start
Ajouter ensuite un programme "VPN" dans la liste des "Applications au démarrage" avec comme commande :
vpn-autostart
Ceci démarrera la connexion "Connection VPN 1" à l'ouverture de la session.
Et pour reconnecter automatiquement la connexion en cas de coupure, ajouter ce script "02-loop-vpn" exécutable dans "/etc/NetworkManager/dispatcher.d/":
/etc/NetworkManager/dispatcher.d/02-loop-vpn :
#!/bin/bash
[ "$2" = "vpn-down" ] && vpn-autostart
Et voilà !
Hors ligne
lynn
Re : Connexion VPN automatique (NetworkManager)
Bonjour,
Merci à toi coredump pour ces scripts de connection automatique pour VPN. Ils fonctionnent parfaitement
Comme tu le dis si bien :
- quand on coche "Connecter automatiquement", ceci n'est pas pris en compte
- quand on coche "Disponible pour tous les utilisateurs", la connexion ne marche pas (à cause d'une histoire de clé quand on regarde les logs)
A quand un Network Manager complètement fonctionnel ? Parce que c'est vrai que ce genre de "détails" est quand même bien ch...t.
En attendant, merci encore coredump et je pense que ce post va intéresser pas mal de monde .....:P
Linux est la solution ! Au fait, c'est quoi ton problème ?
Ubuntu 14.04 - 64 bits - Ubuntu 14.10 - 64 bits - Utopic Unicorn
Hors ligne
ElFabio
Re : Connexion VPN automatique (NetworkManager)
Merci encore une fois coredump pour ce tutoriel trés pratique et directement utilisable, j'en profite pour abuser un peu de tes compétences pour te poser une question concernant l'usage de tes scripts (j'utilise en particulier checkVPN) : aprés maintenant plusieurs jours d'utilisation, je remarque qu'au fur et à mesure de mes reconnexions automatique à mon provider VPN (lors d'une déconnexion), le débit global des téléchargements (dans mon client torrent préféré...) a tendance à se contracter fortement (divisé par 2 ou 3), et un simple redémarrage du PC permet de revenir à un débit normal. Pour info je me connecte en WiFi, et peut être n'est ce pas du à l'utilisation de tes scripts, mais est ce que ca ne pourrait pas venir d'un "engorgement" de process qui s'accumulent en taches de fond suite à de multiples déconnexion/reconnexion VPN, je ne pense pas trop parce qu'en faisant un ps aux je n'en trouve pas trace et qu'en plus ton script me parait vraiment trés propre, mais je n'ai pas d'explications plausibles... est ce que tu aurais déjà rencontré le même genre de soucis ou aurais tu une idée de leur origine ?
Je te souhaite une trés bonne année,
Hors ligne
rogerjm
Re : Connexion VPN automatique (NetworkManager)
Bravo coredump pour ce post (qui n'est pas loin d'être un article ). Tout ce que tu y as décrit m'a été très utile pour configurer mon VPN et le lancer automatiquement, mais aussi m'a appris plein de choses.
Bonne année
Hors ligne
coredump
Re : Connexion VPN automatique (NetworkManager)
Bonne année à tous !
Au sujet de ton problème, ElFabio, je ne pense pas pouvoir t'aider beaucoup.
À vue de nez, voici mes impressions :
- Concernant le script de reconnexion, ça m'étonnerait qu'il puisse provoquer un "engorgement".
La plupart du temps il est au repos (en attente d'évènements) et quand il bosse, il ne fait jamais que quelques petites opérations.
Le seul petit souci que je verrais, serait le délai de reconnexion.
En cas de coupure, il cherche instantanément à se reconnecter et ce n'est peut-être pas très bon.
J'ai remarqué qu'en cas de coupure, la reconnexion ne se fait pas toujours à la première tentative.
Le fait d'envoyer des requêtes de reconnexion aussi proches n'est peut-être pas très bon.
En même temps, une fois qu'il s'est reconnecté, je n'ai pas observé pour ma part de diminution de la bande passante.
Mais, si tu veux chercher dans cette voie, tu peux essayer avec l'autre méthode (elle n'utilise pas de process en fond de tâche)
et jouer sur le délai de reconnection.
Les autres pistes pourraient venir à mon avis de la connexion Wifi, du client torrent ou du service VPN :
- Pour la connexion Wifi, j'ai entendu dire que le peer-to-peer n'est pas très bon.
J'ai eu à une époque un fournisseur internet wifi qui interdisait de faire du peer-to-peer sur son réseau (sinon ça le faisait planter).
De cette époque, j'ai pris l'habitude de faire du warez, je n'utilise les torrents que de façon ponctuel, donc je n'ai pas trop d'expérience à ce sujet.
Tout ce que je peux te dire, c'est que je ne rencontre pas ce problème avec les boards warez et JDownloader.
Pour explorer cette piste, il faudrait que tu es la possibilité de tester la différence avec une connexion filaire,
ou consulter les forums sur les torrents et le Wifi.
- Pour le client torrent, peut-être que le fait d'avoir des coupures le perturbe.
Une possibilité pourrait être de le relancer quand tu observes une diminution de débit et voir si ça change quelque chose.
Ou voir si tu observes aussi sur cette baisse de débit sur un test de bande passante (avec speedtest.net, par exemple).
- Le fournisseur VPN peut-être aussi offre de moins bon service au bout d'une certaine durée de connexion.
Là, si tu as la possibilité d'essayer une autre connexion VPN pour voir la différence.
Ou provoquer volontairement les coupures VPN depuis l'applet du Network Manager pour voir si ce sont bien les coupures qui font baisser le débit.
En gros, essaye de voir, et si c'est possible, si ton problème persiste :
- sans vpn (mais ça, tu le sais surement déjà)
- ou avec une connexion réseau filaire
- ou en redémarrant le client torrent
- ou en redémarrant le Network Manager (sudo service network-manager restart, NetworkManager pour les versions d'ubuntu plus anciennes)
- ou en espaçant les délais entre les reconnections
- ou avec un autre fournisseur VPN (personnellement, j'utilise HideMyNet, un peu payant)
ça t'aidera peut-être mieux à localiser ton problème qu'en redémarrant le pc.
Bonne chance !
Dernière modification par coredump (Le 02/01/2010, à 12:14)
Hors ligne
ElFabio
Re : Connexion VPN automatique (NetworkManager)
Déjà je te remercie pour avoir pris autant de temps pour me répondre, je vais essayer de reparcourir les pistes que tu as mentionné mais, effectivement, ce sont également sensiblement les mêmes que celles que j'avais regardé jusque-là. Mes premieres impresssions tendraient à confirmer les tiennes, le probléme semblerait effectivement provenir davantage de la connexion en Wifi, puisque j'utilise également tes scripts sur un PC fixe en ethernet avec le même provider VPN, et je ne rencontre pas ce genre de problème. J'avais déjà éliminé la piste du provider VPN dont je suis personnellement trés satisfait (il s'agit de TorrentFreedom), et d'ailleurs le fait qu'en redémarrant le PC je retrouve un débit normal tend également à confirmer que le pb ne vient pas de là. D'ailleurs je n'ai pas, comme tu le mentionnes pour toi, de problémes de connexion particulier au VPN, la connexion se fait trés rapidement, par contre, en revanche, il se produit des déconnexions au VPN de façon trés régulière voire périodique (presque toutes les 30mn), ce qui me fait également pencher vers un probléme WiFi ou plutôt de passerelle (Livebox dans mon cas actuel) voire de FAI...
Je vais par contre également regarder du côté de ton 2eme script pour voir si j'observe des changements.
En tout cas, merci pour ton temps et ta réponse, ca me permet de disposer d'un 2eme avis "éclairé" sur le sujet !
Hors ligne
hybernatus
Re : Connexion VPN automatique (NetworkManager)
Fiou... merci pour ce script et tout ton boulot, je me suis abonné hier à Ipredator (ayant trouvé un super tuto, et n'y connaissant rien en réseaux, j'ai fait au plus simple ^^ ) et j'ai remarqué qu'il se déconnecte de temps en temps... ce qui est un peu c*n tout de même quand on veut une connexion sécurisée et anonyme je trouve
J'essairai d'appliquer ça dès que je trouve la motiv merci !
Mes photos: http://www.hyb.me/photos
Hors ligne
ElFabio
Re : Connexion VPN automatique (NetworkManager)
Salut coredump, je reviens juste vers toi pour te faire un petit debriefing : ta deuxiéme solution (via connection-service) a résolu mes problémes de "coupure" intempestive et réguliére du VPN, je l'ai un peu aménagé à ma sauce, notamment pour disposer d'une connexion 'manuelle' au VPN et non un lancement automatique au démarrage, mais, que ce soit en Wi-Fi ou en Ethernet, cela fonctionne maintenant parfaitement. Donc encore merci pour ton travail, et bonne continuation !
Hors ligne
Papou
Re : Connexion VPN automatique (NetworkManager)
Merci Coredump pour ces scripts très utiles.
La reconnection automatique c'est nickel .... sauf quand c'est le modem qui décroche de l'ADSL et met un peu de temps pour redémarrer, la reconnection au VPN n'aboutit alors pas et l'accès internet se retrouve en direct quelques secondes plus tard.
Serait-il possible de faire encore mieux ?
Un pour tous et tous pour un, les petits ruisseaux feront les grandes rivières ...
Hors ligne
coredump
Re : Connexion VPN automatique (NetworkManager)
Tout d'abord merci ElFabio pour ton retour d'expérience.
A mon avis :
- la première solution (en python) est plus fiable, car le service tourne en tâche de fond et ne dépend pas de la connexion de l'utilisateur, mais plus complexe et donc plus difficile à maintenir,
- la deuxième (en shell) est plus simple et plus clair, et donc plus adaptable et plus facile à maintenir, et par expérience marche bien.
Et en définitif, je conseillerai donc plutôt celle-ci.
Pour rappel, cette méthode est décrite dans le post #15 avec le script "connection-service" de la fin du poste #11.
(Si je trouve un peut de temps, j'en ferais bien la synthèse dans un tuto ...)
Ensuite par rapport à Papou, si tu veux que le vpn se reconnecte quand ta connexion adsl se reconnecte (j'imagine que tu utilises la deuxième méthode et qu'il ne s'agit pas d'une connexion adsl pppoe ?), tu peux essayer d'ajouter cette ligne dans le script
/etc/NetworkManager/dispatcher.d/02-loop-vpn :
[ "$2" = "up" ] && vpn-autostart
(Pour voir si ça marche, tu peux essayer en redémarrant à la main ton modem en cours de connexion.)
Dernière modification par coredump (Le 18/01/2010, à 15:45)
Hors ligne
Papou
Re : Connexion VPN automatique (NetworkManager)
coredump,
Merci pour ta réponse.
j'utilise la deuxième méthode et il s'agit d'une connexion adsl pppoe.
L'inconvénient d'ajouter la ligne "[ "$2" = "up" ] && vpn-autostart" est qu'il devient alors impossible de déconnecter volontairement le VPN pour les applications qui ne le supporte pas (sauf a écrire un script de déconnexion volontaire qui va déplacer le fichier 02-loop-vpn en dehors de dispatcher).
D'autre part, il me semble avoir remarqué que le problème est que la connection VPN échoue parfois (timeout d'environ 10 sec ? ) et qu'il n'y a alors pas de deuxième essai.
Un pour tous et tous pour un, les petits ruisseaux feront les grandes rivières ...
Hors ligne
|
I wrote what I thought was a straightforward Python script to traverse a given directory and tabulate all the file suffixes it finds. The output looks like this:
OTUS-ASIO:face fish$ sufs
>>> /Users/fish/Dropbox/ost2/face (total 194)
=== 1 1 -
=== css 16 -----
=== gif 14 -----
=== html 12 ----
=== icc 87 --------------------------
=== jpg 3 -
=== js 46 --------------
=== png 3 -
=== zip 2 -
... which would be great, if those values were correct. They are not. Here's what happens when I run it in a subdirectory of the directory I listed above:
OTUS-ASIO:face fish$ cd images/
OTUS-ASIO:images fish$ sufs
>>> /Users/fish/Dropbox/ost2/face/images (total 1016)
=== JPG 3 -
=== gif 17 -
=== ico 1 -
=== jpeg 1 -
=== jpg 901 --------------------------
=== png 87 ---
... It only seems to go one directory level down. Running the script one level up didn't pick up on the 'jpeg' suffix at all, and seemed to miss a good 898 jpg files.
The script in question is here:
#!/usr/bin/env python
# encoding: utf-8
"""
getfilesuffixes.py
Created by FI$H 2000 on 2010-10-15.
Copyright (c) 2010 OST, LLC. All rights reserved.
"""
import sys, os, getopt
help_message = '''
Prints a list of all the file suffixes found in each DIR, with counts.
Defaults to the current directory wth no args.
$ %s DIR [DIR DIR etc ...]
''' % os.path.basename(__file__)
dirs = dict()
skips = ('DS_Store','hgignore')
class Usage(Exception):
def __init__(self, msg):
self.msg = msg
def getmesomesuffixes(rootdir, thisdir=None):
if not thisdir:
thisdir = rootdir
for thing in [os.path.abspath(h) for h in os.listdir(thisdir)]:
if os.path.isdir(thing):
getmesomesuffixes(rootdir), thing)
else:
if thing.rfind('.') > -1:
suf = thing.rsplit('.').pop()
dirs[rootdir][suf] = dirs[rootdir].get(suf, 0) + 1
return
def main(argv=None):
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "h", ["help",])
except getopt.error, msg:
raise Usage(msg)
for option, value in opts:
if option == "-v":
verbose = True
if option in ("-h", "--help"):
raise Usage(help_message)
if len(args) == 0:
args.append(os.getcwd())
for durr in [os.path.abspath(arg) for arg in args]:
if os.path.isdir(durr):
dirs[durr] = dict()
for k, v in dirs.items():
getmesomesuffixes(k)
print ""
for k, v in dirs.items():
sufs = v.items()
sufs.sort()
maxcount = reduce(lambda fs, ns: fs > ns and fs or ns, map(lambda t: t[1], sufs), 1)
mincount = reduce(lambda fs, ns: fs < ns and fs or ns, map(lambda t: t[1], sufs), 1)
total = reduce(lambda fs, ns: fs + ns, map(lambda t: t[1], sufs), 0)
print ">>>\t\t\t%s (total %s)" % (k, total)
for suf, sufcount in sufs:
try:
skips.index(suf)
except ValueError:
print "===\t\t\t%12s\t %3s\t %s" % (suf, sufcount, "-" * (int(float(float(sufcount) / float(maxcount)) * 25) + 1))
print ""
except Usage, err:
print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
print >> sys.stderr, "\t for help use --help"
return 2
if __name__ == "__main__":
sys.exit(main())
It seems that getmesomesuffixes() is subtly not doing what I want it to. I hate to ask such an annoying question, but if anyone can spot whatever amateur-hour error I am making with a quick once-over, it would save me some serious frustration.
|
While looking over some code in Think Complexity, I noticed their Graph class assigning values to itself. I've copied a few important lines from that class and written an example class, ObjectChild, that fails at this behavior.
class Graph(dict):
def __init__(self, vs=[], es=[]):
for v in vs:
self.add_vertex(v)
for e in es:
self.add_edge(e)
def add_edge(self, e):
v, w = e
self[v][w] = e
self[w][v] = e
def add_vertex(self, v):
self[v] = {}
class ObjectChild(object):
def __init__(self, name):
self['name'] = name
I'm sure the different built in types all have their own way of using this, but I'm not sure whether this is something I should try to build into my classes. Is it possible, and how? Is this something I shouldn't bother with, relying instead on simple composition, e.g. self.l = [1, 2, 3]? Should it be avoided outside built in types?
I ask because I was told "You should almost never inherit from the builtin python collections"; advice I'm hesitant to restrict myself to.
To clarify, I know that ObjectChild won't "work", and I could easily make it "work", but I'm curious about the inner workings of these built in types that makes their interface different from a child of object.
|
Ruby has a couple of well-known libraries for unit testing, mocking and stubbing HTTP interactions. My typical toolset includes RSpec, WebMock and VCR. I had the chance to work on a Python project recently and did some investigation into similar libraries for Python.
General testing libraries
The two most popular python test libraries + runners are py.test and nose. A neat feature of py.test is that is gets by with only the builtin ‘assert’ keyword: the test runner expands assertion failures to show exactly how the assertion failed e.g.:
===================== FAILURES =====================
_____________________ test_web _____________________
def test_web():
resp = c.get('/')
> assert resp.status == '404'
E assert '200 OK' == '404'
E - 200 OK
E + 404
lib/test_snack_overflow.py:9: AssertionError
============= 1 failed in 0.24 seconds =============
One gotcha is that py.test silences stdout by default, so you’ll need to pass the -s flag to see any debugging output.
Test doubles
The mock library can be installed through pip for Python 2 and comes as part of the standard library of Python 3. As an example of mocking out an environment variable using a context manager:
with mock.patch.dict('os.environ', {'APP_NAME': 'HelloWorld'}):
assert app.name = 'HelloWorld'
There’s also a decorator form, nice because it clearly states what modules are being mocked in your tests:
@mock.patch('crazyservice')
def test_nationals_stats(_crazyservice):
_crazyservice.date = "2013-04-06 12:31 AM"
Another gotcha for newcomers to Python testing: not all methods can be replaced at runtime. A good example is stubbing DateTime.now in ruby: the equivalent monkeypatching in python raises:
TypeError: can’t set attributes of built-in/extension type ‘datetime.datetime’
as these methods cannot be replaced in CPython. You’ll need to write a wrapper function and mock that out instead in your tests.
Web testing
The werkzeug WSGI library includes simple utilities to make request testing as easy as with rack-test. Another library I’m a big fan of is HTTPretty, which is similar to Ruby’s WebMock or FakeWeb. Finally, Ruby’s VCR gem is invaluable for recording real HTTP interactions. A port exists on python called vcr.py.
|
Suppose I have 4 words, as a string. How do I join them all like this?
s = orange apple grapes pear
The result would be a String:
"orangeapple/orangegrapes/orangepear/applegrapes/applepear/grapespear/orangeapplegrapes/orangeapplepear/applegrapespear"
I am thinking:
list_words = s.split(' ')
for l in list_words:
And then use enumerate? Is that what you would use to do this function?
|
I my code I have a dictionary which has two lists combined with zip() function
self.dict = OrderedDict(zip(self.name,self.unit))
The lists are given as arguments... var=class([[1,2,4,7],["y","y","t"],[11.1,12.3,6]],name=["num1","letter","num2"])
In one point there should be a function which checks if the items in the each brackets has numbers only. for example int=[1,2,3]if that's true the program calculates the average for each number only list. And prints out the values as num1 = 3.5 num2 = 9.8 (as a table):
num1 num2 3.5 9.8
First I make a new list using this:
for i in range(len(self.unit)):
if all(isinstance(item, (int,float)) for item in self.unit[i]):
self.new_l.append(self.unit[i])
After that I (in another function) create a new list called self.sum_l in which put in the average of each number list in a new list of lists (In this example i get two averages).
self.sum_l.append([sum(self.new_1[i])/float(len(self.new_1[i]))])
After that I make a new dictionary which uses the self.name and the self.sum_1 lists
self.nov_slovar = OrderedDict(zip(self.ime, self.seznam_vsot))
Which works fine, but the PROBLEM I'm facing is... when I create a new dictionary the code takes as much elements out of list name when forming a new dictionary, as there are lists in the self.sum_1 list. But the thing is, it takes the first two (in my case). And that makes the output absolutely incorrect:
num1 letter 4.6 9.8
So my question is, what should I do to prevent that from happening. I've tried many things. Even trying to calculate the sum of values in a dictionary, but I'm getting errors
|
In perl, to get a list of all strings from "a" to "azc", to only thing to do is using the range operator:
perl -le 'print "a".."azc"'
What I want is a list of strings:
["a", "b", ..., "z", "aa", ..., "az" ,"ba", ..., "azc"]
I suppose I can use ord and chr, looping over and over, this is simple to get for "a" to "z", eg:
>>> [chr(c) for c in range(ord("a"), ord("z") + 1)]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
But a bit more complex for my case, here.
Thanks for any help !
|
In Io, you can set the execution context using do:
Http := Object clone
Http get := method(uri, ("<GET request to " .. uri .. ">") println)
Http delete := method(uri, ("<DELETE request to " .. uri .. ">") println)
Database := Object clone
Database insert := method(table, data, ("<insert data to " .. table .. ">") println)
Database delete := method(table, id, ("<delete " .. id .. " from " .. table .. ">") println)
Http do(
get("http://example.com/")
delete("http://example.com/something")
)
Database do(
insert("cats", list("Phil", "gray"))
delete("cats", 12)
)
(Ruby has a similar feature with Object#instance_exec, but its object model is a bit more complicated.)
In effect, this gives you a temporary namespace, which is nice for writing domain specific languages. Is there a technique to achieve a similar effect (a temporary namespace) in Haskell?
For example, something like: (Not necessarily exactly like this, but something with similarly succinct syntax.)
main = do
http $ do
get "http://example.com/"
delete "http://example.com/something"
database $ do
insert "cats" ["Phil", "gray"]
delete "cats" 12
Notice that the two deletes are completely different functions. I'd prefer to avoid writing things like H.delete and D.delete, because that would get messy quick. I realize that this could be avoided by renaming that database version to, for example, deleteFrom, but I don't want to.
|
I am using IPython or the Python shell to interact with matplotlib. I have two DataFrames. Each has an index of months in the 'YYYY-MM' format (these are just strings). The rest of the columns are sums of different values.
One DataFrame contains 2012 data, and the other contains 2013 data. Since it is still 2013, there are nulls for many of the 2013 months.
The graph I want to create just uses one metric at a time, and shows 2013 data as bars, and 2012 data as a line. I want both graphs to be laid on top of each other, and share x- and y-axis. I also want the bars to be centered on each data point.
The nulls in the 2013 data seem to be causing issues.
Here is sample of what I have tried in IPython:
df2012['metric'].plot(color='black')
bar(np.arange(len(df2013.index)), df2013['metric'], align='center')
I have also tried using twinx() and twiny() but also having issues.
|
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
|
Commercial Services ✈ Flight Status API / Flight Tracking API / FlightAware API ✈ Documentation
FlightXML 2.0 Documentation
About
Using the FlightXML API, programs can query the FlightAware live flight information and recent history datasets.
Queries for in-flight aircraft return a set of matching aircraft based on a combination of location, flight or tail number, origin and/or destination airport, aircraft type, and/or a low-to-high range of altitude and/or ground speed, among others. For each matching aircraft, data returned includes the flight or tail number, the aircraft type, origin and destination, time the last position was received, and the longitude, latitude, groundspeed, and altitude of that position. Matching flights' flight tracks can be requested as well.
For airports, FlightXML queries can return a list of scheduled flights, flights that have departed, flights that are enroute to the airport, and flights that have arrived at the airport.
Example Applications
Possible uses of FlightXML include:
Authentication
To access FlightXML 2.0, all requests must include a username and FlightXML Key (don't have one?). This data is transmitted via the "basic" HTTP Authentication standard, which is sent to the FlightXML server as a part of each HTTP request.
The web service libraries available in most programming languages allow you to directly specify a username and password as an argument for the request, so that the authentication is transparent to your application as it makes requests. However, with some libraries it may be necessary to manually encode the "user:key" in base64 and send the result in the "Authorization" header as part of each HTTP request.
If data security is a concern, all FlightXML services are also available over SSL by simply substituting "https" as the protocol for any
Web Services / SOAP / WSDL
The primary protocol recommended for use with FlightXML 2.0 is the "Simple Object Access Protocol" (SOAP). Most modern SOAP implementations support use of "Web Services Description Language" (WSDL) definition file, which greatly simplifies accessing web services.
View:
Although you can read the WSDL and generate SOAP queries manually, it is recommended that you develop your applications using a SOAP library that automatically parses the WSDL and populates your application namespace with the FlightXML functions.
It is strongly suggested that you ensure that your applications cache the WSDL file so that it is not necessary to fetch and parse the WSDL for every request or instance of your application. This will vastly improve the performance and efficiency of your application.
The FlightXML 2.0 WSDL uses the "Document/Literal wrapped" method for encoding SOAP requests and responses. This is a newer method that recent SOAP industry standards dictate should be used instead of the older "RPC/Encoded" method that was used by the FlightXML 1.0 WSDL. Most modern SOAP client libraries fully support this newer method, although some older SOAP libraries are not yet compatible. The SOAP client libraries listed in the examples section have been tested to be compatible.
REST / JSON
FlightXML 2.0 can also be accessed using a light-weight "Representational state transfer" (REST) inspired protocol that returns its responses encoded in "JavaScript Object Notation" (JSON) format. This allows FlightXML to be used in environments in which it is inconvenient or impossible to invoke SOAP services, such as mobile phone applications, web browser applications, or server-side JavaScript environments.
To access any method, simply perform either a GET or POST request to
For example, the following URL is how you might request the current weather at John F. Kennedy airport (KJFK) in New York:
Requests can be returned in "JSONP" format, allowing a web page to load the response in a way that avoids the same-domain security restrictions enforced by some browsers. To do this, simply specify the optional argument "jsonp_callback" with a value that is the name of the JavaScript function that should be invoked with the JSON data.
Pushed Notifications
Although FlightXML functionality is primarily intended to be accessed through a "pull" oriented request model using the SOAP/WSDL or REST/JSON interfaces, you can also opt to receive a "pushed" notification from our server to yours whenever certain flight events occur. Upon receiving a notification, your server-based application is sent basic information about the flight, its current status, and the triggering event. In response, your server-based application can initiate requests to FlightXML using the normal SOAP/WSDL or REST/JSON interfaces to obtain additional details. This can allow your application to intelligently reduce or increase the rate at which it makes other FlightXML requests at various parts of a flight, reducing your costs by avoiding unnecessary API requests during uneventful time periods.
To use pushed notifications, you must first call the "RegisterAlertEndpoint" method once to configure the URL endpoint where your server-based application can receive POST requests via HTTP or HTTPS. Once the URL endpoint has been registered, you can use the "SetAlert" method to define the triggering event conditions for the notifications that you want to receive.
When an event occurs, your URL endpoint will receive a POST request containing a JSON message. Although you can define alerts using either the SOAP/WSDL or REST/JSON interfaces, pushed notifications are always delivered in a JSON format. Delivery of each alert is attempted only once and is made on a best-effort policy. Your URL endpoint must accept the POST request and return a successful response within 5 seconds. It is recommended that your URL endpoint return a "Content-type" of "text/plain", and a short body (less than 32 characters) that acknowledges receipt of the pushed alert. If troubleshooting of alert delivery is required, the body responses for each delivered alert can be later reviewed on the Recently delivered alerts page.
Show example (JSON push notification)...
{
"long_desc": "DAL116 arrived at KATL (Hartsfield-Jackson Intl) at 04:11PM EST from KTPA (Tampa Intl)",
"short_desc": "DAL116 arrived at KATL from KTPA",
"summary": "DAL116 arrived at KATL from KTPA",
"eventcode": "arrival",
"alert_id": 123456,
"flight": {
"ident": "DAL116",
"aircrafttype": "B752",
"origin": "KTPA",
"destination": "KATL",
"filed_ete": "01:15:00",
"route": "ENDED4 CTY HONIE8",
"faFlightID": "DAL116-1318311885-airline-0362",
"filed_altitude": 360,
"filed_airspeed_kts": 465,
"filed_time": 1318532269,
"filed_departuretime": 1318531500,
"estimatedarrivaltime": 1318536216,
"actualarrivaltime": 1318536660,
"actualdeparturetime": 1318532220
}
}
{
"long_desc": "Delta #1752 (DC95) has just filed a flight plan. It is scheduled to depart from Jackson-Evers Intl (KJAN) at 01:05PM CST heading for Hartsfield-Jackson Intl (KATL) for an estimated arrival at 03:34PM EST.",
"short_desc": "DAL1752 (DC95) filed to depart KJAN @ 01:05PM CST for KATL @ ETA 03:34PM EST (MEI LGC3)",
"summary": "DAL1752 filed a flight plan KJAN -> KATL",
"eventcode": "filed",
...rest of sample omitted for brevity...
}
{
"long_desc": "Delta #116 (B752) departed Detroit Metro Wayne Co (KDTW) at 06:44PM UTC enroute to KATL (Hartsfield-Jackson Intl) for an estimated arrival at 08:30PM UTC",
"short_desc": "DAL116 (B752) departed KDTW @ 06:44PM UTC for KATL ETA 08:30PM UTC",
"summary": "DAL116 has departed KDTW for KATL",
"eventcode": "departure",
...rest of sample omitted for brevity...
}
The description of the JSON attributes are as follows:
(view legacy 1.0 documentation instead)
Examples (SOAP / WSDL)
Microsoft .NET
Show example (C#)...
Any Microsoft CLR .NET language should be usable to make requests to FlightXML 2.0, however this example is using C#. The procedure for using other languages may vary slightly. The steps described here use the command-line utilities to generate the WSDL stub and compile, but the steps can be adapted for use within the Visual Studio IDE.
Requirements
Save the following file as test.cs, but substitute your actual username and API key:
using System.Net;
class test {
public static void Main(string[] args)
{
FlightXML2 df = new FlightXML2();
df.Credentials = new NetworkCredential("sampleUser", "abc123abc123abc123abc123abc123");
df.PreAuthenticate = true;
// get the flights currently enroute.
EnrouteStruct r = df.Enroute("KAUS", 10, "", 0);
foreach (EnrouteFlightStruct e in r.enroute) {
System.Console.WriteLine(e.ident);
}
// get the weather.
System.Console.WriteLine(df.Metar("KAUS"));
}
}
Run commands:
wsdl.exe http://flightxml.flightaware.com/soap/FlightXML2/wsdl
csc.exe test.cs FlightXML2.cs
test.exe
PHP
Show example (SoapClient)...
The built-in SoapClient provided in PHP5 supports modern Document/Literal SOAP services, like FlightXML2.
Requirements
Save the following file as testsoap.php, but substitute your actual username and API key:
<?php
$options = array(
'trace' => true,
'exceptions' => 0,
'login' => 'sampleUser',
'password' => 'abc123abc123abc123abc123abc123abc123',
);
$client = new SoapClient('http://flightxml.flightaware.com/soap/FlightXML2/wsdl', $options);
// get the weather.
$params = array("airport" => "KAUS");
$result = $client->Metar($params);
print_r($result);
?>
Show example (nusoap)...
The NuSOAP toolkit for PHP can be used with FlightXML2.
Requirements
Save the following file as testsoap.php, but substitute your actual username and API key:
<?php
require_once( "nusoap/nusoap.php" );
$username = 'sampleUser';
$apiKey = 'abc123abc123abc123abc123abc123abc123';
$baseUri = "http://flightxml.flightaware.com/soap/FlightXML2";
date_default_timezone_set('UTC');
$client = new nusoap_client("$baseUri/wsdl",'wsdl');
$client->setCredentials($username,$apiKey);
if ( $client->getError() ) {
die "Soap Constructor Error:" . $client->getError();
}
// get the weather.
$params = array("airport" => "KAUS");
$result = $client->call( "Metar", $params);
if ($client->fault) { //soap_fault
die "Soap Fault: ". $client->faultcode . "(" . $client->faultstring . ")";
}
elseif ( $client->getError() ) {
die "Soap Error: " . $client->getError();
}
else {
print_r($result);
}
?>
Perl
Show example (SOAP::WSDL)...
The Perl CPAN module SOAP::WSDL is a modern SOAP client that fully supports Document/Literal services.
Requirements
Save the following file as testwsdl.pl, but substitute your actual username and API key:
#!/usr/bin/perl
use strict;
use SOAP::WSDL 2.0;
my $username = "sampleUser";
my $apiKey = "abc123abc123abc123abc123abc123";
my $baseUri = "http://flightxml.flightaware.com/soap/FlightXML2";
sub SOAP::WSDL::Transport::HTTP::get_basic_credentials {
return $username => $apiKey;
}
sub SOAP::Transport::HTTP::Client::get_basic_credentials {
return $username => $apiKey;
}
# Check if the SOAP result is an exception.
sub is_fault ($) {
my $result = shift;
return !defined($result) || ref($result) eq 'SOAP::Fault' || !defined($result->result);
}
# Singleton arrays are changed by SOAP::WSDL into scalars, making you handle either type.
sub coerce_arrayref ($) {
my $val = shift;
my @result = (ref($val) eq 'ARRAY' ? @$val : $val) if defined($val);
return @result;
}
my $soap = SOAP::WSDL->new( wsdl => "$baseUri/wsdl" );
my $enroute = $soap->call('Enroute', EnrouteRequest => {'airport' => "KSMO", 'howMany' => 10, 'filter' => "", 'offset' => 0});
die if is_fault($enroute);
print "Aircraft en route to KSMO:\n";
my @flights = coerce_arrayref($enroute->result->{enroute});
foreach my $flight (@flights) {
print $flight->{'ident'} . " (" . $flight->{'aircrafttype'} . ") \t" .
$flight->{'originName'} . " (" . $flight->{'origin'} . ")\n";
}
Run commands:
Show example (SOAP::Lite)...
The Perl CPAN module SOAP::Lite is an old and well-known SOAP client for Perl, however it is not especially well-suited for modern "Document/Literal" SOAP services. However, it can be used if you are willing to make calls to explicitly declare the types of all function arguments using the SOAP::Data method. The "stubmaker.pl" utility and the SOAP::Lite WSDL support cannot be used.
Requirements
Save the following file as testlite.pl, but substitute your actual username and API key:
#!/usr/bin/perl
use strict;
use SOAP::Lite;
my $username = "sampleUser";
my $apiKey = "abc123abc123abc123abc123abc123";
my $baseUri = "http://flightxml.flightaware.com/soap/FlightXML2";
sub SOAP::Transport::HTTP::Client::get_basic_credentials {
return $username => $apiKey;
}
my $soap = SOAP::Lite->default_ns($baseUri)->proxy("$baseUri/op")->autotype(0);
my $enroute = $soap->call("Enroute",
SOAP::Data->name("airport" => 'KSMO'),
SOAP::Data->name("howMany" => 10),
SOAP::Data->name("filter" => ''),
SOAP::Data->name("offset" => 0)
);
die if !defined($enroute) || $enroute->fault;
print "Aircraft en route to KSMO:\n";
my $flights = $enroute->result->{enroute};
foreach my $flight (@$flights) {
print $flight->{'ident'} . " (" . $flight->{'aircrafttype'} . ") \t" .
$flight->{'originName'} . " (" . $flight->{'origin'} . ")\n";
}
Run commands:
Java
Show example (Apache Axis1)...
Requirements
Save the following file as test.java, but substitute your actual username and API key:
import com.flightaware.flightxml.soap.FlightXML2.*;
class test {
public static void main(String[] args)
{
try {
FlightXML2Locator locator = new FlightXML2Locator();
FlightXML2Soap df = locator.getFlightXML2Soap();
FlightXML2SoapStub stub = (FlightXML2SoapStub)df;
stub.setUsername("sampleUser");
stub.setPassword("abc123abc123abc123abc123");
// Get the list of enroute aircraft.
EnrouteStruct r = df.enroute(new EnrouteRequest("KAUS", 10, "", 0)).getEnrouteResult();
for (EnrouteFlightStruct e: r.getEnroute()) {
System.out.println(e.getIdent());
}
// Get the weather.
System.out.println(df.metar(new MetarRequest("KAUS")).getMetarResult());
} catch (javax.xml.rpc.ServiceException x) {
System.err.println(x);
} catch (java.rmi.RemoteException x) {
System.err.println(x);
}
}
}
Run commands (Win32):
set CLASSPATH=axis-1_4\lib\axis-ant.jar;axis-1_4\lib\axis.jar;axis-1_4\lib\commons-discovery-0.2.jar;
axis-1_4\lib\commons-logging-1.0.4.jar;axis-1_4\lib\jaxrpc.jar;axis-1_4\lib\log4j-1.2.8.jar;
axis-1_4\lib\saaj.jar;axis-1_4\lib\wsdl4j-1.5.1.jar;.
wget -O wsdl2.xml http://flightxml.flightaware.com/soap/FlightXML2/wsdl
java org.apache.axis2.wsdl.WSDL2Java wsdl2.xml
javac test.java
java test
Show example (Apache Axis2)...
Requirements
Save the following file as test2.java, but substitute your actual username and API key:
import com.flightaware.flightxml.soap.flightxml2.*;
import org.apache.axis2.transport.http.*;
class test2 {
public static void main(String[] args)
{
try {
HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
auth.setUsername("sampleUser");
auth.setPassword("abc123abc123abc123abc123");
FlightXML2Stub stub = new FlightXML2Stub();
stub._getServiceClient().getOptions().setProperty(HTTPConstants.CHUNKED, false);
stub._getServiceClient().getOptions().setProperty(HTTPConstants.AUTHENTICATE, auth);
// Get the list of enroute aircraft.
FlightXML2Stub.EnrouteRequest req1 = new FlightXML2Stub.EnrouteRequest();
req1.setHowMany(10);
req1.setAirport("KAUS");
req1.setFilter("");
req1.setOffset(0);
FlightXML2Stub.EnrouteRequestE req1e = new FlightXML2Stub.EnrouteRequestE();
req1e.setEnrouteRequest(req1);
for (FlightXML2Stub.EnrouteFlightStruct e:
stub.enroute(req1e).getEnrouteResults().getEnrouteResult().getEnroute()) {
System.out.println(e.getIdent() + " (" + e.getAircrafttype() + ") \t" +
e.getOriginName() + " (" + e.getOrigin() + ")");
}
// Get the weather.
FlightXML2Stub.MetarRequest req2 = new FlightXML2Stub.MetarRequest();
req2.setAirport("KAUS");
FlightXML2Stub.MetarRequestE req2e = new FlightXML2Stub.MetarRequestE();
req2e.setMetarRequest(req2);
System.out.println(stub.metar(req2e).getMetarResults().getMetarResult());
} catch (java.rmi.RemoteException x) {
System.err.println(x);
}
}
}
Run commands (UNIX):
export CLASSPATH=$(echo . axis2-1.5.1/lib/*.jar | tr ' ' ':')
./axis2-1.5.1/bin/wsdl2java.sh -S . -uri http://flightxml.flightaware.com/soap/FlightXML2/wsdl
javac test2.java
java test2
Tcl
Show example (tclws)...
Requirements
Save the following file as test.tcl, but substitute your actual username and API key:
#!/bin/env tclsh8.5
package require WS::Client 1.3.0
package require base64
# uncomment these lines for debugging output
#::log::lvChannelForall stderr
#foreach lev [::log::levels] { ::log::lvSuppress $lev 0 }
set username "sampleUser"
set apiKey "abc123abc123abc123abc123abc123"
set baseUri "http://flightxml.flightaware.com/soap/FlightXML2"
set wsdl [::WS::Client::GetAndParseWsdl "$baseUri/wsdl"]
set apiname [::WS::Client::LoadParsedWsdl $wsdl]
set authheader [list Authorization "Basic [::base64::encode $username:$apiKey]"]
proc get_weather {airport} {
global apiname authheader
array set result [::WS::Client::DoCall $apiname Metar [list airport $airport] $authheader]
puts "Weather for $airport:"
puts $result(MetarResult)
}
proc get_flights {airport} {
global apiname authheader
array set result [::WS::Client::DoCall $apiname Enroute [list airport $airport howMany "10" fiter "" offset "0"] $authheader]
array set flights $result(EnrouteResult)
puts "Aircraft en route to $airport:"
foreach flightdata $flights(enroute) {
array unset flight
array set flight $flightdata
puts "$flight(ident) ($flight(aircrafttype)) $flight(originName) ($flight(origin))"
}
}
get_weather "KSMO"
get_flights "KSMO"
Run commands:
Python
Show example (soapPy)...
Requirements
Save the following file as test.py, but substitute your actual username and API key:
#!/usr/bin/env python
from SOAPpy import Config, HTTPTransport, SOAPAddress, WSDL
username = 'sampleuser'
apiKey = 'abc123abc123abc123abc123abc123abc123'
wsdlFile = 'http://flightxml.flightaware.com/soap/FlightXML2'
# This is a custom HTTP transport that allows Basic Authentication.
class myHTTPTransport(HTTPTransport):
username = None
passwd = None
@classmethod
def setAuthentication(cls,u,p):
cls.username = u
cls.passwd = p
def call(self, addr, data, namespace, soapaction=None, encoding=None,
http_proxy=None, config=Config):
if not isinstance(addr, SOAPAddress):
addr=SOAPAddress(addr, config)
if self.username != None:
addr.user = self.username+":"+self.passwd
return HTTPTransport.call(self, addr, data, namespace, soapaction,
encoding, http_proxy, config)
# Make a FlightXML server request.
myHTTPTransport.setAuthentication(username, apiKey)
DF = WSDL.Proxy(wsdlFile, transport=myHTTPTransport)
enroute = DF.Enroute('KSMO',10,'',0)
flights = enroute['enroute']
print "Aircraft en route to KSMO:"
for flight in flights:
print "%s (%s) \t%s (%s)" % ( flight['ident'], flight['aircrafttype'],
flight['originName'], flight['origin'])
Run commands:
Show example (suds)...
Requirements
Save the following file as test.py, but substitute your actual username and API key:
#!/usr/bin/python
import sys
from suds import null, WebFault
from suds.client import Client
import logging
username = 'sampleUser'
apiKey = 'abc123abc123abc123abc123abc123abc123'
url = 'http://flightxml.flightaware.com/soap/FlightXML2/wsdl'
logging.basicConfig(level=logging.INFO)
api = Client(url, username=username, password=apiKey)
#print api
# Get the weather
result = api.service.Metar('KAUS')
print result
# Get the flights enroute
result = api.service.Enroute('KSMO', 10, '', 0)
flights = result['enroute']
print "Aircraft en route to KSMO:"
for flight in flights:
print "%s (%s) \t%s (%s)" % ( flight['ident'], flight['aircrafttype'],
flight['originName'], flight['origin'])
Run commands:
Ruby
Show example (soap4r)...
Requirements
Save the following file as test.rb, but substitute your actual username and API key:
#!/usr/bin/env ruby
require 'FlightXML2Driver.rb'
username = 'sampleuser'
apiKey = 'abc123abc123abc123abc123abc123abc123'
$api = FlightXML2Soap.new(username, apiKey)
result = $api.enroute(EnrouteRequest.new('KSMO',10,'',0))
flights = result.enrouteResult.enroute
print "Aircraft en route to KSMO:\n"
flights.each { |flight|
print "#{flight.ident} (#{flight.aircrafttype}) \t#{flight.originName} (#{flight.origin})\n"
}
Run commands:
Show example (savon)...
Requirements
Save the following file as test.rb, but substitute your actual username and API key:
#!/usr/bin/env ruby
require 'rubygems'
require 'savon'
SOAP_URL = 'http://flightxml.flightaware.com/soap/FlightXML2/wsdl'
USERNAME = 'sampleuser'
API_KEY = 'abc123abc123abc123abc123abc123abc123'
client = Savon::Client.new do
wsdl.document = SOAP_URL
http.auth.basic USERNAME, API_KEY
end
result = client.request(:enroute) do
soap.body = {
:airport => 'KSMO',
:how_many => 10,
:filter => '',
:offset => 0
}
end
flights = result.to_hash[:enroute_results][:enroute_result][:enroute]
print "Aircraft en route to KSMO:\n"
flights.each { |flight|
print "#{flight[:ident]} (#{flight[:aircrafttype]}) \t#{flight[:origin_name]} (#{flight[:origin]})\n"
}
Run commands:
ColdFusion
Show example (cfm)...
Requirements
Save the following file as test.cfm, but substitute your actual username and API key:
<cfscript>
stAuth = structNew();
stAuth.username = "sampleuser";
stAuth.password = "abc123abc123abc123abc123abc123abc123";
ws = createObject("webservice", "http://flightxml.flightaware.com/soap/FlightXML2/wsdl", stAuth);
stEnroute = structNew();
stEnroute.airport = "KSFO";
stEnroute.howMany = 15;
stEnroute.filter = "";
stEnroute.offset = 0;
aEnrouteStruct = ws.Enroute(stEnroute);
</cfscript>
<cfset EnrouteFlights = aEnrouteStruct.getEnrouteResult().getEnroute()>
<cfloop from="1" to="#ArrayLen(EnrouteFlights)#" index="i">
<cfset dtime = DateAdd("s",EnrouteFlights[i].actualdeparturetime,DateConvert("utc2Local", "January 1 1970 00:00"))>
<cfoutput>#EnrouteFlights[i].ident# = #EnrouteFlights[i].aircrafttype# departed at #dtime#<br></cfoutput>
</cfloop>
Examples (REST / JSON)
JavaScript
Show example (jQuery)...
This example is a static HTML page using JavaScript and jQuery to access FlightXML2 over its JSON interface. We recommend that this technique be only used in protected Intranet environment, since embedding your FlightXML API key in public web pages will allow other users to copy your key and make unauthorized use against your account.
Requirements
Save the following file as test.html, but substitute your actual username and API key:
<html>
<head>
<!--
This example uses:
* the FlightXML2 FlightInfoEx and DecodeFlightRoute functions over REST:
http://flightaware.com/commercial/flightxml/
* Google Maps API:
http://code.google.com/apis/visualization/documentation/gallery/map.html
* jQuery, hosted by Google API
-->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
var fxml_url = 'http://YOUR_USERNAME:YOUR_API_KEY@flightxml.flightaware.com/json/FlightXML2/';
google.load("visualization", "1", {packages:["map"]});
// When the button is clicked, fetch the details about the entered flight ident.
$(document).ready(function() {
$('#go_button').click(function() {
$.ajax({
type: 'GET',
url: fxml_url + 'FlightInfoEx',
data: { 'ident': $('#ident_text').val(), 'howMany': 1, 'offset': 0 },
success : function(result) {
// display some textual details about the flight.
var flight = result.FlightInfoExResult.flights[0];
$('#results').html('Flight ' + flight.ident + ' from ' + flight.origin + ' to ' + flight.destination);
// display the route on a map.
fetchAndRenderRoute(flight.faFlightID);
},
error: function(data, text) { alert('Failed to fetch flight: ' + data); },
dataType: 'jsonp',
jsonp: 'jsonp_callback',
xhrFields: { withCredentials: true }
});
});
});
// Fetch the planned route for a specified flight_id.
function fetchAndRenderRoute(flight_id) {
$.ajax({
type: 'GET',
url: fxml_url + 'DecodeFlightRoute',
data: { 'faFlightID': flight_id },
success : function(result) {
// Initialize a data table using the Google API.
var table = new google.visualization.DataTable();
table.addColumn('number', 'Lat');
table.addColumn('number', 'Lon');
table.addColumn('string', 'Name');
// Insert all of the points into the data table.
var points = result.DecodeFlightRouteResult.data;
table.addRows(points.length);
for (rowid = 0; rowid < points.length; rowid++) {
table.setCell(rowid, 0, points[rowid].latitude);
table.setCell(rowid, 1, points[rowid].longitude);
table.setCell(rowid, 2, points[rowid].name + ' (' + points[rowid].type + ')' );
}
// Render the data table into a map using Google Maps API.
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(table, {showTip: true, showLine: true, lineWidth: 3, lineColor: '#009900'});
},
error: function(data, text) { alert('Failed to decode route: ' + data); },
dataType: 'jsonp',
jsonp: 'jsonp_callback',
xhrFields: { withCredentials: true }
});
}
</script>
</head>
<body>
<form onsubmit="return false;">
<p>Enter a flight ident to track:
<input type="text" name="ident" id="ident_text" value="COA423" />
<input type="submit" id="go_button" value="Go" />
</p>
</form>
<div id="results"></div>
<div id="map_div" style="width: 400px; height: 300px"></div>
</body>
</html>
Show example (Node.js)...
This example is a Node.JS console application written in Javascript that accesses FlightXML2 over its JSON interface.
Requirements
Save the following file as test.js, but substitute your actual username and API key:
/*
* This requires: restler
* To install, type 'npm install restler'
* Tested with node.js v0.6.14
*/
var util = require('util');
var restclient = require('restler');
var fxml_url = 'http://flightxml.flightaware.com/json/FlightXML2/';
var username = 'YOUR_USERNAME';
var apiKey = 'YOUR_APIKEY';
restclient.get(fxml_url + 'MetarEx', {
username: username,
password: apiKey,
query: {airport: 'KAUS', howMany: 1}
}).on('success', function(result, response) {
// util.puts(util.inspect(result, true, null));
var entry = result.MetarExResult.metar[0];
util.puts('The temperature at ' + entry.airport + ' is ' + entry.temp_air + 'C');
});
restclient.get(fxml_url + 'Enroute', {
username: username,
password: apiKey,
query: {airport: 'KIAH', howMany: 10, filter: '', offset: 0}
}).on('success', function(result, response) {
util.puts('Aircraft en route to KIAH:');
//util.puts(util.inspect(result, true, null));
var flights = result.EnrouteResult.enroute;
for (i in flights) {
var flight = flights[i];
//util.puts(util.inspect(flight));
util.puts(flight.ident + ' (' + flight.aircrafttype + ')\t' +
flight.originName + ' (' + flight.origin + ')');
}
});
Run commands:
Microsoft classic ASP
Show example (classic ASP)...
This example demonstrates how to access FlightXML2 over its JSON interface using classic ASP.
Requirements
Save the following file as test.asp, but substitute your actual username and API key:
<script language="javascript" runat="server" src="json2.js"></script>
<%
Dim postData, httpRequest, jsonResponse
postData = "airport=KAUS"
postData = postData & "&howMany=10"
postData = postData & "&filter=airline"
Set httpRequest = Server.CreateObject("MSXML2.ServerXMLHTTP")
httpRequest.Open "POST", "http://flightxml.flightaware.com/json/FlightXML2/Arrived", False, "YOUR_USERNAME", "YOUR_APIKEY"
httpRequest.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
httpRequest.Send postData
If httpRequest.status = 200 Then
Set jsonResponse = JSON.parse(httpRequest.responseText)
For Each flight In jsonResponse.ArrivedResult.arrivals
Response.Write("Flight " & flight.ident & " is arriving from " & flight.origin & "<br>")
Next
Else
Response.Write("Error occurred")
End If
Set httpRequest = Nothing
%>
Objective C
Show example (Objective C)...
This example demonstrates how to access FlightXML2 over its JSON interface using Objective C on Mac OS X.
Requirements
Save the following file as test.m, but substitute your actual username and API key:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSString* path = @"http://YOUR_USERNAME:YOUR_APIKEY@flightxml.flightaware.com/json/FlightXML2/Enroute?airport=KSMO&filter=''&howMany=10&offset=0";
NSMutableURLRequest* _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
[_request setHTTPMethod:@"GET"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData* _connectionData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];
if(nil != error)
{
NSLog(@"Error: %@", error);
}
else
{
NSMutableDictionary* json = nil;
if(nil != _connectionData)
{
json = [NSJSONSerialization JSONObjectWithData:_connectionData options:NSJSONReadingMutableContainers error:&error];
}
if (error || !json)
{
NSLog(@"Could not parse loaded json with error:%@", error);
}
else
{
NSMutableDictionary *routeRes;
routeRes = [json objectForKey:@"EnrouteResult"];
NSMutableArray *res;
res = [routeRes objectForKey:@"enroute"];
for(NSMutableDictionary *flight in res)
{
NSLog(@"ident is %@, aircrafttype is %@, originName is %@, origin is %@", [flight objectForKey:@"ident"], [flight objectForKey:@"aircrafttype"], [flight objectForKey:@"originName"], [flight objectForKey:@"origin"]);
}
}
_connectionData = nil;
}
}
return 0;
}
Ruby
Show example (Ruby)...
Requirements
Save the following file as test.rb, but substitute your actual username and API key:
#!/usr/bin/env ruby
require './FlightXML2RESTDriver.rb'
require './FlightXML2Rest.rb'
username = 'YourUserName'
apiKey = 'YourAPIKey'
# This provides the basis for all future calls to the API
test = FlightXML2REST.new(username, apiKey)
# Enroute
print "Aircraft en route to KSMO:\n"
result = test.Enroute(EnrouteRequest.new('KSMO', 'ga', 15, 0 ))
pp result.enrouteResult
Run commands:
Changelog
The following list summarizes the functional changes between FlightXML 1.0 and FlightXML 2.0 to date:
|
Django Celery, ImportError: Import by filename is not supported
Asked by Thomas Grainger on 10/20/2012 at 4:02 PM
When I try to run my celery workers for my django application, I get an import error.
As far as I can tell it's an import in kombu.utils failing
What follows is a rather large stack-trace:
$ ./manage.py celery worker --loglevel=info
Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/djcelery/management/commands/celery.py", line 22, in run_from_argv
["%s %s" % (argv[0], argv[1])] + argv[2:])
File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 890, in execute_from_commandline
super(CeleryCommand, self).execute_from_commandline(argv)))
File "/usr/local/lib/python2.7/dist-packages/celery/bin/base.py", line 179, in execute_from_commandline
return self.handle_argv(prog_name, argv[1:])
File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 882, in handle_argv
return self.execute(command, argv)
File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 857, in execute
return cls(app=self.app).run_from_argv(self.prog_name, argv)
File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 142, in run_from_argv
return self(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 112, in __call__
ret = self.run(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 214, in run
return self.target.run(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/celery/bin/celeryd.py", line 153, in run
return self.app.Worker(**kwargs).run()
File "/usr/local/lib/python2.7/dist-packages/celery/apps/worker.py", line 176, in run
print(str(self.colored.cyan(' \n', self.startup_info())) +
File "/usr/local/lib/python2.7/dist-packages/celery/apps/worker.py", line 246, in startup_info
'conninfo': self.app.connection().as_uri(),
File "/usr/local/lib/python2.7/dist-packages/kombu/connection.py", line 446, in as_uri
fields = self.info()
File "/usr/local/lib/python2.7/dist-packages/kombu/connection.py", line 435, in info
return OrderedDict(self._info())
File "/usr/local/lib/python2.7/dist-packages/kombu/connection.py", line 414, in _info
D = self.transport.default_connection_params
File "/usr/local/lib/python2.7/dist-packages/kombu/connection.py", line 637, in transport
self._transport = self.create_transport()
File "/usr/local/lib/python2.7/dist-packages/kombu/connection.py", line 395, in create_transport
return self.get_transport_cls()(client=self)
File "/usr/local/lib/python2.7/dist-packages/kombu/connection.py", line 402, in get_transport_cls
transport_cls = get_transport_cls(transport_cls)
File "/usr/local/lib/python2.7/dist-packages/kombu/transport/__init__.py", line 104, in get_transport_cls
_transport_cache[transport] = resolve_transport(transport)
File "/usr/local/lib/python2.7/dist-packages/kombu/transport/__init__.py", line 88, in resolve_transport
return symbol_by_name(transport)
File "/usr/local/lib/python2.7/dist-packages/kombu/utils/__init__.py", line 81, in symbol_by_name
module = imp(module_name, package=package, **kwargs)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: Import by filename is not supported.
Responses
No responses yet. Be the first one!
[Some content on this page is from Stackoverflow]
|
All this is quite easily done with standard Python, but for "excel" (xls,or xlsx) files -- you'd have to install a third party library for that. However, if you need just a 2D table that cna open up on a spreadsheed you can use Comma Separated Values (CSV) files - these are comaptible with Excel and other spreadsheet software, and comes integrated in Python.
As for searching a string inside a file, it is straightforward. You may not even need regular expressions for most things. What information do you want along with the string?
Also, the "os" module onthse standardlib has some functions to list all files in a directory, or in a directory tree. The most straightforward is os.listdir(path)
String methods like "count" and "find" can be used beyond "in" to locate the string in a file, or count the number of ocurrences.
And finally, the "CSV" module can write a properly formated file to read in ay spreadsheet.
Along the away, you may abuse python's buit-in list objects as an easy way to manipulate data sets around.
Here is a sample programa that counts strings given in the command line found in files in a given directory,, and assembles a .CSV table with them:
# -*- coding: utf-8 -*-
import csv
import sys, os
output_name = "count.csv"
def find_in_file(path, string_list):
count = []
file_ = open(path)
data = file_.read()
file_.close()
for string in string_list:
count.append(data.count(string))
return count
def main():
if len(sys.argv) < 3:
print "Use %s directory_path <string1>[ string2 [...]])\n" % __package__
sys.exit(1)
target_dir = sys.argv[1]
string_list = sys.argv[2:]
csv_file = open(output_name, "wt")
writer = csv.writer(csv_file)
header = ["Filename"] + string_list
writer.writerow(header)
for filename in os.listdir(target_dir):
path = os.path.join(target_dir, filename)
if not os.path.isfile(path):
continue
line = [filename] + find_in_file(path, string_list)
writer.writerow(line)
csv_file.close()
if __name__=="__main__":
main()
|
I know when using Groovy closures, I can change the delegate on the closure so function calls made within the closure could be defined externally.
Can I do something similar in Python?
Specifically, if you take the following code:
def configure():
build()
def wrap(function):
def build():
print 'build'
function()
wrap(configure)
I'd like it to print 'build' (only making changes to wrap()).
Some notes:
I don't want to pass functions into configure() since there may be a large number of functions that can be called by configure().
I also don't want to define those globally, because, once again, there may be a large number of functions that can be called by configure() and I don't want to pollute the global namespace.
|
iheartquotes provides an interface for easily pulling a random quote from a database of Unix fortune files. If all you want is the data then you should go find the fortune files (try freshmeat). If what you want is to easily put a dynamic quote on your webpage or in your login script then read on.
Put this in your .bash_profile or other login startup script. This will retrieve a random fortune from the iheartquotes server or quickly timeout if you're not online. OSX users will probably want to substitute 'curl --max-time 3' for the wget command.
alias getfortune='wget --timeout=3 -O - -q'
alias fortune='getfortune http://www.iheartquotes.com/api/v1/random'
alias myfortune='getfortune http://www.iheartquotes.com/api/v1/random?source=joel_on_software+paul_graham+prog_style
myfortune
Cut and paste this HTML into your website. There's an example of what it looks like on my blog.
<iframe width="230"
height="165"
frameborder="0"
scrolling="no"
src="http://iheartquotes.com/api/v1/random?format=html&max_lines=4&max_characters=320&width=225&height=165">
<a href="http://iheartquotes.com/fortune/random">Random Quote</a>
</iframe>
I put this code in the sidebar of my blog.
The API has a single REST method. Call the URI below to access the API and pass in any of the options as query string parameters.
http://www.iheartquotes.com/api/v1/random
format: return the result 'text', 'html', or 'json' format. The default is text.
max_lines: maximum number of lines in the quote.
min_lines: minimum number of lines in the quote.
max_characters: maximum number of characters in the quote.
min_characters: minimum number of characters in the quote.
source: pulls quotes from one of the sources listed. Multiple sources should be space or "+" separated, ex: calvin+xfiles
show_permalink: show the quote's permalink at the bottom of the text by default. Turn this off with "false" or "0".
show_source: show the quote's source at the bottom of the text by default. Turn this off with "false" or "0".
font_family:Render the text in the specified font-family.
font_color: Render the text in the specified font color.
width: The width of the box to render the quote in.
height: The height of the box to render the quote in.
|
I am trying to create a function to calculate the moving average on a set of data. This is the function:
def averaged_rel_track(navg, rel_values, nb, zeroindex):
#function to average the relative track values for each blade. This is
#dependant on the number values specified by the user to average over in a
#rolling average
for blade in range(0,int(nb)):
av_values=[]
rel_blade=rel_values[:,blade]
for rev in range(0,len(rel_blade)):
section=rel_blade[rev-int(navg)+1:rev]
av_value=np.mean(section)
av_values.append(av_value)
print av_values
however I would like to add a check to it and I'm strugging witht the best way to implement this...If the number of averages (navg) in the moving average is say 24 the average is taken of the 23 values before the specified element and the element. However, if one of those 24 values is a zero I want the average for that specified element to be zero. I tried:
def averaged_rel_track(navg, rel_values, nb, zeroindex):
#function to average the relative track values for each blade. This is
#dependant on the number values specified by the user to average over in a
#rolling average
for blade in range(0,int(nb)):
av_values=[]
rel_blade=rel_values[:,blade]
for rev in range(0,len(rel_blade)):
section=rel_blade[rev-int(navg)+1:rev]
av_value=np.mean(section)
zero_test= np.where(np.any(section==0))
print zero_test
if len(zero_test)==0:
av_value=None
av_values.append(av_value)
print av_values
However the length of zero_test is always 1?
Can anyone think of a way to correct this method or a different method altogether?
Cheers
|
I'm trying to use association proxy for tags, in a very similar scenario to the example in the docs. Here is a subset of my schema (it's a blog), using declarative:
class Tag(Base):
__tablename__ = 'tags'
id = Column(Integer, primary_key=True)
tag = Column(Unicode(255), unique=True, nullable=False)
class EntryTag(Base):
__tablename__ = 'entrytags'
entry_id = Column(Integer, ForeignKey('entries.id'), key='entry', primary_key=True)
tag_id = Column(Integer, ForeignKey('tags.id'), key='tag', primary_key=True)
class Entry(Base):
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
subject = Column(Unicode(255), nullable=False)
# some other fields here
_tags = relation('Tag', backref='entries', secondary=EntryTag.__table__)
tags = association_proxy('_tags','tag')
Here's how I'm trying to use it:
>>> e = db.query(Entry).first()
>>> e.tags
[u'foo']
>>> e.tags = [u'foo', u'bar'] # really this is from a comma-separated input
db.commit()
Traceback (most recent call last):
[...]
sqlalchemy.exc.IntegrityError: (IntegrityError) duplicate key value violates unique constraint "tags_tag_key"
'INSERT INTO tags (id, tag) VALUES (%(id)s, %(tag)s)' {'tag': 'bar', 'id': 11L}
>>> map(lambda t:(t.id,t.tag), db.query(Tag).all())
[(1, u'foo'), (2, u'bar'), (3, u'baz')]
The tag u'bar' already existed with id 2; why didn't SQLAlchemy just attach that one instead of trying to create it? Is my schema wrong somehow?
|
Here is a screenshot of my kivy app. I am trying to get the TextInput in the bottom left to be centered in the BoxLayout which it is in, and I don't want it to be the same size as the layout, I want it to be much smaller. This BoxLayout in question resides in the bottom half of the screen. I have tried setting the TextInputs propertycenter:self.parent.center but this doesn't work. As you can see, I have printed the center coords from the BoxLayout into the TextInput using that very line, self.parent.center, with the correct result. Yet, setting the TextInputs center or position to these coords is not centering it, it doesn't move... what am I doing wrong?
py file:
import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
class TimeTabler(Widget):
pass
class TimerApp(App):
def build(self):
return TimeTabler()
if __name__ == "__main__":
TimerApp().run()
*kv file:*
#:kivy 1.0
BoxLayout:
orientation: 'vertical'
size: root.size
BoxLayout:
orientation: 'vertical'
Label:
text: 'TimeTabler'
BoxLayout:
TextInput:
text: '%s' % (self.parent.center) # why does this work here
size_hint: None, None
width: sp(200)
height: sp(30)
center: self.parent.center # but not here
|
To understand what yield does, you must understand what generators are. And before generators come iterables.
Iterables
When you create a list, you can read its items one by one, and it's called iteration:
>>> mylist = [1, 2, 3]
>>> for i in mylist:
... print(i)
1
2
3
Mylist is an iterable. When you use a list comprehension, you create a list, and so an iterable:
>>> mylist = [x*x for x in range(3)]
>>> for i in mylist:
... print(i)
0
1
4
Everything you can use "for... in..." on is an iterable: lists, strings, files...These iterables are handy because you can read them as much as you wish, but you store all the values in memory and it's not always what you want when you have a lot of values.
Generators
Generators are iterators, but you can only iterate over them once. It's because they do not store all the values in memory, they generate the values on the fly:
>>> mygenerator = (x*x for x in range(3))
>>> for i in mygenerator:
... print(i)
0
1
4
It is just the same except you used () instead of []. BUT, you can not perform for i in mygenerator a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end calculating 4, one by one.
Yield
Yield is a keyword that is used like return, except the function will return a generator.
>>> def createGenerator():
... mylist = range(3)
... for i in mylist:
... yield i*i
...
>>> mygenerator = createGenerator() # create a generator
>>> print(mygenerator) # mygenerator is an object!
<generator object createGenerator at 0xb7555c34>
>>> for i in mygenerator:
... print(i)
0
1
4
Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once.
To master yield, you must understand that when you call the function, the code you have written in the function body does not run. The function only returns the generator object, this is a bit tricky :-)
Then, your code will be run each time the for uses the generator.
Now the hard part:
The first time the for calls the generator object created from your function, it will run the code in your function from the beginning until it hits yield, then it'll return the first value of the loop. Then, each other call will run the loop you have written in the function one more time, and return the next value, until there is no value to return.
The generator is considered empty once the function runs but does not hit yield anymore. It can be because the loop had come to an end, or because you do not satisfy a "if/else" anymore.
Your code explained
Generator:
# Here you create the method of the node object that will return the generator
def node._get_child_candidates(self, distance, min_dist, max_dist):
# Here is the code that will be called each time you use the generator object:
# If there is still a child of the node object on its left
# AND if distance is ok, return the next child
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
# If there is still a child of the node object on its right
# AND if distance is ok, return the next child
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
# If the function arrives here, the generator will be considered empty
# there is no more than two values: the left and the right children
Caller:
# Create an empty list and a list with the current object reference
result, candidates = list(), [self]
# Loop on candidates (they contain only one element at the beginning)
while candidates:
# Get the last candidate and remove it from the list
node = candidates.pop()
# Get the distance between obj and the candidate
distance = node._get_dist(obj)
# If distance is ok, then you can fill the result
if distance <= max_dist and distance >= min_dist:
result.extend(node._values)
# Add the children of the candidate in the candidates list
# so the loop will keep running until it will have looked
# at all the children of the children of the children, etc. of the candidate
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result
This code contains several smart parts:
The loop iterates on a list but the list expands while the loop is being iterated :-) It's a concise way to go through all these nested data even if it's a bit dangerous since you can end up with an infinite loop. In this case, candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) exhausts all the values of the generator, but while keeps creating new generator objects which will produce different values from the previous ones since it's not applied on the same node.
The extend() method is a list object method that expects an iterable and adds its values to the list.
Usually we pass a list to it:
>>> a = [1, 2]
>>> b = [3, 4]
>>> a.extend(b)
>>> print(a)
[1, 2, 3, 4]
But in your code it gets a generator, which is good because:
You don't need to read the values twice.
You can have a lot of children and you don't want them all stored in memory.
And it works because Python does not care if the argument of a method is a list or not. Python expects iterables so it will work with strings, lists, tuples and generators! This is called duck typing and is one of the reason why Python is so cool. But this is another story, for another question...
You can stop here, or read a little bit to see a advanced use of generator:
Controlling a generator exhaustion
>>> class Bank(): # let's create a bank, building ATMs
... crisis = False
... def create_atm(self):
... while not self.crisis:
... yield "$100"
>>> hsbc = Bank() # when everything's ok the ATM gives you as much as you want
>>> corner_street_atm = hsbc.create_atm()
>>> print(corner_street_atm.next())
$100
>>> print(corner_street_atm.next())
$100
>>> print([corner_street_atm.next() for cash in range(5)])
['$100', '$100', '$100', '$100', '$100']
>>> hsbc.crisis = True # crisis is coming, no more money!
>>> print(corner_street_atm.next())
<type 'exceptions.StopIteration'>
>>> wall_street_atm = hsbc.create_atm() # it's even true for new ATMs
>>> print(wall_street_atm.next())
<type 'exceptions.StopIteration'>
>>> hsbc.crisis = False # trouble is, even post-crisis the ATM remains empty
>>> print(corner_street_atm.next())
<type 'exceptions.StopIteration'>
>>> brand_new_atm = hsbc.create_atm() # build a new one to get back in business
>>> for cash in brand_new_atm:
... print cash
$100
$100
$100
$100
$100
$100
$100
$100
$100
...
It can be useful for various things like controlling access to a resource.
Itertools, your best friend
The itertools module contains special functions to manipulate iterables. Ever wish to duplicate a generator?Chain two generators? Group values in a nested list with a one liner? Map / Zip without creating another list?
Then just import itertools.
An example? Let's see the possible orders of arrival for a 4 horse race:
>>> horses = [1, 2, 3, 4]
>>> races = itertools.permutations(horses)
>>> print(races)
<itertools.permutations object at 0xb754f1dc>
>>> print(list(itertools.permutations(horses)))
[(1, 2, 3, 4),
(1, 2, 4, 3),
(1, 3, 2, 4),
(1, 3, 4, 2),
(1, 4, 2, 3),
(1, 4, 3, 2),
(2, 1, 3, 4),
(2, 1, 4, 3),
(2, 3, 1, 4),
(2, 3, 4, 1),
(2, 4, 1, 3),
(2, 4, 3, 1),
(3, 1, 2, 4),
(3, 1, 4, 2),
(3, 2, 1, 4),
(3, 2, 4, 1),
(3, 4, 1, 2),
(3, 4, 2, 1),
(4, 1, 2, 3),
(4, 1, 3, 2),
(4, 2, 1, 3),
(4, 2, 3, 1),
(4, 3, 1, 2),
(4, 3, 2, 1)]
Understanding the inner mechanisms of iteration
Iteration is a process implying iterables (implementing the __iter__() method) and iterators (implementing the __next__() method).Iterables are any objects you can get an iterator from. Iterators are objects that let you iterate on iterables.
More about it in this article about how does the for loop work.
|
import urllib
import cookielib
import mechanize
url = "http://hattrick.org/World/Transfers/"
cookie = cookielib.CookieJar()
browser = mechanize.Browser()
browser.set_cookiejar(cookie)
browser.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
browser.open(url)
browser.select_form(name="aspnetForm")
browser.form['ctl00$ctl00$CPContent$ucSubMenu$ucLogin$txtUserName'] = 'login8192'
browser.form['ctl00$ctl00$CPContent$ucSubMenu$ucLogin$txtPassword'] = '8192login'
response = browser.submit()
browser.select_form(name="aspnetForm")
#<select name="ctl00$ctl00$CPContent$CPMain$ddlSkill1" id="ctl00_ctl00_CPContent_CPMain_ddlSkill1" class="skillDropDown" style="width:120px;">
#control=browser.form.find_control("ctl00$ctl00$CPContent$CPMain$ddlSkill1")# <--- here is the problem
#<select name="ctl00$ctl00$CPContent$CPMain$ddlSkill1Min" id="ctl00_ctl00_CPContent_CPMain_ddlSkill1Min"
#onchange="primaryMinSelected('ctl00_ctl00_CPContent_CPMain_ddlSkill1Min', 'ctl00_ctl00_CPContent_CPMain_ddlSkill1Max');"
#onkeyup="primaryMinSelected('ctl00_ctl00_CPContent_CPMain_ddlSkill1Min', 'ctl00_ctl00_CPContent_CPMain_ddlSkill1Max');" style="width:120px;">
control=browser.form.find_control("ctl00$ctl00$CPContent$CPMain$ddlSkill1Min")
#this works fine
response=browser.submit()
Problem is that:
control=browser.form.find_control("ctl00$ctl00$CPContent$CPMain$ddlSkill1")
cannot be find.
---------------------------Error---------------------------ControlNotFoundError: no control matching name 'ctl00$ctl00$CPContent$CPMain$ddlSkill1'---------------------------OK ---------------------------
|
We have a object method that returns a city/state tuple, i.e. ('Boston', 'MA'). Under some valid circumstances, there is no valid city/state to return. Stylistically, does it make more sense to return None, or a two element tuple containing (None, None) in that case?
I would return
It is also easier to test:
result = getCity()
if result:
# do something
I would only return
By only returning one value in exceptional circumstances, you risk breaking the tuple unpacking idiom. Some of your callers might issue:
city, state = getCityStateTuple("something")
In that case, returning
So, I personally would return
As others have noted, a tuple with items in it does not test as
class falsetuple(tuple):
def __nonzero__(self):
return False
Then you could return
I'm not necessarily recommending that you do this, in fact I have serious misgivings about flouting this convention, I'm just saying that the truthiness of non-empty tuples is not necessarily in itself a reason to not return a tuple.
If your routine normally returns a tuple, then a tuple is what it should keep returning. The real choice is between returning
If it were me, and I chose the tuple over the exception, I would go with the FalseTuple that kindall suggests, and also realize that the calling code (which is using tuple unpacking) can also test
if city is None:
to see if a valid result was obtained. This way you are supporting tuple extraction across all possible return values, and still allowing the pythonic idiom of asking the object, "Do you evaluate as True?" (Here is kindall's again for completeness):
class FalseTuple(tuple):
def __nonzero__(self):
return False
why not making State a property of City? That way your function would return always one value: a City or None.
Returning (None, None) is bad for all the reasons stated in the other answers and serves only to support tuple unpacking.
None is the best value to return to state that no valid city can be returned, but having a function returning 1 or 2 values is not that good, again because of tuple unpacking.
To me, returning (None, None) would imply that (None, State) or (City, None) would also be valid return values. If that is the case, go with (None, None), otherwise, Felix and Brent provide very good arguments for simply returning None.
I would implement a public method for object that returned, let say
|
vince06fr
Re : Nettoyage dans les noyaux (kernel)
Umuntu : Si tu veux prendre le temps de traduire ce script, surtout ne te gêne pas comme tout est "hardcodé" dans le script, la seule chose à faire est... De modifier l'ensemble des textes en français présents dans le script pour les mettre en anglais.
Une fois le script modifié, et après avoir vérifié que cette nouvelle version ne pose pas de de soucis particulier, je ferai un nouveau paquet "anglais".
Si quelqu'un connait un moyen simple d'inclure les deux langues dans le même script je suis preneur, mais je doute que ce soit possible facilement. (Et je préfère avoir deux versions faciles à lire et à mettre à jour plutôt qu'une seule plus compliquée à modifier)
Il faut utiliser des fichier .po avec la bibliotheque gettext
http://fr.wikipedia.org/wiki/Gettext
http://schplurtz.free.fr/wiki/envrac/bash-international
Dernière modification par vince06fr (Le 06/11/2012, à 21:53)
Hors ligne
Hoper
Re : Nettoyage dans les noyaux (kernel)
frenchy : mince... ca ne devrait plus faire ca... je regarderai ca des que possible (pas avant quelques jours).
Vince : merci pour les infos.
Hors ligne
Hoper
Re : Nettoyage dans les noyaux (kernel)
Je viens de regarder et de trouver le soucis. Je ne sais pas du tout comment j'ai fait mon coup, mais la correction apportée (post 199) n'était pas présente dans la version 3.2 en téléchargement C'est maintenant réparé.
Frenchy82 : Peut tu re-télécharger le paquet depuis mon blog, refaire l'installation, et refaire un essai ?
Désolé aussi d'avoir mis autant de temps pour répondre alors qu'il s'agissait la d'un problème important, mais il se trouve que j'étais un peu occupé ces derniers temps
Dernière modification par Hoper (Le 16/11/2012, à 17:38)
Hors ligne
frenchy82
Re : Nettoyage dans les noyaux (kernel)
C'est tout bon maintenant
Merci pour ton attention
Hors ligne
loubrix
Re : Nettoyage dans les noyaux (kernel)
Si quelqu'un connait un moyen simple d'inclure les deux langues dans le même script je suis preneur
perso, je remplace les textes à afficher par une variable, et je fais un case, comme ça:
case "$LANG" in
fr*)
TITLE="Mon titre"
_yes="Oui"
_no="Non"
_cancel="Annuler"
_continue_label="Continuer"
_exit="Quitter"
;;
*)
TITLE="My title"
_yes="Yes"
_no="No"
_cancel="Cancel"
_continue_label="Continue"
_exit="Exit"
;;
esac
et les variables dans le script (ici dans une déclaration qui m'évite de repasser toujours les mêmes options à dialog à chaque utilisation):
DIALOG() {
dialog --title "$TITLE" \
--yes-label "$_yes" --no-label "$_no" --cancel-label "$_cancel" --exit-label "$_exit" \
"$@"
}
si ça peut aider
PS: sinon, on a soumis une demande qui a le même but que ton script (mais automatisé) sur Launchpad
Dernière modification par loubrix (Le 16/11/2012, à 19:21)
Asus X50VL - Ubuntu 12.04 AMD64
HP G62 - Ubuntu 12.10 AMD64
Fujitsu-Siemens Amilo EL - Lubuntu 12.04 i686
Manjaro, une rolling pour débutants
Hors ligne
Babdu89
Re : Nettoyage dans les noyaux (kernel)
Bonjour...
Je ne sais pas si quelqu'un a testé kclean sur Ubuntu 13.04 ...
Comme j'ai installé une version de test, et qu'il y avait 3 versions de noyau dans l'Os, après les mises à jour ... J'ai fait le test ...
Çà marche !! ....
Le contenu ,du menu Grub de la 13.04, maintenant ...
bernard@bernard-GA-7VAX:~$ grep menuentry /boot/grub/grub.cfg
if [ x"${feature_menuentry_id}" = xy ]; then
menuentry_id_option="--id"
menuentry_id_option=""
export menuentry_id_option
menuentry 'Ubuntu' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-9236aa85-fab4-459f-95fe-e5ca7e172cfc' {
submenu 'Options avancées pour Ubuntu' $menuentry_id_option 'gnulinux-advanced-9236aa85-fab4-459f-95fe-e5ca7e172cfc' {
menuentry 'Ubuntu, avec Linux 3.7.0-5-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.7.0-5-generic-advanced-9236aa85-fab4-459f-95fe-e5ca7e172cfc' {
menuentry 'Ubuntu, avec Linux 3.7.0-5-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.7.0-5-generic-recovery-9236aa85-fab4-459f-95fe-e5ca7e172cfc' {
menuentry 'Ubuntu, avec Linux 3.7.0-4-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.7.0-4-generic-advanced-9236aa85-fab4-459f-95fe-e5ca7e172cfc' {
menuentry 'Ubuntu, avec Linux 3.7.0-4-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.7.0-4-generic-recovery-9236aa85-fab4-459f-95fe-e5ca7e172cfc' {
menuentry "Memory test (memtest86+)" {
menuentry "Memory test (memtest86+, serial console 115200)" {
@+. Babdu89 .
J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours....
Hors ligne
Hoper
Re : Nettoyage dans les noyaux (kernel)
Merci pour ce test
Hors ligne
cptnflam
Re : Nettoyage dans les noyaux (kernel)
J'ai installé la dernière version en deb sur debian sid + cinnamon
- Pour pouvoir le lancer depuis le menu, il faut éditer le fichier sudoers.
- Sinon le lancer dans une console root avec kclean --gui
Super idée ce script.
Merci.
Hors ligne
Hoper
Re : Nettoyage dans les noyaux (kernel)
Attention en l'utilisant sous debian, il me semble que le nom de certains paquets différent... Vérifie bien à chaque fois ce qu'il te propose de supprimer Sinon, ce script est prévu pour fonctionner aussi bien (si ce n'est mieux) en ligne de commande.
Dernière modification par Hoper (Le 12/12/2012, à 12:08)
Hors ligne
cptnflam
Re : Nettoyage dans les noyaux (kernel)
Merci pour le conseil. Je vais privilégier la ligne de commande.
Hors ligne
Babdu89
Re : Nettoyage dans les noyaux (kernel)
Bonjour...
Kclean tester aujourd'hui avec Xubuntu 12.10 ...
Dans les maj proposées,il y a un changement de version de noyau
3.5.0-19 ==> 3.5.0-21 ...
Je fais le maj du noyau ...
J'installe Kclean depuis le lien du post#1 de ce sujet ...
Je lance Kclean et voila ce qui m'est proposé de désinstaller ; Ah, je n'ai pas de noyau 3.0.5-21 dans ce que propose Kclean ...
Je vérifie le contenu du menu grub de Xubuntu 12.10 ...
Le noyau 3.0.5-21 est bien installé et présent au menu grub ...
Bon je fais une maj de Grub depuis Xubuntu 12.10 ...J'ai bien le noyau 3.0.5-21 en premier ...
Je relance Kclean ; toujours pareil, pas de noyau 3.0.5-21 , il n'est pas vu par Kclean ...
J'avais déjà eu des soucis avec une histoire de maj de grub ... ,J'en ai parlé quelques posts plus haut... Çà étonnait les intervenants ...
Ah... Au fait... j'ai plusieurs Linux installésJe lance mon Xubuntu 12.10, depuis le menu grub de l'os qui fait démarrer ma machine ... Ubuntu 12.04 ...
Bon ,je relance ma machine...
Dans le menu grub de la 12.04, le noyau 3.0.5-21 de Xubuntu 12.10, nest pas dans le menu grub de la 12.04 ...
Je lance la 12.04, je fais une maj de grub ... le noyau 3.0.5-21 est dans l'entrée du menu grub qui lance ma machine...
Je relance Xubuntu 12.10 depuis le menu grub de la 12.04 ...
Je lance Kclean et ...
Voila ,j'ai le noyau 3.0.5-21 cette foi-ci ...
Que faut'il en déduire? ...
Pourquoi suis-je obligé de mettre grub à jour, sur l'Os qui fait démarrer la machine, et qui n'est pas Xubuntu 12.10 ?...
Important çà, dans le cadre d'un multiboot, dont la machine est démarrée par un autre Os linux que celui où on veut uriliser Kclean...
Je résume ce qui c'est passé sur ma machine...
Multi boot lancé sur Ubuntu 12.04 ...
Lancement Xubuntu12.10 depuis le menu grub de Ubuntu12.04...
Maj de Xubuntu 12.10 proposés avec changement de noyau 3.0.5-19 ==>3.0.5-21 ...
Installation de Kclean v3.2 ...
Lancement de Kclean ... pas de noyau 3.0.5-21 proposé dans la fenêtre de Kclean ,propose 3.0.5-19 ...
Maj de grub de Xubuntu 12.10 ...
Pas de changement dands la fenêtre de Kclean ... ==> 3.0.5-19 ...
Je comprend qu'il faut que je mette grub à jour sur l'Os qui lance la machine, ce n'est pas Xubuntu 12.10 ...
Obligé de relancer la machine sur Ubuntu 12.04 pour mettre à jour grub de la 12.04 ... il n'y a pas de noyau 3.0.5-21 dans le menu grub ,concernant Xubuntu 12.10 ...
Maj de grub Ubuntu 12.04 faite, le noyau 3.0.5-21 de Xubuntu 12.10, est au menu grub de Ubuntu 12.04 ...
Lancement de la machine sur Xubuntu 12.10 , depuis le menu grub de Ubuntu 12.04 ...
Kclean voit maintenant le noyau 3.0.5-21 sur Xubntu12.10 ...Je peux nettoyer...
Donc... Dans le cadre d'un multiboot Linux ..L'utilisateur qui ne comprend pas ce qui se passe... Qui ne fait pas la maj de grub de l'Os qui lance la machine ,il va chercher longtemps,avant d'arriver à utiliser Kclean sur un autre Os ,lancé depuis le menu grub de l'Os qui lance la machine ...
Çà n'est expliqué nul part çà ... (À part ici,maintenant) ...
Je teste le nettoyage...
Édit...
Çà marche... Voici le menu grub de Xubuntu 12.010 ,maintenant....
Reste les noyaux 3.0.5-19 et 3.0.5-21 ...
@+. Babdu89 .
Dernière modification par Babdu89 (Le 22/12/2012, à 15:47)
J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours....
Hors ligne
Hoper
Re : Nettoyage dans les noyaux (kernel)
Maj de Xubuntu 12.10 proposés avec changement de noyau 3.0.5-19 ==>3.0.5-21 ...
Installation de Kclean v3.2 ...
Lancement de Kclean ... pas de noyau 3.0.5-21 proposé dans la fenêtre de Kclean
De ce que je comprend, j'ai l'impression qu'il n'y a aucun problème. kclean ne te proposera jamais de supprimer le noyau que tu es en train d'utiliser. Donc effectivement, il ne le "voit pas", et c'est tout à fait normal !
Hors ligne
Babdu89
Re : Nettoyage dans les noyaux (kernel)
Bonsoir...
@ Hoper ...
De ce que je comprend, j'ai l'impression qu'il n'y a aucun problème. kclean ne te proposera jamais de supprimer le noyau que tu es en train d'utiliser. Donc effectivement, il ne le "voit pas", et c'est tout à fait normal !
OK!!!...
La prochaine foi que çà arrive, je fais un reboot sur l'OS concerné , durant les manips pour voir ce qui se passe ...
Merci ...
Bonnes fêtes à tous...
@+. Babdu89 .
J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours....
Hors ligne
Babdu89
Re : Nettoyage dans les noyaux (kernel)
Bonjour...
Un peu de pub, et un test + démonstration de l'utilisation du script en mode graphique sous la 13.04 encore ici ...
Bonne continuation ...
@+. Babdu89 .
J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours....
Hors ligne
Hoper
Re : Nettoyage dans les noyaux (kernel)
Merci pour le test en 13.04
Hors ligne
Sylll2o
Re : Nettoyage dans les noyaux (kernel)
Bonjour,
Un grand MERCI pour ce script Bravo Hoper
Parfait pour les allergiques du terminal !!!
++
Hors ligne
Hoper
Re : Nettoyage dans les noyaux (kernel)
C'est la qu'on voit qu'il en faut pour tous les gouts. J'ai déjà reçu des remerciements de gens qui trouvaient ce script très pratique à utiliser en ligne de commande... comme quoi
Hors ligne
Babdu89
Re : Nettoyage dans les noyaux (kernel)
Bonjour...
@ Hoper ...
Je reviens sur un souci déjà évoqué dans ce sujet ... Avec plus de détails des manips ...
Le cadre d'un multi-boot , un Os dont veut nettoyer le nombre de noyaux avec ton script, après une maj système, et ajout d'un nouveau noyau ...
Os à nettoyé ,installé en /sda11
Os qui démarre la machine installé en /sda13
Mais ...
Le fait que l'Os a "nettoyer" (/sda11) , soit démarré par le menu Grub non à jour, d'un autre Os (/sda13) que celui où on veut utiliser ton script (sur /sda11)...(forcément,il ne peut pas y avoir d'entrée du dernier noyau, de l'Os à nettoyé (/sda11), au menu Grub de L'Os qui lance l'Os à nettoyé(/sda13) ) ...
Donc l'Os à nettoyé (/sda11) est démarré par l'avant dernier noyau ,dans le menu Grub de l'Os (/sda13) qui lance la machine...
Tant que la maj de Grub de l'Os (/sda13) qui la la machine ne sera pas faite, le dernier noyau de l'Os à nettoyé (en /sda11) ne figure dans le menu Grub de l'Os (/sda13) qui lance la machine ...
Bon , le souci, c'est que bien que le dernier noyau soit installé dans l'Os (/sda11) voici ce que donne les manips ...
Maj système avec changement de noyau sur l'Os en (/sda11) ... 3.8.0-5 vers le 3.8.0-6 ...
Maj de Grub (déjà faite' de cet Os (/sda11) ...
Lancement du script de Hoper ...
Le script ,nous signal que nous somme sur le noyau 3.8.0-5 , normal, et nous propose de désinstaller le dernier noyau installé 3.8.0-6 ?!?!?!.....
Pas normal çà ... Çà tient au fait que l'on est lancé depuis le menu Grub de l'Os en (/sda13) sur le noyau 3.8.0-5 ...
Voila le contenu de l'entrée au menu Grub de l'Os (/sda11) qui est lancer depuis le nenu Grub de l'Os (/sda13) ...
menuentry "Ubuntu' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.8.0-5-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-5-generic-advanced-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.8.0-5-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-5-generic-recovery-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.8.0-4-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-4-generic-advanced-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.8.0-4-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-4-generic-recovery-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.8.0-1-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-1-generic-advanced-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.8.0-1-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-1-generic-recovery-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
Il n'y a pas de noyau 3.8.0-6 ...
Je reboot la machine sur l'Os qui est en /sda13 ,pour faire la maj de Grub de cet Os ...
Voila ce que donne le contenu, pour la même entrée au menu Gtub ,maintenant ...
menuentry "Ubuntu' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.8.0-6-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-6-generic-advanced-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.8.0-6-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-6-generic-recovery-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.8.0-5-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-5-generic-advanced-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.8.0-5-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-5-generic-recovery-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.8.0-4-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-4-generic-advanced-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.8.0-4-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-4-generic-recovery-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.8.0-1-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-1-generic-advanced-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.8.0-1-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-1-generic-recovery-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
Çà y est ,nous avons maintenant le noyau 3.8.0-6 dans le menu Grub de l'Os en /sda13 , pour lancer l'Os en /sda11 ...
Je relance la machine, et je démarre l'Os en /sda11 (l'Os à nettoyer) ...
Je lance le script, et cette foi-ci, c'est conforme à ce que j'en attends ...
Le script me dit bien que je suis sur le noyau 3.8.0-6 ...
Et propose les bonnes versions au nettoyage ...
Je valide pour faire la manip ...
Voila c'est fini ...
Le contenu du menu Grub , depuis l'Os nettoyé en /sda11 ...
menuentry 'Ubuntu' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-9236aa85-fab4-459f-95fe-e5ca7e172cfc' {
submenu 'Options avancées pour Ubuntu' $menuentry_id_option 'gnulinux-advanced-9236aa85-fab4-459f-95fe-e5ca7e172cfc' {
menuentry 'Ubuntu, avec Linux 3.8.0-6-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-6-generic-advanced-9236aa85-fab4-459f-95fe-e5ca7e172cfc' {
menuentry 'Ubuntu, avec Linux 3.8.0-6-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-6-generic-recovery-9236aa85-fab4-459f-95fe-e5ca7e172cfc' {
menuentry 'Ubuntu, avec Linux 3.8.0-5-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-5-generic-advanced-9236aa85-fab4-459f-95fe-e5ca7e172cfc' {
menuentry 'Ubuntu, avec Linux 3.8.0-5-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-5-generic-recovery-9236aa85-fab4-459f-95fe-e5ca7e172cfc' {
Après reboot sur l'Os qui lance la machine /sda13 ...
Mise à jour à nouveau de Grub de cet Os ...
Le contenu de l'entrée de l'Os /sda11, au menu Grub de L'Os qui lance la machine /sda13 ...
menuentry "Ubuntu' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.8.0-6-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-6-generic-advanced-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.8.0-6-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-6-generic-recovery-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.8.0-5-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-5-generic-advanced-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.8.0-5-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-5-generic-recovery-9236aa85-fab4-459f-95fe-e5ca7e172cfc (on /dev/sda11)" --class gnu-linux --class gnu --class os {
C'est bon ,j'ai bien les deux denier noyaux .... 3.8.0-5 et 3.8.0-6 ....
Alors question ...
Quelle va être la réaction d'un utilisateur, qui n'aura pas pigé tout ceci , en utilisant le script ??... Et qui va se retrouver devant ceci???..
Dans le cas d'un multi-boot , avec démarrage depuis le menu Grub d'un Os (/sda11) autre que celui sur lequel on veut utiliser le script ...
N'y a-t'il pas moyen de mettre un message d'alerte, incitant l'utilisateur à faire la mise à jour de Grub de l'Os (/sda13) qui lance la machine ?? ...
Voir essayer de modifier ton script, pour qu'il prenne en compte cette situation ... Et fasse lui même la mise à jour de Grub sur l'Os qui lance la machine, avant de continuer le nettoyage sur l'Os où on utilise le script ...Ceci en transparent pour l'utilisateur ...
Si tu entrevois une possibilité, tu me fais signe ,pour aider à tester ...
Voila , je pense que ces manips devraient aider à mieux cerner le problème ....
@+. Babdu89 .
Dernière modification par Babdu89 (Le 15/02/2013, à 21:13)
J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours....
Hors ligne
Hoper
Re : Nettoyage dans les noyaux (kernel)
Babdu89, je suis vraiment désolé parce que tu fais clairement de gros efforts, avec des postes très long, et des copies d'écran et tout et tout.
Mais cela fait deux fois que je ne comprend RIEN à tes messages.
Je ne sais pas, ça vient peut etre de moi, mais j'ai beau essayé de me concentrer sur ce que tu raconte, au bout de quelques lignes je suis largué. Pour te dire la vérité, je n'arrive même pas à lire tes posts jusqu'au bout.
Globalement, que tu sois en multiboot ou pas, le script s'en fiche complétement. Il fonctionne de façon très simple, en listant les noyaux installés avec la commande dpkg -l (le contenu de grub n'a rien à voir la dedans) trouve ceux qu'il faut supprimer et les supprime toujours avec dpkg. Je crois vraiment que tu te fais des noeuds dans le cerveau pour rien.
Le script ,nous signal que nous somme sur le noyau 3.8.0-5 , normal, et nous propose de désinstaller le dernier noyau installé 3.5.8-6 ?!?!?!.....
Pas normal çà ..
Et pourquoi pas normal ? 3.5.8-6 est bien inférieur à 3.8.0-5 non ? Il est donc bien normal qu'il te propose de le supprimer. Encore une fois, le "contenu de grub" (ce qui ne veut pas dire grand chose) n'a rien à voir dans tous ça. Je pense que tu te imagine des choses (à propos du fonctionement de ce script) qui sont très loin de la réalité.
Hors ligne
Babdu89
Re : Nettoyage dans les noyaux (kernel)
Bonsoir...
@ Hoper ...
Déjà excuse moi "d'écorcher " ton pseudo Hopper ,pour Hoper ...
Tu dis ...
Le script ,nous signal que nous somme sur le noyau 3.8.0-5 , normal, et nous propose de désinstaller le dernier noyau installé 3.5.8-6 ?!?!?!.....
Pas normal çà ..
Et pourquoi pas normal ? 3.5.8-6 est bien inférieur à 3.8.0-5 non ? Il est donc bien normal qu'il te propose de le supprimer. Encore une fois, le "contenu de grub" (ce qui ne veut pas dire grand chose) n'a rien à voir dans tous ça. Je pense que tu te imagine des choses (à propos du fonctionement de ce script) qui sont très loin de la réalité.
Ou là là...
Je me suis trompé en reportant les n° de versions de noyau ... 3.8.0-5 et 3.8.0-6 ...
Voir ce qui est indiqué entre les balises code ...
J'ai corrigé mon post, et çà change la donne ...
@+. Babdu89 .
J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours....
Hors ligne
Hoper
Re : Nettoyage dans les noyaux (kernel)
Ok, la dernière copie d'écran semble indiquer que dans des cas VRAIMENT tordus il y a peut être un soucis... Je vais donc sérieusement ré-essayer de comprendre ton post.
(laisse moi un peu de temps, parce que je ne pourrai pas me pencher la dessus ce week end...)
Hors ligne
Babdu89
Re : Nettoyage dans les noyaux (kernel)
Bonsoir ...
@ Hoper ...
Ok, la dernière copie d'écran semble indiquer que
dans des cas VRAIMENT tordusil y a peut être un soucis...
Je re-formule en plus simple ...
Une machine en multi-boot Os Linux, (au moins deux ; Linux1 et Linux2) ...
La machine boot sur le Linux2 ...( donc menu Grub du Linux2)
Sur le Linux1...
La maj système, propose un changement de version de noyau ...
On en profite, pour utilise ton script ...
Et,on se retrouve dans la situation que je décris ...
Je ne trouve pas que ce soit un cas vraiment tordu ... On doit voir çà sur toutes les machines en multi-boot Os Linux ...
Prends ton temps pour étudier, voir tester chez toi si tu as la possibilité ... C'est de ma part juste une constatation que je rapporte ...
Ce qui n'enlève rien à la qualité du script que tu as créé ...
Juste que dans le cas d'espèce, çà engendre des manips non prévues, du Grub de L'Os (Linux2) qui lance la machine, pour pouvoir utiliser ton script correctement sur le Linux1 ...
Bonne continuation ...
@+. Babdu89 .
Dernière modification par Babdu89 (Le 15/02/2013, à 21:17)
J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours....
Hors ligne
Hoper
Re : Nettoyage dans les noyaux (kernel)
Une machine en multi-boot Os Linux, (au moins deux ; Linux1 et Linux2) ...
Plusieurs linux sur une même machine, personnellement je trouve ça déjà bien tordu Si c'est pour faire des essais de distribution etc, il semble plus logique de passer par des machines virtuelles mais bon.
La machine boot sur le Linux2 ...( donc menu Grub du Linux2)
Et alors la, on entre dans le vraiment bizarre. Le role de grub est bien de gérer l’amorçage de l'OS de ton choix. Pourquoi mettre plusieurs grub différents !? Pour moi, le gestionaire de boot, que ce soit grub, ou lilo, ou gag, ou ce que tu veux, ça se met sur le MBR et il y en a qu'un, pas deux.
On doit voir çà sur toutes les machines en multi-boot Os Linux ...
Alors la non, je peux me tromper bien sur, mais vraiment je crois pas
Il n'en reste pas moins que, comme indiqué plus haut, je vais essayer de de comprendre ce qui se passe...
Hors ligne
Babdu89
Re : Nettoyage dans les noyaux (kernel)
Bonsoir ...
@ Hoper ...
Je fais les tests, en éditant un fichier texte de ce que je fais ... Et malheureusement je ne me relis pas, avant de faire des Copier/coller, pour poster...
Il faut m'en excuser, et surtout continuerà me "ramasser" car je suis impardonnable ...
Quand on fait des tests il faut faire plus attention à ce que l'on fait et dit ...Mea-culpa ...
La machine boot sur le Linux2 ...( donc menu Grub du Linux2)
Non , je voulais écrire ...
La machine boot sur le Linux2 ...(
depuis le menu Grub du Linux1)
Çà change encore bien les choses ...
Tu dis ...
Il n'en reste pas moins que, comme indiqué plus haut, je vais essayer de de comprendre ce qui se passe...
Oui ,car voici un deuxième test, fait sur un autre hdd de test, avec un multi-boot Os Linux ...
Hdd multi-boot Os Linux ...Machine bootant sur le Linux1Os qui va être nettoyé avec le script ; Linux2 ,lancé à partir du menu Grub du Linux1 ...
Menu Grub Linux2 avant maj système ... Dernier noyau 3.2.0-35 ...
bernard@bernard-System-Product-Name:~$ grep menuentry /boot/grub/grub.cfg
menuentry 'Ubuntu, with Linux 3.2.0-35-generic' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, with Linux 3.2.0-35-generic (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, with Linux 3.2.0-34-generic' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, with Linux 3.2.0-34-generic (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, with Linux 3.2.0-33-generic' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, with Linux 3.2.0-33-generic (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, with Linux 3.2.0-32-generic' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, with Linux 3.2.0-32-generic (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, with Linux 3.2.0-31-generic' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, with Linux 3.2.0-31-generic (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, with Linux 3.2.0-30-generic' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, with Linux 3.2.0-30-generic (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os {
Maj système sur le Linux2 proposées avec changement de version de noyau 3.2.0-35 vers 3.2.0-38 ...
Je fais les maj, je reboot la machine comme demandé, a partir du menu Grub du Linux1, puisque la machine boot comme çà ...
J'ai bien le noyau 3.2.0.38 installé sur Linux2...
bernard@bernard-System-Product-Name:~$ grep menuentry /boot/grub/grub.cfg
menuentry 'Ubuntu, avec Linux 3.2.0-38-generic' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, avec Linux 3.2.0-38-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, avec Linux 3.2.0-35-generic' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, avec Linux 3.2.0-35-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, avec Linux 3.2.0-34-generic' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, avec Linux 3.2.0-34-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, avec Linux 3.2.0-33-generic' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, avec Linux 3.2.0-33-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, avec Linux 3.2.0-32-generic' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, avec Linux 3.2.0-32-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, avec Linux 3.2.0-31-generic' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, avec Linux 3.2.0-31-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, avec Linux 3.2.0-30-generic' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, avec Linux 3.2.0-30-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os {
Je lance le script ,pour faire du nettoyage ...
Alors, que faire???? ....
L'utilisateur qui ne sait pas, va te dire que ton script ne marche pas ...
Comme nous savons maintenant qu'il faut mettre à jour le menu Grub de l'Os (Linux1),qui lance actuellement le Linux2 sur le noyau 3.2.0-35,
pour que le Linux2 soit lancé sur le noyau 3.2.0-38...
C'est ce que je vais faire ...
Reboot de la machine sur le Linux1 ...
Voila l'entrée du Linux2 au menu Grub du Linux1 ...
menuentry "Ubuntu, with Linux 3.2.0-35-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, with Linux 3.2.0-35-generic (recovery mode) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, with Linux 3.2.0-34-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, with Linux 3.2.0-34-generic (recovery mode) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, with Linux 3.2.0-33-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, with Linux 3.2.0-33-generic (recovery mode) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, with Linux 3.2.0-32-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, with Linux 3.2.0-32-generic (recovery mode) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, with Linux 3.2.0-31-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, with Linux 3.2.0-31-generic (recovery mode) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, with Linux 3.2.0-30-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, with Linux 3.2.0-30-generic (recovery mode) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
Le dernier noyau présent pour le Linux1 3.2.0-35 .... Pas de noyau 3.2.0-38 ...
Je fais la maj de Grub du Linux1 ...
J'ai le noyau 3.2.0-38 dans les entrées du Linux2, au menu Grub du Linux1, je vais pouvoir lancer le Linux2 sur le noyau 3.2.0-38 ...
menuentry "Ubuntu, avec Linux 3.2.0-38-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-38-generic (mode de dépannage) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-35-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-35-generic (mode de dépannage) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-34-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-34-generic (mode de dépannage) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-33-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-33-generic (mode de dépannage) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-32-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-32-generic (mode de dépannage) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-31-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-31-generic (mode de dépannage) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-30-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-30-generic (mode de dépannage) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
Je vais pouvoir faire mon nettoyage des noyaux en trop du Linux2 maintenant ...
Lancement de Kclean à partir du Linux2 ... Ahhhh !!! ... ÇÀ va mieux ...
Je valide l'opération ...
C'est fini ...
Voila les entrées au menu Grub du Linux2 maintenant ... Deux derniers noyaux ...
bernard@bernard-System-Product-Name:~$ grep menuentry /boot/grub/grub.cfg
menuentry 'Ubuntu, avec Linux 3.2.0-38-generic' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, avec Linux 3.2.0-38-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, avec Linux 3.2.0-35-generic' --class ubuntu --class gnu-linux --class gnu --class os {
menuentry 'Ubuntu, avec Linux 3.2.0-35-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os {
Pour être complet, il n'y a plus-qu'à rebooter la machine sur le Linux1, mettre faire une maj de Grub ,pour n'avoir que deux noyaux dans les entrées du Linux2, au menu Grub du Linux1 ...
Entrées du Linux2 au menu Grub du Linux1 ... Avant maj de Grub ...
menuentry "Ubuntu, avec Linux 3.2.0-38-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-38-generic (mode de dépannage) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-35-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-35-generic (mode de dépannage) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-34-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-34-generic (mode de dépannage) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-33-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-33-generic (mode de dépannage) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-32-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-32-generic (mode de dépannage) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-31-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-31-generic (mode de dépannage) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-30-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-30-generic (mode de dépannage) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
Entrées du Linux2 au menu Grub du Linux1 ... Après maj de Grub ...
menuentry "Ubuntu, avec Linux 3.2.0-38-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-38-generic (mode de dépannage) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-35-generic (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
menuentry "Ubuntu, avec Linux 3.2.0-35-generic (mode de dépannage) (on /dev/sdb9)" --class gnu-linux --class gnu --class os {
Voila c'est fini, il n'y a plus-qu'à lancer le Linux2 sur le noyau 3.2.0-38 ...
Alors, des trucs tordus comme çà, j'en ai, encore sur 2 hdd usb de tests, et sur ma machine de la campagne, 4 hdd internes avec les mêmes situations ...
Des utilisateurs , qui n'aiment pas la ligne de commande , comme moi, mais qui se plaisent à tester tou ce qui leur tombe sous la main ,il y en a plein le forum, je t'assure...
Donc Un Grand Merci , a des contributeurs comme toi et beaucoup, d'autres qui mettez votre "travail" à disposition ,pour des "gus" comme moi ...
Alors si en retour ,nous pouvons aider lorsque c'est possible, il ne faut pas s'en privé ...
Mais ,je le reconnais humblement, ne pas dire trop n'importe quoi ... Je ferais plus attention ,les prochaines fois ...
Excuse ,encore la longueur du post, mais je pense pas que l'on puisse expliquer ceci en deux ou trois lignes ...
Tu dis...
Plusieurs linux sur une même machine, personnellement je trouve ça déjà bien tordu smile
Si c'est pour faire des essais de distribution etc, il semble plus logique de passer par des machines virtuelles mais bon.
Pas sûr que l'on voit tous ce qui ne va pas en VM ... En installé, tout ce que l'on teste ...Çà marche, ou pas ... Bon ,il faut du temps ,et de la passion ...
Au fait, qu'est-ce qui peut être fait pour régler le souci??? ...
@+. Babdu89 .
Dernière modification par Babdu89 (Le 16/02/2013, à 00:28)
J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours....
Hors ligne
Hoper
Re : Nettoyage dans les noyaux (kernel)
Tu n'a pas répondu à l'une de mes remarques.
Comment se fait il que tu ai plusieurs grub !?
Pour le reste, on ne s'en sortira pas par forum interposé. Je te propose qu'on en discute par téléphone (je peux te filer mon téléphone, ou le contraire, comme ça t'arrange). Évidement pas ce soir l'appel hein
Hors ligne
|
self is not used to declare variables anywhere. self is the usual name for the first parameter of a method, as the method receives the instance to which it is bound as the first parameter to every call.
It is not used "elsewhere" because it only applies in contexts where there is an instance for a callable to be bound to.
You are probably thinking of something like:
class Foo(object):
y = 1
x = self.y * 2
This is not possible because there is no self - in fact, at the time that the body of a class statement is evaluated, there is no instance or class object yet in existence. It is also not necessary, because one can simply refer directly to other variables in the scope of the body without using self.
Note that assignments to members of self, and assignments to variables in class scope do two different things:
class Foo(object):
y = 1 # class variable
def __init__(self):
self.x = self.y * 2 # instance variable, defined by reference to class variable
first = Foo()
Foo.y = 2
first.y = 3
second = Foo()
print first.x # = 2
print second.x # = 4
|
29 Dec 2013
When writing a new program in python, I often find myself using the same pattern over and over, and wanted to document it here. The idea is that you have some core functionality of the program, and loadable modules to expand the functionality, with only some of the modules being loaded at runtime. These modules are single files inside a modules/ directory, contain a single Module() class (and optionally others depending on what the module needs), and some other functionality that the core of your program will use. This pattern lets you specify which modules to load in a configuration file, and load them up on demand, passing in some configuration to the module.
First, the code to load the modules:
import ConfigParser import logging import os import time # Read the config file(s) c = ConfigParser.SafeConfigParser() c.read(['/etc/myapprc', os.path.expanduser('~/.myapprc')]) # Load the modules modules = [] # List of module objects for s in c.sections(): # We define which modules to load by the fact that there is a section # in the file for that module, starting with "mod_". This lets you # have other configuration in the file if needed. You can also get the # list of modules to load in some other way if desired. if s.startswith("mod_"): modulename = s[4:] # Strip off the mod_ try: # Actually import the module module = __import__('modules.%s' % modulename, globals(), locals(), [modulename]) except ImportError, e: # Print an error if we failed, and carry on, you could exit # here if desired. I also tend to use the logging module, but # this could just be a print statement or something else if # needed. logging.error("Unable to load module %s: %s" % (modulename, e)) continue # Instantiate an instance of the module, and pass in the config # from the file. I convert all items to a dict for ease of access # by the module. You could also pass the raw config parser object # if desired. module_object = module.Module(dict(c.items(s))) # Add the module to the list. This can be more complex than just # storing the module object (e.g. adding a name and some config in a # dict) if you needed to store more informaiton. modules.append(module_object) # Do something with the modules here. Simple example here to call all module # run() methods over and over, sleeping 10 seconds in between. while True: for m in modules: m.run() time.sleep(10)
This gives you a list of module objects in modules, and you can then call methods on those modules (I tend to have a run() method or have the __init__ method set up callbacks for various events depending on the program’s functionality).
A module itself would be a single python file inside modules (e.g. modules/example.py) and look something like this:
class Module(object): def __init__(self, config): # config is a dictionary containing the relevant section of the # configuration file self.foo = config.get('foo', 'some_default') # more initialization code here # ... other module code goes here
You also need to make sure your modules directory has an __init__.py file (it can be blank) so that python knows the directory contains modules.
This pattern can be expanded on in various ways depending on the needs of your program, but for anywhere where you have pluggable functionality, it works well.
11 Jun 2013
I’ve been reading Tom Limoncelli’s Time Management for Systems Administrators once again, and am trying out (once again, for real this time) the time management system described in the book called “the cycle”. I also use todo.txt system as one of my (several) task list tools, and decided to try to make it work with the cycle.
The advantages of the todo.txt system are its simplicity, ease of adding new items (with an alias it’s simply typing t add Do something in any terminal window). The built in tools did need some tweaks to get things working correctly however.
One very nice feature of the cycle is that you have a different todo list for each day. Do you have something that needs doing Wednesday next week? Add it to that day’s todo list and you don’t have to think about it again until Wednesday comes around, at which point it will be on your todo list ready for you to look at. Items that you don’t get done today, either because you have decided you’re not doing them today or because you run out of time at the end of the day, get bumped to next day’s todo list and are marked as ‘managed’ on today’s todo list. This system makes it very easy to see what you have left to do today, and lets you immediately get items that aren’t going to be done today out of the way and to somewhere where you’ll come across them as a more appropriate time.
Out of the box todo.sh, the todo.txt cli script, is primarily made to work with a single file, namely todo.txt, and another to archive completed tasks so they don’t clutter up the main file. Because of this, I thought I’d have to write another tool to effectively deal with daily todo lists. However, the config file is actually sourced as a shell script, and so it was a simple matter to change to using a todo.txt file based on today’s date:
export TODO_FILE="$TODO_DIR/$(date +%Y-%m-%d).txt"export DONE_FILE="$TODO_DIR/$(date +%Y-%m-%d)-done.txt"
So far, so good. I run todo.sh and it instantly picks today’s todo list.
$ todo.sh add Throw things at Brian once I get in the office
1 Throw things at Brian once I get in the office
2012-05-25: 1 added.
The book recommends 3 priorities for tasks: A - needs to be done today, B - needs to be done soon, C - everything else. Todo.sh also uses alphabetical priorities, and they’re simple to add/change:
$ todo.sh pri 1 A
1 (A) Throw things at Brian once I get in the office
TODO: 1 prioritized (A)
Todo.sh even has built in support for looking at other dated files:
$ todo.sh listfile 2013-05-24.txt # you could use 'todo.sh lf' here
1 Revoke VPN keys for bob
2 Purchase new servers
The missing piece was the ability to bump tasks, both individually and with a single command to bump any incomplete tasks left at the end of the day. This functionality was implemented as an addon to todo.sh, which is available on github.
Commands that are in the addon:
bump - bump a single task to the next day. Use this for when you decide you won’t be doing that task today.
bumpall - bump all the remaining tasks for today on to tomorrow’s todo list. Do this at the end of the day with any tasks you didn’t get to complete. Be sure to review any high priority tasks and deal with them before bumping to the next day.
verify - Search all files for unmanaged tasks (those that haven’t been completed and/or bumped to a later day)
bringforward - bring all the tasks you forgot to manage on to today’s todo list.
I also have the following in my setup, which are included as separate addon commands in the git repository:
A quick command to commit changes and push to git. This is literally a wrapper around git add, git commit, and git push with a default commit message.
A modified ‘addto’ command to make it easier to add an item to a future todo list. The todo.txt cli by default won’t create a new todo.txt file for you if it doesn’t already exist (I’m guessing it assumes you made a typo), so I modified the command to create a blank todo file first if it matches a certain pattern.
Something to manage a life goals (or someday/maybe for anyone who is familiar with GTD terminology) list. This simply runs the todo.txt cli with a file called goals.txt.
One of the biggest downsides of this system is that it’s tied to the computer. Tom mentions in the book that your system should always be with you to be able to write something down as someone tells it to you in the hallway. While I agree that you should have something with you at all times, it doesn’t have to be the entire todo list system. Borrowing from GTD, I just keep a small notebook or stack of index cards to capture new items on, and review it regularly, adding items to the computerized list as I get back to my desk. The cycle already has a step where you collect new items from phone calls, emails and so on. And having a small notebook or stack of index cards and a pen handy ensures that I don’t lose track of anything… as long as I write it down.
10 Jun 2013
The following is just a couple of snippets I have in my bash prompt to identify various environments that I’m in for rvm, git and so on. While you can usually find some way of getting this information in your prompt on the sites of the individual programs, it’s nice to have something where it’s all together. I’ve also tried to make an effort to avoid slow versions of various commands, ideally just parsing environment variables if possible. Each section of the prompt also has the relevant technology prefixed (e.g. git:branchname or rvm:1.9.3@gemset)
Note: My real prompt has several things not mentioned here. For example, I’ve stripped out all colors added to the prompt. The aim of this is to give you a guide to how to quickly get prompt information for git, rvm, virtualenv and so on.
prompt_command() {
# Runs every time a prompt is displayed
# Command status - display as red if non-zero
local BRIGHT=$(tput bold)
local RED=$(tput setaf 1)
RETVAL=$?
if [[ $RETVAL != 0 ]]; then
RETVAL=$BRIGHT$RED$RETVAL
fi
# Git
GITPROMPT=
if declare -f __git_ps1 >/dev/null; then
# Only run if we have the git prompt stuff loaded
GITPROMPT=`__git_ps1 "%s"`
fi
[[ $GITPROMPT == "(unknown)" ]] && GITPROMPT=
[[ -n $GITPROMPT ]] && GITPROMPT=${PROMPT_MID}git:$GITPROMPT
# Virtualenv wrapper
# Note: add 'PS1=$_OLD_VIRTUAL_PS1' to ~/.virtualenvs/postactivate to
# stop virtualenvwrapper's normal prompt behavior
VENVPROMPT=
[[ -n $VIRTUAL_ENV ]] && VENVPROMPT=${PROMPT_MID}venv:${VIRTUAL_ENV##*/}
# RVM
RUBYPROMPT=
local GEMSET=${GEM_HOME#*@}
if [[ -n $GEMSET && $GEMSET != $GEM_HOME ]]; then
RUBYPROMPT=${PROMPT_MID}rvm:${RUBYVER}${GEMSET}
fi
}
setprompt() {
# Customize these as appropriate
PROMPT_LEFT='('
PROMPT_RIGHT=')'
PROMPT_MID=')-('
# SSH - shows you what IP you're connecting from
local SSHPROMPT=${SSH_CLIENT%% *}
[[ -n $SSHPROMPT ]] && SSHPROMPT="$PROMPT_MID$SSHPROMPT"
# Set the prompt variable here, customize as appropriate. The
# important parts are the GITPROMPT, VENVPROMPT and so on. Note that
# anything set via PROMPT_COMMAND needs to have a backslash before it
# in order for it to be evaluated every time
PS1="$PROMPT_LEFT\u@\h$PROMPT_MID\$RETVAL$PROMPT_MID"
PS1="$PS1\$GITPROMPT\$VENVPROMPT\$RUBYPROMPT$SSHPROMPT$PROMPT_RIGHT"
PS1="$PS1\n$PROMPT_LEFT\W$PROMPT_RIGHT"
}
PROMPT_COMMAND=prompt_command
setprompt
14 Apr 2012
A while ago I was reading a blog post with tips on writing vim plugins. There’s lot of good information there, and if you find yourself writing any vim scripts or plugins, it’s well worth a read. I was surprised by one point though, the section on testing. My vimtodo plugin has a large number of regression tests, and it’s my safety net to make sure that I’ve not horribly broken something with my latest change. I don’t subscribe to the test driven development philosophy of writing a test and coding only until it passes, but I do find it useful to have a few tests to guard against you breaking something.
So when I read that testing sucks so much in Vim that you should avoid it, I was a little surprised, and certainly disagreed with the sentiment. My tests work fine, and I don’t recall it being particularly hard to implement the tests. So I took a look at the shell script testing tool mentioned in the blog post, cram, to see what was so special about it. I looked back at my tests in vimtodo, then at the example of the cram page, and back at my tests. The cram example showed a test that basically looked like a transcript of a shell session, and definitely not like the mess of code that comprised my tests. I thought that it couldn’t be too hard to implement something like that for vim, and the guy who wrote the blog post offered to buy a nice bottle of scotch for anyone who did so. One can never drink too much scotch (this may or may not be true), and so I got cracking.
The result is vimcram, which is now up on github. There are still a few features I’d like to add, but it’s pretty usable, and I’m currently converting all of my tests on vimtodo over to using it.
Tests in vimcram look like this:
Test substituting text:
> Add some text
> Add some more text
:%s/some //
Add text
Add more text
Test normal mode commands
@ggdW
@jdW
text
more text
Which, while not exactly a transcript of a vim session (it’s kind of hard to do with a visual editor and multiple modes), is pretty straightforward.
If you have a vim plugin and don’t have any tests for it, give vimcram a try. It might make test writing easy enough that you actually write them!
27 Jan 2012
Ever since I saw Jekyll, I liked the idea of having a statically generated site for something as simple as a blog where you really don’t need dynamic content (except for comments where, as you can see below, I cheated and used intense debate). But I hadn’t touched anything in ruby before (at the time it probably wasn’t even installed on my web server), was suffering from not-invented-here syndrome, and decided to write my own version in Python. It was clunky, but it worked, for the most part. Two years later however, it’s seen no love, was in dire need of some maintenance/improvement, and I finally realized that pretty much everything I wanted to do was already done in Jekyll.
The site was simple to convert (the original program being an attempted clone), and it now means that I can punt on hosting and let github deal with things. And if github turns out not to be a good choice, then it’s simple to host anywhere. It is after all, a static site.
27 Jan 2012
I’m thinking about backups once more, and thought I would take a look at bup. Bup’s claim to fame (and the reason I first heard about it) is that it’s a git based backup system, or rather it uses the git repository format, with its own tools to make it deal with large files effectively. The more I looked at it, the more I realized that bup being git-based isn’t the main feature. Bup has a rolling checksum algorithm similar to rsync and splits up files so that only changes are backed up, even in the case of large files. This also has a nice side effect: you get deduplication of data for free. This includes space efficient backups of VM images, and files across multiple computers (the OS files are almost identical). I have two laptops with the same data (git repositories, photos, other work) on both of them, and multiple VM images used for testing, so the ability to have block level deduplication in backups sounded ideal.
Bup can also generate par2 files for error recovery, and has commands to verify/recover corrupted backups. This is a useful feature given that bup goes to great lengths to ensure that each piece of data is only stored once.
My old backups were with rsnapshot, and as it happened, bup has a conversion tool for this, so the first step was to move them over to using bup. The command do to this is bup import-rsnapshot, but this didn’t quite work for me and gave an error when running bup save. Thankfully there is a dry-run option which prints out the commands that bup uses, and because rsnapshot backups direct copies of the files, what bup does is basically back up the backup. So I ended up running:
export BUP_DIR=/bup
/usr/bin/bup index -ux -f bupindex.rigel.tmp manual.0/rigel/
/usr/bin/bup save --strip --date=1314714851 -f bupindex.rigel.tmp \
-n rigel manual.0/rigel/
The two bup commands were directly output from the import-rsnapshot command, and I did this multiple times for each backup I had.
Next was to take the initial backup from my laptop. This was actually a different laptop from the one I took the rsnapshot backups with, but I’d copied over a lot of the data and wanted to see how well the dedup feature worked. As can be seen with the rsnapshot import, taking a backup is actually two steps, bup index followed by bup save. The index command generates a list of files to back up, while the save command actually does it. The documentation gives a couple of reasons for splitting this in to two steps, mainly that it allows you to use a different method (such as inotify) to generate and update the index, and it also allows you to only generate the list of files once if you are backing up to multiple locations. This separation of duties appeals to the tinkerer in me, but it would still have been nice to have a shortcut ‘just back it up’ command, similar to how gitpull is a combination of git fetch and git merge.
The commands to take a backup are:
export BUP_DIR=/bupbup index -ux --exclude=/bup /bup save -n procyon /
First, I set the backup directory to /bup. What I’m doing here is backing up locally (and copying to an external hard drive later), but you can also pass the -r option to back up directly to a remote server via ssh.
I also pass the -x option to bup index to limit it to one filesystem, and also exclude the backup directory itself from the backup.
Next, the bup save command actually performs that backup. I passed in the hostname of my laptop (procyon) as the name of the backup set. Multiple backups can have the same name, and they show up as multiple git commits, so a hostname is a good choice for the name of the backup set.
As I mentioned above, bup can make use of par2 to generate parity files. This is a separate step, and is done using the bup fsck command:
bup fsck -g -j4
The -g option generates the par2 files, and the -j 4 option means run up to 4 par2 jobs at the same time. Generating parity files is CPU intensive, so I set it to twice the number of CPUs in my system. I have hyperthreading turned on, and it saturated all 4 ‘virtual’ CPUs. Once this was done, I ended up with several .par2 files in the /bup/objects/pack directory (this is a git repository, and all data is stored in the objects/ dir.
And the results? Bup used 30GB for 2 original backups from rsnapshot (rsnapshot used 26GB and 37GB for the first and second backups, and this was taking into account identical files). Then, when I backed up my 2nd laptop (with approx 40GB used at the time) the size of the bup backup increased by only 4GB. This backup of my laptop included a 5GB ubuntu VM image that didn’t exist in the previous snapshots, so bup must have been able to deal with the duplicate data from the image and the live OS.
All of this sounds amazing, but of course there are a few downsides, all of which are spelled out pretty plainly in the bup README:
no metadata - these are backups of my personal laptop, and I’ll be restoring either single files, or reinstalling and copying over files as I need them, so losing permissions/file ownership etc. isn’t a big deal for me. However, this feature is supposed to be coming soon.
no way to prune old backups - this is another feature that is coming soon, but given that I’m a pack rat, rarely deleting old data, and the dedup feature, I’m not too concerned for the moment.
bup is relatively new and immature. This shows both in the possible bugs I encountered above, the lack of what some might consider essential features, and the somewhat low level command usage (separate index, save and fsck commands). This is easily worked around however, and is likely to improve in future.
That said, if you can live with the above limitations, and want incredible space savings for your backups (especially across multiple computers), then I would suggest giving bup a try.
31 Mar 2010
Less than one week after I switched my hosting over to Solaris 10, with all its ZFS/dtrace goodness, Oracle quietly makes a license change that everybody dealing with Solaris is likely now familiar with, and Solaris 10 is no longer free to use. Emails to Sun/Oracle’s licensing department result only in form letters repeating instructions on the website, and then nothing.
I can’t really blame Oracle for this, Sun didn’t make enough money to survive, and Oracle has this radical idea that you need to actually charge people in order to make money. I can blame them for not providing more clarity regarding the issue (so far they haven’t announced anything), and for leaving customers unsure about what’s going to happen next. However, this is mostly besides the point. I now needed to look into a good alternative.
OpenSolaris is the obvious candidate, and I’ve played around with it a little previously, but I can’t make myself like some of the changes made to it. The biggest annoyances being related to the new packaging system and some of the poor choices made in its design (e.g. no –nodeps option). That is an entire post (or rather, rant) in itself however. In addition to this, I can’t help but believe that Oracle is going to make some change to OpenSolaris that makes it not a realistic option.
This is where FreeBSD comes in. With release 8.0, ZFS has become a fully supported filesystem. It has dtrace support, jails (just like zones), even virtual networking so you can have a full network stack inside the jail.
For my personal server, the main feature I was interested in was ZFS, specifically ZFS root/boot. With ZFS it is trivial to set up mirrored drives, and I wanted to avoid doing software raid with UFS as well as ZFS. Thankfully there is extensive documentation on how to do this. It isn’t in the standard install, but if you need a repeatable procedure for many servers, it’s a (relatively) simple matter to script the installation, and you would probably want to do this anyway for an automated install.
There were a few gotchas, as with any new system you’re not familiar with, but so far it looks quite nice. I’ll be looking further into jails (especially the vimage jails) and other nice features. Hopefully, FreeBSD will turn out to be a good replacement for Solaris.
05 Mar 2010
I’ve finally made all my projects available publicly via git at http://git.mivok.net/ thanks to gitosis. Before that, I kind of just thrown everything in a git directory under my home directory and accessed it over ssh, which worked fine for private repositories, but fell flat whenever I wanted to make something available to somebody else.
Gitosis promised to make it easy to add new repositories and set up access for new people as needed, and once everything is set up, it is really easy - everything is contained in a config file inside a git repository, so you can make changes locally and push. You also have the benefit that your changes themselves are under version control. However, there were a few hiccups along the way, so I’m going to describe what I did in case others try and hit the same problems I did.
Gitosis uses python and setuptools, which I already had available. I’m running Ubuntu, so installing any requirements is as simple as running:
aptitude install python python-setuptools
Of course, git itself is a requirement. For now we’ll use the Ubuntu package, but it’s a good idea to build from source if you want the latest version:
aptitude install git-core
Next, get the gitosis source:
git clone git://eagain.net/gitosis.git
and install:
cd gitosis
sudo python ./setup.py install
So far, everything is pretty straightforward. Next we need to add a user that everyone will connect as in order to access repositories. The main method gitosis uses for accessing repositories, is to have a single user that everyone connects to over ssh. Logins are only allowed via ssh keys, and anyone who connects is restricted to running gitosis commands, preventing them from accessing anything they shouldn’t.
sudo adduser --system --shell /bin/sh --gecos 'git user' \
--group --disabled-password --home /srv/git git
Here I’ve set the home directory to /srv/git. This directory will hold all repositories and gitosis files. Next we need to initialize this directory with all of the gitosis configuration files:
sudo -H -u git gitosis-init < your-ssh-key.pub
(the -H option to sudo sets the HOME variable to the user you are running commands as. In this case - /srv/git).
The your-ssh-key.pub file should be your ssh public key for the computer you are working on now. You will use this to access the administration repository and any other repositories you create later. If you don’t have an ssh key set up already, make one now and copy the id_rsa.pub file to the server before running the above command:
ssh-keygen -t rsa -b 4096
For more information on ssh-keys, see the ssh-keygen man page.
Note: by default, gitosis takes the comment field of your ssh key to be your username. In my case, it was mark@laptop, and I would have had to use mark@laptop as my username whenever editing permissions. If you want something nicer, edit the copy of your public key before running the gitosis-init command and change the comment field to something a little nicer.
Now you have the basic server set up. To edit the configuration, clone the administration repository:
git clone git@your-server.example.com:gitosis-admin.git
Then you can edit the gitosis.conf file, commit it, and push back to the server.
At this point I hit my first snag. Any changes pushed back to the server didn’t take effect. The magic updating of settings wasn’t working. After some hunting around (read: typing stuff into Google and clicking frantically), I found that all of the magic is done via a hook on the gitosis-admin repository. For some reason, the hook script wasn’t executable, and so never ran. Before committing any configuration changes, make sure to fix the permissions on the repository hook:
sudo chmod +x /srv/git/repositories/gitosis-admin.git/hooks/post-update
The basic gitosis setup at this point is complete. Aside from adding repositories and new users, the other steps are optional. However, we are talking about making repositories publicly accessible, and the other two steps - setting up git:// access via git-daemon and setting up gitweb will do this.
First though, here’s a quick overview on adding users/repositories.
To add a new user, get a copy of their ssh public key (ssh keys are what makes the whole thing work), and copy it to your gitosis-admin checkout inside the keydir directory. Name the file USERNAME.pub, replacing the username with the name of the user you wish to add - this is the username you will use when setting permissions. For example, if you add joe.pub, then you will use joe as the username in the configuration below.
To add a repository, you just give somebody permission to access it and then push. This involves editing the gitosis.conf and adding a few lines:
[group foo] writable = myrepository members = joe
This allows user joe to write to myrepository.git. You then add this as a remote in your local repository and push to create the repository on the server:
cd path/to/my-repository
git remote add origin git@your-server.example.com:myrepository.git
git push
This assumes you actually have something to push. In practice this isn’t an issue - you start with a blank local repository (using git init), commit your first changes, and push. The first person to push actually creates the repository.
Setting up git:// access
This part allows people to clone a repository without needing to authenticate, and without having to generate ssh keys. You can’t push to repositories in this way however - you have to use ssh if you want to push back to a repository. Chances are, you don’t want all repositories to be public, and gitosis allows you to pick and choose which you make public and which you make private using (wait for it…) the gitosis.conf file.
Setting up git:// access is as simple as running the git-daemon command:
sudo -u git git-daemon --base-path=/srv/git/repositories/
If you’re running Ubuntu however, gitosis comes with a nice script that you just drop in to /etc/event.d, edit to change the path, and it will start the git-daemon automatically on boot:
sudo cp gitosis/etc-event.d-local-git-daemon /etc/event.d/local-git-daemon
sudo sed -i s+/srv/example.com/git+/srv/git+ /etc/event.d/local-git-daemon
sudo initctl start local-git-daemon
The initctl script starts the daemon without rebooting, which is usually a good thing.
By default, no repositories are made public. To make them public, you need to add a daemon = yes option to your gitosis.conf:
[repo myrepository] daemon = yes
Here we have made a new repo section for myrepository. Save the gitosis.conf file, commit, push, and you should be able to clone myrepository using git://your-server.example.com/myrepository.git.
Gitweb - making everything look pretty
The final step is getting gitweb working. For this you need a copy of gitweb.cgi and associated files. I built git from source, and gitweb.cgi was built as part of this, but if you didn’t do this, there is an Ubuntu package available called gitweb. I also use lighttpd on my server, with pages stored under /srv/www/domain.example.com/pages/ so I’ll be describing a configuration for that server and layout.
First, copy gitweb.cgi, gitweb.css, and all of the images to /srv/www/domain.example.com/. I put the css files and images inside a pages subdirectory (the document root), and put gitweb.cgi inside a separate cgi-bin directory outside of the document root.
Next, configure lighttpd. I have simple-vhost set up which sets the document root based on the domain name requested, so we only need to do special set up for the git/cgi parts:
$HTTP["host"] =~ "^git\.your-server\.example\.com$" {
url.redirect = (
"^/$" => "/gitweb/",
"^/gitweb$" => "/gitweb/"
)
alias.url = (
"/gitweb/" => "/srv/www/git.your-server.example.com/cgi-bin/gitweb.cgi",
)
setenv.add-environment = (
"GITWEB_CONFIG" => "/srv/www/git.your-server.example.com/gitweb.conf",
)
$HTTP["url"] =~ "^/gitweb/" { cgi.assign = ("" => "") }
}
Gitosis does provide a config file for lighttpd, but it wasn’t appropriate for my setup. Note that the above needs the following modules loaded: mod_alias, mod_cgi, mod_redirect, mod_setenv.
Gitweb.cgi needs editing slightly in the above configuration, by default it looks for the css file in the same location as the gitweb.cgi file (i.e. in a /gitweb/ dir), but they are stored at the root of the site. Open up gitweb.cgi and search for gitweb.css. Add a slash before the filename and save the file.
Next is creating a gitweb.conf file. Again, gitosis helps out here, providing a gitweb.conf file that just needs some tweaking with the right paths. Copy the gitweb.conf file from the gitosis source distribution to /srv/www/git.your-server.example.com/, and open it up for editing.
Edit the $projects_list, $projectroot, and the @git_base_url_list lines and save:
$projects_list = '/srv/git/gitosis/projects.list'; $projectroot = "/srv/git/repositories"; @git_base_url_list = ('git://your-server.example.com');
By default, gitosis creates repositories that are only accessible by the git user and users in the git group, so we need to give the web server permissions to access repositories. If this isn’t done, gitweb will say that there are no repositories available even when you configure web access in gitosis for the repository.
usermod -G git www-data
You will need to restart the web server after this in order for the group change to take effect. If your web server is running as someone else other than www-data, change the above command appropriately.
Finally, to give access to a repository via gitweb, the process is similar to setting up git:// access. Edit gitosis.conf, and add a gitweb = yes line next to the daemon = yes line for the repository. Commit, push, and the repository should now show up in gitweb. In the default configuration, you need to have both daemon = yes and gitweb = yes for a repository to be made available via gitweb. See the gitweb.conf file if you want to change this.
20 Sep 2009
One annoyance I found when writing bash scripts is the lack of function references. This became apparent when overriding a function, but when I wanted to change the behavior only slightly. I had a library of functions, and wanted to add some commands before the start of the function, and some cleanup code immediately after it finished.
This being a library function that was called elsewhere, I couldn’t edit the function in the library itself. Nor could I edit the calling code and add the steps before and after - the calling code was itself another library function. This left the option of copying and pasting the entire function, and adding my extra code to the beginning and end.
In python (and many other languages), I would have done something like the following:
old_foo = foo def foo(): initialization_code() old_foo() cleanup_code()
but bash doesn’t seem to support function references in that manner. After much searching however, I finally found a way to save a function under a new name, which gives the same kind of functionality using bash’s declare builtin.
The declare command prints out the values of declared variables, and more importantly, declared functions - declare -f foo will print out the code for function foo. So all you need to do is execute the output of the declare -f command, after substituting the name of the function. The following bash function does just this:
save_function() { local ORIG_FUNC=$(declare -f $1) local NEWNAME_FUNC="$2${ORIG_FUNC#$1}" eval "$NEWNAME_FUNC" }
Add that to your scripts, and you have a simple way to copy/rename a function, and a simple way to add a step before/after an existing function. To copy the python example above:
save_function foo old_foo foo() { initialization_code() old_foo() cleanup_code() }
Now any code calling foo in the script will get the new behavior.
18 Apr 2009
A common thing when writing shell scripts is to allow the user to specify options to commands in a variable. Something like the following:
$ OPTS="--some-option --some-other-option" $ my_command $OPTS
We can set my_command to the following script to see exactly what gets passed:
#!/bin/bash for t; do echo "'$t'" done
Running the above prints the following output:
'--some-option' '--some-other-option'
This works fine, until you want to include options with whitespace in them:
$ OPTS="--libs='-L/usr/lib -L/usr/local/lib'" $ my_command $OPTS '--libs='-L/usr/lib' '-L/usr/local/lib''
This output clearly isn’t what we want. We want a single parameter passed with the entire content of $OPTS. The culprit here is Word Splitting. Bash will split the value of $OPTS into individual parameters based on whitespace. One way to get around this is to put $OPTS in double quotes:
$ OPTS="--libs='-L/usr/lib -L/usr/local/lib'" $ my_command "$OPTS" '--libs='-L/usr/lib -L/usr/local/lib'' $ OPTS="--libs=-L/usr/lib -L/usr/local/lib" $ my_command "$OPTS" '--libs=-L/usr/lib -L/usr/local/lib'
Putting $OPTS in double quotes suppresses word expansion. In the above example, that works as expected. The second command has the single quotes removed as they were passed directly to the command, which isn’t what we wanted. So far, so good. The problem, as you may have spotted by the removal of the single quotes, comes when we want to pass more than one parameter in $OPTS:
$ OPTS="--cflags=O3 --libs=-L/usr/lib -L/usr/local/lib" $ my_command "$OPTS" '--cflags=O3 --libs=-L/usr/lib -L/usr/local/lib'
Here, the entire $OPTS variable gets passed as a single parameter, which isn’t what we want. We want --cflags to be passed as one parameter, and --libs (and everything that comes with it) to be passed as another parameter. Adding more quotes, backslash escaped or not, does nothing to help.
The solution? Use bash arrays:
$ OPTS=("--cflags=O3" "--LIBS=-L/usr/lib -L/usr/local/lib") $ my_command "${OPTS[@]}" '--cflags=O3' '--LIBS=-L/usr/lib -L/usr/local/lib'
Perfect. But what about backward compatibility? If you have hundreds of scripts that use a string for $OPTS, how does it work if you change to using arrays? Let’s try it out:
$ OPTS="--some-option --some-other-option" $ my_command "${OPTS[@]}" '--some-option --some-other-option'
So it works if your old scripts only have single options, but if multiple scripts are needed, then they will need to be changed to use arrays instead. This however seems to be the best option for passing multiple arguments with whitespace.
|
In python, assignment operator can unpack list or tuple into variables, like this:
l = (1, 2)
a, b = l # here goes auto unpack
But i need to specify exactly same amount of names to the left as an items count in the list to the right. But sometimes i don't know a size of the list to the right, for example if i use split(). Example:
a, b = "length=25".split("=") # this will result in a="length" and b=25
But the following code will lead an error:
a, b = "DEFAULT_LENGTH".split("=") # error, list has only 1 item
is it possible to somehow unpack list in the example above so i get a = "DEFAULT_LENGTH" and b equals to 'None' or not set? Straightforward way looks kinda long:
a = b = None
if "=" in string :
a, b = string.split("=")
else :
a = string
|
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.
|
Introduction
web2py[web2py] is a free, open-source web framework for agile development of secure database-driven web applications; it is written in Python[python] and programmable in Python. web2py is a full-stack framework, meaning that it contains all the components you need to build fully functional web applications.
web2py is designed to guide a web developer to follow good software engineering practices, such as using the Model View Controller (MVC) pattern. web2py separates the data representation (the model) from the data presentation (the view) and also from the application logic and workflow (the controller). web2py provides libraries to help the developer design, implement, and test each of these three parts separately, and makes them work together.
web2py is built for security. This means that it automatically addresses many of the issues that can lead to security vulnerabilities, by following well established practices. For example, it validates all input (to prevent injections), escapes all output (to prevent cross-site scripting), renames uploaded files (to prevent directory traversal attacks). web2py takes care of main security issues, so developers have less chances of introducing vulnerabilities.
web2py includes a Database Abstraction Layer (DAL) that writes SQL[sql-w] dynamically so that you, the developer, don't have to. The DAL knows how to generate SQL transparently for SQLite[sqlite], MySQL[mysql], PostgreSQL[postgres], MSSQL[mssql], FireBird[firebird], Oracle[oracle], IBM DB2[db2], Informix[informix] and Ingres[ingresdb].
The DAL can also generate function calls for the Google Datastore when running on the Google App Engine (GAE)[gae]. Experimentally we support more databases and new ones are constantly added. Please check on the web2py web site and mailing list for more recent adapters. Once one or more database tables are defined, web2py automatically generates a fully functional web-based database administration interface to access the database and the tables.
web2py differs from other web frameworks in that it is the only framework to fully embrace the Web 2.0 paradigm, where the web is the computer. In fact, web2py does not require installation or configuration; it runs on any architecture that can run Python (Windows, Windows CE, Mac OS X, iOS, and Unix/Linux), and the development, deployment, and maintenance phases for the applications can be done via a local or remote web interface. web2py runs with CPython (the C implementation) and PyPy (Python written in Python), on Python versions 2.5, 2.6, and 2.7.
web2py provides a ticketing system for error events. If an error occurs, a ticket is issued to the user, and the error is logged for the administrator.
web2py is open source and released under the LGPL version 3 license.
Another important feature of web2py is that we, its developers, commit to maintain backward compatibility in future versions. We have done so since the first release of web2py in October, 2007. New features have been added and bugs have been fixed, but if a program worked with web2py 1.0, that program will work even better today.
Here are some examples of web2py statements that illustrate its power and simplicity. The following code:
db.define_table('person', Field('name'), Field('image', 'upload'))
creates a database table called "person" with two fields: "name", a string; and "image", something that needs to be uploaded (the actual image). If the table already exists but does not match this definition, it is altered appropriately.
Given the table defined above, the following code:
form = SQLFORM(db.person).process()
creates an insert form for this table that allows users to upload images. It also validates the submitted form, renames the uploaded image in a secure way, stores the image in a file, inserts the corresponding record in the database, prevents double submission, and eventually modifies the form itself by adding error messages if the data submitted by the user does not pass validation.
This code embeds a fully working wiki with tags, search, tag cloud, permissions, media attachments, and oembed support:
def index(): return auth.wiki()
The following code instead:
@auth.requires_permission('read','person')
def f(): ....
prevents visitors from accessing the function f unless the visitor is a member of a group whose members have permissions to "read" records of table "person". If the visitor is not logged in, the visitor gets directed to a login page (provided by default by web2py).
web2py also supports components, i.e. actions which can be loaded in a view and interact with the visitor via Ajax without re-loading the entire page. This is done via a LOAD helper which allows very modular design of applications; it is discussed in chapter 3 in the context of the wiki and, in some detail, in the last chapter of this book.
This 6th edition of the book describes web2py 2.4.1 and later versions.
Principles
Python programming typically follows these basic principles:
Don't repeat yourself (DRY).
There should be only one way of doing things.
Explicit is better than implicit.
web2py fully embraces the first two principles by forcing the developer to use sound software engineering practices that discourage repetition of code. web2py guides the developer through almost all the tasks common in web application development (creating and processing forms, managing sessions, cookies, errors, etc.).
web2py differs from other frameworks with regard to the third principle, which sometimes conflicts with the other two. In particular, web2py does not import user applications, but executes them in a predefined context. This context exposes the Python keywords, as well as the web2py keywords.
To some this may appear as magic, but it should not. Simply, in practice, some modules are already imported without you doing so. web2py is trying to avoid the annoying characteristic of other frameworks that force the developer to import the same modules at the top of every model and controller.
web2py, by importing its own modules, saves time and prevents mistakes, thus following the spirit of "don't repeat yourself" and "there should be only one way of doing things".
If the developer wishes to use other Python modules or third-party modules, those modules must be imported explicitly, as in any other Python program.
Web frameworks
At its most fundamental level, a web application consists of a set of programs (or functions) that are executed when the corresponding URL is visited. The output of the program is returned to the visitor and rendered by the browser.
The purpose of web frameworks is to allow developers to build new apps quickly, easily and without mistakes. This is done by providing APIs and tools that reduce and simplify the amount of coding that is required.
The two classic approaches for developing web applications are:
The first model is the one that was followed, for example, by early CGI scripts. The second model is followed, for example, by PHP[php] (where the code is in PHP, a C-like language), ASP (where the code is in Visual Basic), and JSP (where the code is in Java).
Here is an example of a PHP program that, when executed, retrieves data from a database and returns an HTML page showing the selected records:
<html><body><h1>Records</h1><?
mysql_connect(localhost,username,password);
@mysql_select_db(database) or die( "Unable to select database");
$query="SELECT * FROM contacts";
$result=mysql_query($query);
mysql_close();
$i=0;
while ($i < mysql_numrows($result)) {
$name=mysql_result($result,$i,"name");
$phone=mysql_result($result,$i,"phone");
echo "<b>$name</b><br>Phone:$phone<br /><br /><hr /><br />";
$i++;
}
?></body></html>
The problem with this approach is that code is embedded into HTML, but the very same code also needs to generate additional HTML and to generate SQL statements to query the database, entangling multiple layers of the application and making it difficult to read and maintain. The situation is even worse for Ajax applications, and the complexity grows with the number of pages (files) that make up the application.
The functionality of the above example can be expressed in web2py with two lines of Python code:
def index():
return HTML(BODY(H1('Records'), db().select(db.contacts.ALL)))
In this simple example, the HTML page structure is represented programmatically by the HTML, BODY, and H1 objects; the database db is queried by the select command; finally, everything is serialized into HTML. Notice that db is not a keyword but a user defined variable. We will use this name consistently to refer to a database connection to avoid confusion.
Web frameworks are typically categorized as one of two types: A "glued" framework is built by assembling (gluing together) several third-party components. A "full-stack" framework is built by creating components designed specifically to be tightly integrated and work together.
web2py is a full-stack framework. Almost all of its components are built from scratch and are designed to work together, but they function just as well outside of the complete web2py framework. For example, the Database Abstraction Layer (DAL) or the template language can be used independently of the web2py framework by importing gluon.dal or gluon.template into your own Python applications. gluon is the name of the web2py module that contains system libraries. Some web2py libraries, such as building and processing forms from database tables, have dependencies on other portions of web2py. web2py can also work with third-party Python libraries, including other template languages and DALs, but they will not be as tightly integrated as the original components.
Model-View-Controller
web2py encourages the developer to separate data representation (the model), data presentation (the view) and the application workflow (the controller). Let's consider again the previous example and see how to build a web2py application around it. Here is an example of the web2py MVC edit interface:
The typical workflow of a request in web2py is described in the following diagram:
In the diagram:
The Server can be the web2py built-in web server or a third-party server, such as Apache. The Server handles multi-threading.
"main" is the main WSGI application. It performs all common tasks and wraps user applications. It deals with cookies, sessions, transactions, URL routing and reverse routing, and dispatching.
It can serve and stream static files if the web server is not doing it yet.
The Models, Views and Controller components make up the user application.
Multiple applications can be hosted in the same web2py instance.
The dashed arrows represent communication with the database engine(s). The database queries can be written in raw SQL (discouraged) or by using the web2py Database Abstraction Layer (recommended), so that web2py application code is not dependent on the specific database engine.
The dispatcher maps the requested URL to a function call in the controller. The output of the function can be a string or a dictionary of symbols (a hash table). The data in the dictionary is rendered by a view. If the visitor requests an HTML page (the default), the dictionary is rendered into an HTML page. If the visitor requests the same page in XML, web2py tries to find a view that can render the dictionary in XML. The developer can create views to render pages in any of the already supported protocols (HTML, XML, JSON, RSS, CSV, and RTF) or in additional custom protocols.
All calls are wrapped into a transaction, and any uncaught exception causes the transaction to be rolled back. If the request succeeds, the transaction is committed.
web2py also handles sessions and session cookies automatically, and when a transaction is committed, the session is also stored, unless specified otherwise.
It is possible to register recurrent tasks (via cron) to run at scheduled times and/or after the completion of certain actions. In this way it is possible to run long and compute-intensive tasks in the background without slowing down navigation.
Here is a minimal and complete MVC application, consisting of three files:
"db.py" is the model:
db = DAL('sqlite://storage.sqlite')
db.define_table('contact',
Field('name'),
Field('phone'))
It connects to the database (in this example a SQLite database stored in the storage.sqlite file) and defines a table called contact. If the table does not exist, web2py creates it and, transparently and in the background, generates SQL code in the appropriate SQL dialect for the specific database engine used. The developer can see the generated SQL but does not need to change the code if the database back-end, which defaults to SQLite, is replaced with MySQL, PostgreSQL, MSSQL, FireBird, Oracle, DB2, Informix, Interbase, Ingres, and the Google App Engine (both SQL and NoSQL).
Once a table is defined and created, web2py also generates a fully functional web-based database administration interface, called appadmin, to access the database and the tables.
"default.py" is the controller:
def contacts():
grid=SQLFORM.grid(db.contact, user_signature=False)
return locals()
In web2py, URLs are mapped to Python modules and function calls. In this case, the controller contains a single function (or "action") called contacts. An action may return a string (the returned web page) or a Python dictionary (a set of key:value pairs) or the set of local variables (as in this example). If the function returns a dictionary, it is passed to a view with the same name as the controller/function, which in turn renders the page. In this example, the function contacts generates a select/search/create/update/delete grid for table db.contact and returns the grid to the view.
"default/contacts.html" is the view:
{{extend 'layout.html'}}
<h1>Manage My Contacts</h1>
{{=grid}}
This view is called automatically by web2py after the associated controller function (action) is executed. The purpose of this view is to render the variables in the returned dictionary (in our case grid) into HTML. The view file is written in HTML, but it embeds Python code delimited by the special {{ and }} delimiters. This is quite different from the PHP code example, because the only code embedded into the HTML is "presentation layer" code. The "layout.html" file referenced at the top of the view is provided by web2py and constitutes the basic layout for all web2py applications. The layout file can easily be modified or replaced.
Why web2py
web2py is one of many web application frameworks, but it has compelling and unique features. web2py was originally developed as a teaching tool, with the following primary motivations:
Easy for users to learn server-side web development without compromising functionality. For this reason, web2py requires no installation and no configuration, has no dependencies (except for the source code distribution, which requires Python 2.5 and its standard library modules), and exposes most of its functionality via a Web interface, including an Integrated Development Environment with Debugger and database interface.
web2py has been stable from day one because it follows a top-down design; i.e., its API was designed before it was implemented. Even as new functionality has been added, web2py has never broken backwards compatibility, and it will not break compatibility when additional functionality is added in the future.
web2py proactively addresses the most important security issues which plague many modern web applications, as determined by OWASP[owasp]below.
web2py is lightweight. Its core libraries, including the Database Abstraction Layer, the template language, and all the helpers amount to 1.4MB. The entire source code including sample applications and images amounts to 10.4MB.
web2py has a small footprint and is very fast. It uses the Rocket[rocket]WSGI web server developed by Timothy Farrell. It is as fast as Apache with mod_wsgi, and supports SSL and IPv6.
web2py uses Python syntax for models, controllers, and views, but does not import models and controllers (as all the other Python frameworks do) - instead it executes them. This means that apps can be installed, uninstalled, and modified without having to restart the web server (even in production), and different apps can coexist without their modules interfering with one another.
web2py uses a Database Abstraction Layer (DAL) instead of an Object Relational Mapper (ORM). From a conceptual point of view, this means that different database tables are mapped into different instances of one Tableclass and not into different classes, while records are mapped into instances of oneRowclass, not into instances of the corresponding table class. From a practical point of view, it means that SQL syntax maps almost one-to-one into DAL syntax, and there is no complex metaclass programming going on under the hood as in popular ORMs, which would add latency.
Here is a screenshot of the main web2py admin interface:
Security
The Open Web Application Security Project[owasp] (OWASP) is a free and open worldwide community focused on improving the security of application software.
OWASP has listed the top ten security issues that put web applications at risk. That list is reproduced here, along with a description of how each issue is addressed by web2py:
cross site scripting"Cross Site Scripting (XSS): XSS flaws occur whenever an application takes user supplied data and sends it to a web browser without first validating or encoding that content. XSS allows attackers to execute scripts in the victim's browser which can hijack user sessions, deface web sites, possibly introduce worms, etc."web2py, by default, escapes all variables rendered in the view, preventing XSS.
injection flaws"Injection Flaws: Injection flaws, particularly SQL injection, are common in web applications. Injection occurs when user-supplied data is sent to an interpreter as part of a command or query. The attacker's hostile data tricks the interpreter into executing unintended commands or changing data."web2py includes a Database Abstraction Layer that makes SQL injection impossible. Normally, SQL statements are not written by the developer. Instead, SQL is generated dynamically by the DAL, ensuring that all inserted data is properly escaped.
malicious file execution"Malicious File Execution: Code vulnerable to remote file inclusion (RFI) allows attackers to include hostile code and data, resulting in devastating attacks, such as total server compromise."web2py allows only exposed functions to be executed, preventing malicious file execution. Imported functions are never exposed; only actions are exposed. web2py uses a Web-based administration interface which makes it very easy to keep track of what is exposed and what is not.
insecure object reference"Insecure Direct Object Reference: A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, database record, or key, as a URL or form parameter. Attackers can manipulate those references to access other objects without authorization."web2py does not expose any internal objects; moreover, web2py validates all URLs, thus preventing directory traversal attacks. web2py also provides a simple mechanism to create forms that automatically validate all input values.
CSRF"Cross Site Request Forgery (CSRF): A CSRF attack forces a logged-on victim's browser to send a pre-authenticated request to a vulnerable web application, which then forces the victim's browser to perform a hostile action to the benefit of the attacker. CSRF can be as powerful as the web application that it attacks."web2py prevents CSRF as well as accidental double submission of forms by assigning a one-time random token to each form. Moreover web2py uses UUID for session cookie.
information leakageimproper error handling"Information Leakage and Improper Error Handling: Applications can unintentionally leak information about their configuration, internal workings, or violate privacy through a variety of application problems. Attackers use this weakness to steal sensitive data, or conduct more serious attacks."web2py includes a ticketing system. No error can result in code being exposed to the users. All errors are logged and a ticket is issued to the user that allows error tracking. But errors and source code are accessible only to the administrator.
"Broken Authentication and Session Management: Account credentials and session tokens are often not properly protected. Attackers compromise passwords, keys, or authentication tokens to assume other users' identities." web2py provides a built-in mechanism for administrator authentication, and it manages sessions independently for each application. The administrative interface also forces the use of secure session cookies when the client is not "localhost". For applications, it includes a powerful Role Based Access Control API.
cryptographic store"Insecure Cryptographic Storage: Web applications rarely use cryptographic functions properly to protect data and credentials. Attackers use weakly protected data to conduct identity theft and other crimes, such as credit card fraud."web2py uses the MD5 or the HMAC+SHA-512 hash algorithms to protect stored passwords. Other algorithms are also available.
secure communications"Insecure Communications: Applications frequently fail to encrypt network traffic when it is necessary to protect sensitive communications."web2py includes the SSL-enabled[ssl]Rocket WSGI server, but it can also use Apache or Lighttpd and mod_ssl to provide SSL encryption of communications.
access restriction"Failure to Restrict URL Access: Frequently an application only protects sensitive functionality by preventing the display of links or URLs to unauthorized users. Attackers can use this weakness to access and perform unauthorized operations by accessing those URLs directly."web2py maps URL requests to Python modules and functions. web2py provides a mechanism for declaring which functions are public and which require authentication and authorization. The included Role Based Access Control API allow developers to restrict access to any function based on login, group membership or group based permissions. The permissions are very granular and can be combined with database filters to allow, for example, to give access to specific tables and/or records. web2py also allows digitally signed URL and provides API to digitally sign Ajax callbacks.
web2py was reviewed for security and you can find the result of the review in ref.[pythonsecurity].
In the box
You can download web2py from the official web site:
http://www.web2py.com
web2py is composed of the following components:
libraries: provide core functionality of web2py and are accessible programmatically.
web server: the Rocket WSGI web server.
the adminapplication: used to create, design, and manage other web2py applications.adminprovides a complete web-based Integrated Development Environment (IDE) for building web2py applications. It also includes other functionality, such as web-based testing and a web-based shell.
the examplesapplication: contains documentation and interactive examples.examplesis a clone of the official web2py.com web site, and includes epydoc documentation.
the welcomeapplication: the basic scaffolding template for any other application. By default it includes a pure CSS cascading menu and user authentication (discussed in Chapter 9).
web2py is distributed in source code, and in binary form for Microsoft Windows and for Mac OS X.
The source code distribution can be used in any platform where Python runs and includes the above-mentioned components. To run the source code, you need Python 2.5, 2.6 or 2.7 pre-installed on the system. You also need one of the supported database engines installed. For testing and light-demand applications, you can use the SQLite database, included with Python 2.7.
The binary versions of web2py (for Windows and Mac OS X) include a Python 2.7 interpreter and the SQLite database. Technically, these two are not components of web2py. Including them in the binary distributions enables you to run web2py out of the box.
The following image depicts the overall web2py structure:
At the bottom we find the interpreter. Moving up we find the web server (rocket), the libraries, and the applications. Each application consists for its own MVC design (models, controllers, views, modules, languages, databases, and static files). Each application includes it own database administration code (appadmin). Every web2py instance ships with three applications: welcome (the scaffolding app), admin (the web based IDE), and examples (copy of website and examples).
About this book
This book includes the following chapters, besides this introduction:
Chapter 2 is a minimalist introduction to Python. It assumes knowledge of both procedural and object-oriented programming concepts such as loops, conditions, function calls and classes, and covers basic Python syntax. It also covers examples of Python modules that are used throughout the book. If you already know Python, you may skip Chapter 2.
Chapter 3 shows how to start web2py, discusses the administrative interface, and guides the reader through various examples of increasing complexity: an application that returns a string, a counter application, an image blog, and a full blown wiki application that allows image uploads and comments, provides authentication, authorization, web services and an RSS feed. While reading this chapter, you may need to refer to Chapter 2 for general Python syntax and to the following chapters for a more detailed reference about the functions that are used.
Chapter 4 covers more systematically the core structure and libraries: URL mapping, request, response, sessions, caching, scheduler, cron, internationalization and general workflow.
Chapter 5 is a reference for the template language used to build views. It shows how to embed Python code into HTML, and demonstrates the use of helpers (objects that can generate HTML).
Chapter 6 covers the Database Abstraction Layer, or DAL. The syntax of the DAL is presented through a series of examples.
Chapter 7 covers forms, form validation and form processing. FORM is the low level helper for form building. SQLFORM is the high level form builder. In Chapter 7 we also discuss Create/Read/Update/Delete (CRUD) API.
Chapter 8 covers communication features as retrieving and sending emails and SMSes.
Chapter 9 covers authentication, authorization and the extensible Role-Based Access Control mechanism available in web2py. Mail configuration and CAPTCHA are also discussed here, since they are used for authentication. In the third edition of the book we have added extensive coverage of integration with third-party authentication mechanisms such as OpenID, OAuth, Google, Facebook, LinkedIn, etc.
Chapter 10 is about creating web services in web2py. We provide examples of integration with the Google Web Toolkit via Pyjamas, and with Adobe Flash via PyAMF.
Chapter 11 is about web2py and jQuery recipes. web2py is designed mainly for server-side programming, but it includes jQuery, since we have found it to be the best open-source JavaScript library available for effects and Ajax. In this chapter, we discuss how to effectively use jQuery with web2py.
Chapter 12 discusses web2py components and plugins as a way to build modular applications. We provide an example of a plugin that implements many commonly used functionality, such as charting, comments, and tagging.
Chapter 13 is about production deployment of web2py applications. We specifically discuss the deployment on a LAMP web server (which we consider the main deployment alternative). We discuss alternative web servers, and configuration of the PostgreSQL database. We discuss running as a service on a Microsoft Windows environment, and deployment on some specific platforms including Google Applications Engine, Heroku, and PythonAnywhere. In this chapter, we also discuss security and scalability issues.
Chapter 14 contains a variety of other recipes to solve specific tasks, including upgrades, geocoding, pagination, the Twitter API, and more.
Chapter 15 has information and helping and contributing to the project, with topics such as making bug reports and contributing changes to the code.
This book only covers basic web2py functionalities and the API that ships with web2py. This book does not cover web2py appliances (i.e. ready made applications).
You can download web2py appliances from the corresponding web site [appliances].
This book has been written using the MARKMIN syntax See Chapter 5 and automatically converted to HTML, LaTeX and PDF.
Support
The main support channel is the usergroup[usergroup], with dozens of posts every day. Even if you're a newbie, don't hesitate to ask - we'll be pleased to help you. There is also a formal issue tracker system on http://code.google.com/p/web2py/issues . Last but not least, you can have professional support (see the web site for details).
Contribute
Any help is really appreciated. You can help other users on the user group, or by directly submitting patches on the program (at the GitHub site https://github.com/web2py/web2py). Even if you find a typo on this book, or have an improvement on it, the best way to help is by patching the book itself (which is under the source folder of the repository at https://github.com/mdipierro/web2py-book). For more information on contributing, please see Chapter 15
Elements of style
PEP8 [style] contains good style practices when programming with Python. You will find that web2py does not always follow these rules. This is not because of omissions or negligence; it is our belief that the users of web2py should follow these rules and we encourage it. We chose not to follow some of those rules when defining web2py helper objects in order to minimize the probability of name conflict with objects defined by the user.
For example, the class that represents a <div> is called DIV, while according to the Python style reference it should have been called Div. We believe that, for this specific example that using an all-upper-case "DIV" is a more natural choice. Moreover, this approach leaves programmers free to create a class called "Div" if they choose to do so. Our syntax also maps naturally into the DOM notation of most browsers (including, for example, Firefox).
According to the Python style guide, all-upper-case strings should be used for constants and not variables. Continuing with our example, even considering that DIV is a class, it is a special class that should never be modified by the user because doing so would break other web2py applications. Hence, we believe this qualifies the DIV class as something that should be treated as a constant, further justifying our choice of notation.
In summary, the following conventions are followed:
HTML helpers and validators are all upper case for the reasons discussed above (for example DIV,A,FORM,URL).
The translator object Tis upper case despite the fact that it is an instance of a class and not a class itself. Logically the translator object performs an action similar to the HTML helpers, it affects rendering part of the presentation. Also,Tneeds to be easy to locate in the code and must have a short name.
DAL classes follow the Python style guide (first letter capitalized), for example Table,Field,Query,Row,Rows, etc.
In all other cases we believe we have followed, as much as possible, the Python Style Guide (PEP8). For example all instance objects are lower-case (request, response, session, cache), and all internal classes are capitalized.
In all the examples of this book, web2py keywords are shown in bold, while strings and comments are shown in italic.
License
web2py is licensed under the LGPL version 3 License. The full text of the license is available in ref.[lgpl3].
In accordance with LGPL you may:
redistribute web2py with your apps (including official web2py binary versions)
release your applications which use official web2py libraries under any license you wish
Yet you must:
make clear in the documentation that your application uses web2py
release any modification of the web2py libraries under the LGPLv3 license
The license includes the usual disclaimer:
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
Earlier versions
Earlier versions of web2py, 1.0.*-1.90.*, were released under the GPL2 license plus a commercial exception which, for practical purposes, was very similar to the current LGPLv3.
Third party software distributed with web2py
web2py contains third party software under the gluon/contrib/ folder and various JavaScript and CSS files. These files are distributed with web2py under their original licenses, as stated in the files.
Acknowledgments
web2py was originally developed by and copyrighted by Massimo Di Pierro. The first version (1.0) was released in October, 2007. Since then it has been adopted by many users, some of whom have also contributed bug reports, testing, debugging, patches, and proofreading of this book.
Some of the major developers and contributors are, in alphabetical order by first name:
Adam Bryzak, Adam Gojdas, Adrian Klaver, Alain Boulch, Alan Etkin, Alec Taylor, Alexandre Andrade, Alexey Nezhdanov, Alvaro Justen, Anand Vaidya, Anatoly Belyakov, Ander Arbelaiz, Anders Roos, Andrew Replogle, Andrew Willimott, Angelo Compagnucci, Angelo and Villas, Annet Vermeer, Anthony Bastardi, Anton Muecki, Antonio Ramos, Arun Rajeevan, Attila Csipa, Ben Goosman, Ben Reinhart, Benjamin, Bernd Rothert, Bill Ferret, Blomqvist, Boris Manojlovic, Branko Vukelic, Brent Zeiben, Brian Cottingham, Brian Harrison, Brian Meredyk, Bruno Rocha, CJ Lazell, Caleb Hattingh, Carlos Galindo, Carlos Hanson, Carsten Haese, Cedric Meyer, Charles Law, Charles Winebrinner, Chris Clark, Chris May, Chris Sanders, Christian Foster Howes, Christopher Smiga, Christopher Steel, Clavin Sim, Cliff Kachinske, Corne Dickens, Craig Younkins, Dan McGee, Dan Ragubba, Dane Wright, Danny Morgan, Daniel Gonz, Daniel Haag, Daniel Lin, Dave Stoll, David Adley, David Harrison, David Lin, David Marko, David Wagner, Denes Lengyel, Diaz Luis, Dirk Krause, Dominic Koenig, Doug Warren, Douglas Philips, Douglas Soares de Andrade, Douglas and Alan, Dustin Bensing, Elcio Ferreira, Eric Vicenti, Erwin Olario, Falko Krause, Farsheed Ashouri, Felipe Meirelles, Flavien Scheurer, Fran Boon, Francisco Gama, Fred Yanowski, Friedrich Weber, Gabriele Alberti, Gergely Kontra, Gergely Peli, Gerley Kontra, Gilson Filho, Glenn Caltech, Graham Dumpleton, Gregory Benjamin, Gustavo Di Pietro, Gyuris Szabolcs, Hamdy Abdel-Badeea, Hans C. v. Stockhausen, Hans Donner, Hans Murx, Huaiyu Wang, Ian Reinhart Geiser, Iceberg, Igor Gassko, Ismael Serratos, Jan Beilicke, Jay Kelkar, Jeff Bauer, Jesus Matrinez, Jim Karsten, Joachim Breitsprecher, Joakim Eriksson, Joe Barnhart, Joel Carrier, Joel Samuelsson, John Heenan, Jon Romero, Jonas Rundberg, Jonathan Benn, Jonathan Lundell, Jose Jachuf, Joseph Piron, Josh Goldfoot, Josh Jaques, Jose Vicente de Sousa, Jurgis Pralgauskis, Keith Yang, Kenji Hosoda, Kenneth Lundstr, Kirill Spitsin, Kyle Smith, Larry Weinberg, Limodou, Loren McGinnis, Louis DaPrato, Luca De Alfaro, Luca Zachetti, Lucas D'Avila, Madhukar R Pai, Manuele Presenti, Marc Abramowitz, Marcel Hellkamp, Marcel Leuthi, Marcello Della Longa, Margaret Greaney, Maria Mitica, Mariano Reingart, Marin Prajic, Marin Pranji, Marius van Niekerk, Mark Kirkwood, Mark Larsen, Mark Moore, Markus Gritsch, Mart Senecal, Martin Hufsky, Martin Mulone, Martin Weissenboeck, Mateusz Banach, Mathew Grabau, Mathieu Clabaut, Matt Doiron, Matthew Norris, Michael Fig, Michael Herman, Michael Howden, Michael Jursa, Michael Toomim, Michael Willis, Michele Comitini, Miguel Goncalves, Miguel Lopez, Mike Amy, Mike Dickun, Mike Ellis, Mike Pechkin, Milan Melena, Muhammet Aydin, Napoleon Moreno, Nathan Freeze, Niall Sweeny, Niccolo Polo, Nick Groenke, Nick Vargish, Nico de Groot, Nico Zanferrari, Nicolas Bruxer, Nik Klever, Olaf Ferger, Oliver Dain, Olivier Roch Vilato, Omi Chiba, Ondrej Such, Ont Rif, Oscar Benjamin, Osman Masood, Ovidio Marinho Falcao Neto, Pai, Panos Jee, Paolo Betti, Paolo Caruccio, Paolo Gasparello, Paolo Valleri, Patrick Breitenbach, Pearu Peterson, Peli Gergely, Pete Hunt, Peter Kirchner, Phyo Arkar Lwin, Pierre Thibault, Pieter Muller, Piotr Banasziewicz, Ramjee Ganti, Richard Gordon, Richard Ree, Robert Kooij, Robert Valentak, Roberto Perdomo, Robin Bhattacharyya, Roman Bataev, Ron McOuat, Ross Peoples, Ruijun Luo, Running Calm, Ryan Seto, Salomon Derossi, Sam Sheftel, Scott Roberts, Sebastian Ortiz, Sergey Podlesnyi, Sharriff Aina, Simone Bizzotto, Sriram Durbha, Sterling Hankins, Stuart Rackham, Telman Yusupov, Thadeus Burgess, Thomas Dallagnese, Tim Farrell, Tim Michelsen, Tim Richardson, Timothy Farrell, Tito Garrido, Tyrone Hattingh, Vasile Ermicioi, Vidul Nikolaev Petrov, Vidul Petrov, Vinicius Assef, Vladimir Donnikov, Vladyslav Kozlovsky, Vladyslav Kozlovskyy, Wang Huaiyu, Wen Gong, Wes James, Will Stevens, Yair Eshel, Yarko Tymciurak, Yoshiyuki Nakamura, Younghyun Jo, Zahariash.
I am sure I forgot somebody, so I apologize.
I particularly thank Anthony, Jonathan, Mariano, Bruno, Vladyslav, Martin, Nathan, Simone, Thadeus, Tim, Iceberg, Denes, Hans, Christian, Fran and Patrick for their major contributions to web2py and Anthony, Alvaro, Brian, Bruno, Denes, Dane Denny, Erwin, Felipe, Graham, Jonathan, Hans, Kyle, Mark, Margaret, Michele, Nico, Richard, Roberto, Robin, Roman, Scott, Shane, Sharriff, Sriram, Sterling, Stuart, Thadeus, Wen (and others) for proofreading various versions of this book. Their contribution was invaluable. If you find any errors in this book, they are exclusively my fault, probably introduced by a last-minute edit. I also thank Ryan Steffen of Wiley Custom Learning Solutions for help with publishing the first edition of this book.
web2py contains code from the following authors, whom I would like to thank:
Guido van Rossum for Python[python], Peter Hunt, Richard Gordon, Timothy Farrell for the Rocket[rocket] web server, Christopher Dolivet for EditArea[editarea], Bob Ippolito for simplejson[simplejson], Simon Cusack and Grant Edwards for pyRTF[pyrtf], Dalke Scientific Software for pyRSS2Gen[pyrss2gen], Mark Pilgrim for feedparser[feedparser], Trent Mick for markdown2[markdown2], Allan Saddi for fcgi.py, Evan Martin for the Python memcache module[memcache], John Resig for jQuery[jquery].
I thank Helmut Epp (provost of DePaul University), David Miller (Dean of the College of Computing and Digital Media of DePaul University), and Estia Eichten (Member of MetaCryption LLC), for their continuous trust and support.
Finally, I wish to thank my wife, Claudia, and my son, Marco, for putting up with me during the many hours I have spent developing web2py, exchanging emails with users and collaborators, and writing this book. This book is dedicated to them.
top
|
Still normal search with latin and russian translit(!)
$ search sumka
using config file '/etc/sphinx/sphinx.conf'...
index 'test1': query 'sumka ': returned 636 matches of 636 total in 0.000 sec
displaying matches:
1. document=154143, weight=1660, name=Сумка Sony LCS-MS10 Gray Alpha ТекÑÑ‚Ð¸Ð»ÑŒÐ½Ð°Ñ Ñумка Ð´Ð»Ñ Ñ„Ð¾Ñ‚Ð¾ÐºÐ°Ð¼ÐµÑ€Ñ‹ Alpha Серый цвет, casual style (Ñумка почтальона) [LCSMS10H.AE], description_short=Сумка Sony LCS-MS10 Gray Alpha ТекÑÑ‚Ð¸Ð»ÑŒÐ½Ð°Ñ Ñумка Ð´Ð»Ñ Ñ„Ð¾Ñ‚Ð¾ÐºÐ°Ð¼ÐµÑ€Ñ‹ Alpha Серый цвет, casual style (Ñумка почтальона) [LCSMS10H.AE]
...
$ search Ñумка
using config file '/etc/sphinx/sphinx.conf'...
index 'test1': query 'Ñумка ': returned 0 matches of 0 total in 0.000 sec
words:
1. 'Ñумка': 0 documents, 0 hits
Sound like charset problem here, but I have utf8 in mysql and query
mysql> show variables like "character%";
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
mysql> show variables like "collation%";
+----------------------+-----------------+
| Variable_name | Value |
+----------------------+-----------------+
| collation_connection | utf8_general_ci |
| collation_database | utf8_general_ci |
| collation_server | utf8_unicode_ci |
+----------------------+-----------------+
$ file words
words: UTF-8 Unicode text
$ cat words | search --stdin
using config file '/etc/sphinx/sphinx.conf'...
index 'test1': query 'Ñумка
': returned 0 matches of 0 total in 0.000 sec
words:
1. 'Ñумка': 0 documents, 0 hits
This is also true for php client and sphinx mysql like client.
Full sphinx configuration is here, but quote of significient part:
source src1
{
...
sql_query_pre = SET NAMES utf8
sql_query_pre = SET CHARACTER SET utf8
...
}
index test1
{
...
charset_type = utf-8
...
}
I found only one similar problem, but there was latin1 charset in db.
Programs versions is:
mysql Ver 14.14 Distrib 5.5.20, for Linux (x86_64) using readline 5.1
Sphinx 2.0.6-id64-release (r3473)
centos 5.8
UPDATE
Add charset_table to config with tables from http://sphinxsearch.com/wiki/doku.php?id=charset_tables#cyrillic but still no good.
Also I installed Sphinx 2.0.5-release (r3308) on my local gentoo and it work with cyrillic queries out of the box.
|
To store data, object reference to a variable is very easy in python. For example, to assign an integer 5 to a
a=5
Same thing goes to string
str="hello world"
Assign data to a data structured variable, let say list,
L=[1,2,3,4,5]
Even assign a function to a variable.
import sys
wstderr=sys.stderr.write
wstderr("hello world\n")
Observed that all of them uses equal sign, but CAREFUL! Sometimes, they doesn’t work the same way as you expect them to.
In python, some variables are immutable and some are not. For example, string and tuple are immutable, but list and dictionary accept dynamic changes.
Lets look at string in python
>>> str="my snake bites"
>>> str[4]
'n'
>>> str[4]='f'
Traceback (most recent call last):
File "", line 1, in
TypeError: 'str' object does not support item assignment
You can’t cannot change value of a particular character in string, they are immutable. The value “my snake bites” is actually store in a new blocks of memory and str will be refers to that particular blocks of memory.
When you do this:
str2=str
The content of str is copied to str2, both of them are independent.
Lets look at list now, you are allow to delete or append data dynamically during runtime.
L=[1,2,3,4,5]
IMPORTANT: The value will be stored into a range of memory blocks, and what if you do this?
L2=L
It make L2 refers to the same memory blocks where L points to. Let see!
>>> L=[1,2,3,4,5]
>>> L2=L
>>> L2.append(6)
>>> print L
[1, 2, 3, 4, 5, 6]
Append values to L2 reflects to L too, they are refers to the same blocks of memory.
OMG! what if I wanna COPY the value from L to L2?
>>> L2=L[0:]
>>> print L2
[1, 2, 3, 4, 5, 6]
>>> L2.append(7)
>>> print L
[1, 2, 3, 4, 5, 6]
>>> print L2
[1, 2, 3, 4, 5, 6, 7]
How about dictionary?
You can use copy() method for that.
>>> D=dict()
>>> D[1]=10
>>> D[2]=20
>>> print D
{1: 10, 2: 20}
>>> D2=D.copy()
>>> print D2
{1: 10, 2: 20}
>>> D2[3]=30
>>> print D2
{1: 10, 2: 20, 3: 30}
>>> print D
{1: 10, 2: 20}
Although all of them uses equal sign, but they act differently, so bare in mind while dive in python.
|
I wrote IDL code:
zz= [ 0, 5, 10, 15, 30, 50, 90, 100, 500]
uz= [ 20, 20, 20, 30, 60, 90, 30, -200, -200]*(-1.)
zp= findgen(120)*500+500
up= spline((zz-10.),uz,(zp/1000.0))
print, up
and IDL gave me the values of up array from about -20 to 500
.The same I did in Python
import numpy as npy
zz = npy.array([ 0, 5, 10, 15, 30, 50, 90, 100, 500])
uz = npy.array([ 20, 20, 20, 30, 60, 90, 30, -200, -200])*(-1.)
zp = npy.arange(0,120)*500+500
from scipy.interpolate import interp1d
cubic_interp_u = interp1d(zz-10., uz, kind='cubic')
up = cubic_interp_u(zp/1000)
print up
and it gave me up with values from about -20 to -160. Any idea? Thanks in advance!
|
What's the best way to validate that an IP entered by the user is valid? It comes in as a string.
Don't parse it. Just ask.
import socket
try:
socket.inet_aton(addr)
# legal
except socket.error:
# Not legal
The IPy module (a module designed for dealing with IP addresses) will throw a ValueError exception for invalid addresses.
>>> from IPy import IP
>>> IP('127.0.0.1')
IP('127.0.0.1')
>>> IP('277.0.0.1')
Traceback (most recent call last):
...
ValueError: '277.0.0.1': single byte must be 0 <= byte < 256
>>> IP('foobar')
Traceback (most recent call last):
...
ValueError: invalid literal for long() with base 10: 'foobar'
However, like Dustin's answer, it will accept things like "4" and "192.168" since, as mentioned, these are valid representations of IP addresses.
If you're using Python 3.3 or later, it now includes the ipaddress module:
>>> import ipaddress
>>> ipaddress.ip_address('127.0.0.1')
IPv4Address('127.0.0.1')
>>> ipaddress.ip_address('277.0.0.1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.3/ipaddress.py", line 54, in ip_address
address)
ValueError: '277.0.0.1' does not appear to be an IPv4 or IPv6 address
>>> ipaddress.ip_address('foobar')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.3/ipaddress.py", line 54, in ip_address
address)
ValueError: 'foobar' does not appear to be an IPv4 or IPv6 address
def is_valid_ip(ip):
"""Validates IP addresses.
"""
return is_valid_ipv4(ip) or is_valid_ipv6(ip)
IPv4:
def is_valid_ipv4(ip):
"""Validates IPv4 addresses.
"""
pattern = re.compile(r"""
^
(?:
# Dotted variants:
(?:
# Decimal 1-255 (no leading 0's)
[3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2}
|
0x0*[0-9a-f]{1,2} # Hexadecimal 0x0 - 0xFF (possible leading 0's)
|
0+[1-3]?[0-7]{0,2} # Octal 0 - 0377 (possible leading 0's)
)
(?: # Repeat 0-3 times, separated by a dot
\.
(?:
[3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2}
|
0x0*[0-9a-f]{1,2}
|
0+[1-3]?[0-7]{0,2}
)
){0,3}
|
0x0*[0-9a-f]{1,8} # Hexadecimal notation, 0x0 - 0xffffffff
|
0+[0-3]?[0-7]{0,10} # Octal notation, 0 - 037777777777
|
# Decimal notation, 1-4294967295:
429496729[0-5]|42949672[0-8]\d|4294967[01]\d\d|429496[0-6]\d{3}|
42949[0-5]\d{4}|4294[0-8]\d{5}|429[0-3]\d{6}|42[0-8]\d{7}|
4[01]\d{8}|[1-3]\d{0,9}|[4-9]\d{0,8}
)
$
""", re.VERBOSE | re.IGNORECASE)
return pattern.match(ip) is not None
IPv6:
def is_valid_ipv6(ip):
"""Validates IPv6 addresses.
"""
pattern = re.compile(r"""
^
\s* # Leading whitespace
(?!.*::.*::) # Only a single whildcard allowed
(?:(?!:)|:(?=:)) # Colon iff it would be part of a wildcard
(?: # Repeat 6 times:
[0-9a-f]{0,4} # A group of at most four hexadecimal digits
(?:(?<=::)|(?<!::):) # Colon unless preceeded by wildcard
){6} #
(?: # Either
[0-9a-f]{0,4} # Another group
(?:(?<=::)|(?<!::):) # Colon unless preceeded by wildcard
[0-9a-f]{0,4} # Last group
(?: (?<=::) # Colon iff preceeded by exacly one colon
| (?<!:) #
| (?<=:) (?<!::) : #
) # OR
| # A v4 address with NO leading zeros
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]?\d)
(?: \.
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]?\d)
){3}
)
\s* # Trailing whitespace
$
""", re.VERBOSE | re.IGNORECASE | re.DOTALL)
return pattern.match(ip) is not None
The IPv6 version uses "
I found some links discussing how to parse IPv6 addresses with regex:
Finally managed to write a pattern that passes all tests, and that I am also happy with.
import socket
def is_valid_ipv4_address(address):
try:
socket.inet_pton(socket.AF_INET, address)
except AttributeError: # no inet_pton here, sorry
try:
socket.inet_aton(address)
except socket.error:
return False
return address.count('.') == 3
except socket.error: # not a valid address
return False
return True
def is_valid_ipv6_address(address):
try:
socket.inet_pton(socket.AF_INET6, address)
except socket.error: # not a valid address
return False
return True
I think this would do it...
def validIP(address):
parts = address.split(".")
if len(parts) != 4:
return False
for item in parts:
if not 0 <= int(item) <= 255:
return False
return True
From Python 3.4 on, the best way to check if an IPv6 or IPv4 address is correct is to use the module
Example :
#!/usr/bin/env python
import ipaddr
import sys
try:
ip = ipaddr.ip_address(sys.argv[1])
print '%s is a correct IP%s address.' % (ip, ip.version)
except ValueError:
print 'address/netmask is invalid: %s' % sys.argv[1]
except:
print 'Usage : %s ip' % sys.argv[0]
I have to give a great deal of credit to Markus Jarderot for his post - the majority of my post is inspired from his.
I found that Markus' answer still fails some of the IPv6 examples in the Perl script referenced by his answer.
Here is my regex that passes all of the examples in that Perl script:
r"""^
\s* # Leading whitespace
# Zero-width lookaheads to reject too many quartets
(?:
# 6 quartets, ending IPv4 address; no wildcards
(?:[0-9a-f]{1,4}(?::(?!:))){6}
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# 0-5 quartets, wildcard, ending IPv4 address
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?
(?:::(?!:))
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# 0-4 quartets, wildcard, 0-1 quartets, ending IPv4 address
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?
(?:::(?!:))
(?:[0-9a-f]{1,4}(?::(?!:)))?
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# 0-3 quartets, wildcard, 0-2 quartets, ending IPv4 address
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?
(?:::(?!:))
(?:[0-9a-f]{1,4}(?::(?!:))){0,2}
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# 0-2 quartets, wildcard, 0-3 quartets, ending IPv4 address
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?
(?:::(?!:))
(?:[0-9a-f]{1,4}(?::(?!:))){0,3}
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# 0-1 quartets, wildcard, 0-4 quartets, ending IPv4 address
(?:[0-9a-f]{1,4}){0,1}
(?:::(?!:))
(?:[0-9a-f]{1,4}(?::(?!:))){0,4}
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# wildcard, 0-5 quartets, ending IPv4 address
(?:::(?!:))
(?:[0-9a-f]{1,4}(?::(?!:))){0,5}
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# 8 quartets; no wildcards
(?:[0-9a-f]{1,4}(?::(?!:))){7}[0-9a-f]{1,4}
|
# 0-7 quartets, wildcard
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,6}[0-9a-f]{1,4})?
(?:::(?!:))
|
# 0-6 quartets, wildcard, 0-1 quartets
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,5}[0-9a-f]{1,4})?
(?:::(?!:))
(?:[0-9a-f]{1,4})?
|
# 0-5 quartets, wildcard, 0-2 quartets
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?
(?:::(?!:))
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?
|
# 0-4 quartets, wildcard, 0-3 quartets
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?
(?:::(?!:))
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?
|
# 0-3 quartets, wildcard, 0-4 quartets
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?
(?:::(?!:))
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?
|
# 0-2 quartets, wildcard, 0-5 quartets
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?
(?:::(?!:))
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?
|
# 0-1 quartets, wildcard, 0-6 quartets
(?:[0-9a-f]{1,4})?
(?:::(?!:))
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,5}[0-9a-f]{1,4})?
|
# wildcard, 0-7 quartets
(?:::(?!:))
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,6}[0-9a-f]{1,4})?
)
(?:/(?:1(?:2[0-7]|[01]\d)|\d\d?))? # With an optional CIDR routing prefix (0-128)
\s* # Trailing whitespace
$"""
I also put together a Python script to test all of those IPv6 examples; it's here on Pastebin because it was too large to post here.
You can run the script with test result and example arguments in the form of "[result]=[example]", so like:
python script.py Fail=::1.2.3.4: pass=::127.0.0.1 false=::: True=::1
or you can simply run all of the tests by specifying no arguments, so like:
Anyway, I hope this helps somebody else!
I only needed to parse IP v4 addresses. My solution based on Chills strategy follows:
def getIP():
I hope it's simple and pythonic enough:
def is_valid_ip(ip):
m = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip)
return bool(m) and all(map(lambda n: 0 <= int(n) <= 255, m.groups()))
if the following script is hosted on a webserver, it should print out visitors Ip address. You can also put it in a database by assigning it to a variable:
'import os
print 'Content-Type:text/html'
print
print os.environ["REMOTE_ADDR"]'
|
I have a small function like so:
from django.contrib.gis.measure import Distance
def RailTest(mod_ewdim, mod_ewspacing, cols):
y = Distance(inch=mod_ewspacing)
x = Distance(inch=mod_ewdim)
z = Distance(inch=3)
l = ( (x*cols)+(y*(cols-1)) )+z
return l
However when I call the function and I do type(l) it is of type float. How can I ensure I return a distance object.
Any help much appreciated.
|
AuthorPosts
September 14, 2012 at 8:14 pm #16326
Hello,
I want to add Social Media Icons (Facebook/Twitter) on top of Propulsion theme.
The current location (bottom of page) is hard to find, and my client is working on promoting his Facebook page.
Thanks in advance for your help.
Daniel
September 17, 2012 at 10:14 am #91108
Hi Daniel,
The Social Media Icons are found on both top and bottom of the Propulsion theme, except for the frontpage. I’ll post back to this thread for the modification of the frontpage.
Regards,
Ismael
September 17, 2012 at 6:01 pm #91109September 17, 2012 at 6:12 pm #91110
Hi,
Open your header.php and find this code
<div class='container_wrap' id='header'>
<div class='container'>
Below that, put this code
<ul class="social_bookmarks header_social">
<?php
//contact icon
$contact_page_id = avia_get_option('email_page');
if (function_exists('icl_object_id')) $contact_page_id = icl_object_id($contact_page_id, 'page', true); //wpml prepared
if($contact_page_id) echo "<li class='mail'><a href='".get_permalink($contact_page_id)."'>".__('Send us Mail', 'avia_framework')."</a></li>";
if($dribbble = avia_get_option('dribbble')) echo "<li class='dribbble'><a href='http://dribbble.com/".$dribbble."'>".__('Follow us on dribbble', 'avia_framework')."</a></li>";
if($twitter = avia_get_option('twitter')) echo "<li class='twitter'><a href='http://twitter.com/".$twitter."'>".__('Follow us on Twitter', 'avia_framework')."</a></li>";
if($facebook = avia_get_option('facebook')) echo "<li class='facebook'><a href='".$facebook."'>".__('Join our Facebook Group', 'avia_framework')."</a></li>";
?>
<li class='rss'><a href="<?php avia_option('feedburner',get_bloginfo('rss2_url')); ?>"><?php _e('Subscribe to our RSS Feed', 'avia_framework')?></a></li>
</ul>
Now, on your custom.css, add this one
#top .social_bookmarks.header_social {
position: absolute;
top: 8px;
right: 0px;
}
Regards,
Ismael
AuthorPosts
The topic ‘Social Media Icons on top of Propulsion theme’ is closed to new replies.
|
#2676 Le 15/02/2013, à 19:14
mulder29
Re : TVDownloader: télécharger les médias du net !
Et je reçois
python: can't open file
alors que j'ai installé Python 2.7.3, hier.
Hors ligne
#2677 Le 15/02/2013, à 19:26
k3c
Re : TVDownloader: télécharger les médias du net !
si tu tapes
which python
ça affiche quoi ?
Dernière modification par k3c (Le 15/02/2013, à 19:28)
Hors ligne
#2678 Le 15/02/2013, à 20:20
mulder29
Re : TVDownloader: télécharger les médias du net !
ça affiche :
/usr/bin/python
Hors ligne
#2679 Le 15/02/2013, à 22:38
JessicaNichenin
Re : TVDownloader: télécharger les médias du net !
j'utilise la version 0.6 du script et cela ne marche plus
python get.py http://videos.tf1.fr/unforgettable/episode-16-saison-01-la-fille-de-l-air-7817948.html
['rtmpdump', '-r', 'rtmpte://wske.wat.tv/ondemand/mp4:vod/H264-384x288/31/87/9433187.h264', '-c', '1935', '-m', '10', '-w', 'ebb7a6fbdc9021db95e2bd537d73fabb9717508f085bea50bde75f7a8e27698c', '-x', '343642', '-o', 'episode-16-saison-01-la-fille-de-l-air-7817948.mp4', ' --resume']
Erreur : le sous-process s'est terminé avec (le code d'erreur est 1)
Erreur : le sous-process s'est terminé avec (le code d'erreur est 1)
Erreur : le sous-process s'est terminé avec (le code d'erreur est 1)
Erreur : le sous-process s'est terminé avec (le code d'erreur est 1)
Merci pour ce merveilleux script
Hors ligne
#2680 Le 16/02/2013, à 00:17
k3c
Re : TVDownloader: télécharger les médias du net !
Cette version est peu testée, mais télécharge les 3 épisodes de Unforgettable
# -*- coding:utf-8 -*-
# TF1 TMC NT1 HD1 version 0.7 par k3c, correction de 11gjm, modif pour TF1 unforgettable
import subprocess, optparse, re, sys, shlex
import socket
from urllib2 import urlopen
import time, md5, random, urllib2
import bs4 as BeautifulSoup
listeUserAgents = [ 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_5; fr-fr) AppleWebKit/525.18 (KHTML, like Gecko) Version/3.1.2 Safari/525.20.1',
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1',
'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.',
'Mozilla/5.0 (X11; U; Linux x86_64; en-us) AppleWebKit/528.5+ (KHTML, like Gecko, Safari/528.5+) midori',
'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.107 Safari/535.1',
'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.8 (KHTML, like Gecko) Chrome/17.0.940.0 Safari/535.8' ]
def get_wat(id):
def base36encode(number):
if not isinstance(number, (int, long)):
raise TypeError('number must be an integer')
if number < 0:
raise ValueError('number must be positive')
alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
base36 = ''
while number:
number, i = divmod(number, 36)
base36 = alphabet[i] + base36
return base36 or alphabet[0]
ts = base36encode(int(time.time()))
timesec = hex(int(ts, 36))[2:]
while(len(timesec)<8):
timesec = "0"+timesec
token = md5.new("9b673b13fa4682ed14c3cfa5af5310274b514c4133e9b3a81e6e3aba00912564/web/"+str(id)+""+timesec).hexdigest()
id_url1 = "http://www.wat.tv/get/web/"+str(id)+"?token="+token+"/"+timesec+"&getURL=1&country=FR"
return id_url1
def main():
gg@gg-SATELLITE-L755:~$ cat !$
cat hd3.py
# -*- coding:utf-8 -*-
# TF1 TMC NT1 HD1 version 0.7 par k3c, correction de 11gjm, modif pour TF1 unforgettable
import subprocess, optparse, re, sys, shlex
import socket
from urllib2 import urlopen
import time, md5, random, urllib2
import bs4 as BeautifulSoup
listeUserAgents = [ 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_5; fr-fr) AppleWebKit/525.18 (KHTML, like Gecko) Version/3.1.2 Safari/525.20.1',
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1',
'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.',
'Mozilla/5.0 (X11; U; Linux x86_64; en-us) AppleWebKit/528.5+ (KHTML, like Gecko, Safari/528.5+) midori',
'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.107 Safari/535.1',
'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.8 (KHTML, like Gecko) Chrome/17.0.940.0 Safari/535.8' ]
def get_wat(id):
def base36encode(number):
if not isinstance(number, (int, long)):
raise TypeError('number must be an integer')
if number < 0:
raise ValueError('number must be positive')
alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
base36 = ''
while number:
number, i = divmod(number, 36)
base36 = alphabet[i] + base36
return base36 or alphabet[0]
ts = base36encode(int(time.time()))
timesec = hex(int(ts, 36))[2:]
while(len(timesec)<8):
timesec = "0"+timesec
token = md5.new("9b673b13fa4682ed14c3cfa5af5310274b514c4133e9b3a81e6e3aba00912564/web/"+str(id)+""+timesec).hexdigest()
id_url1 = "http://www.wat.tv/get/web/"+str(id)+"?token="+token+"/"+timesec+"&getURL=1&country=FR"
return id_url1
def main():
# timeout en secondes
socket.setdefaulttimeout(90)
usage = "usage: python tmc_tf1.py [options] <url de l'emission>"
parser = optparse.OptionParser( usage = usage )
parser.add_option( "--nocolor", action = 'store_true', default = False, help = 'desactive la couleur dans le terminal' )
parser.add_option( "-v", "--verbose", action = "store_true", default = False, help = 'affiche les informations de debugage' )
( options, args ) = parser.parse_args()
if( len( args ) > 2 or args[ 0 ] == "" ):
parser.print_help()
parser.exit( 1 )
debut_id = ''
html = urlopen(sys.argv[1]).read()
nom = sys.argv[1].split('/')[-1:][0]
no = nom.split('.')[-2:][0]
soup = BeautifulSoup.BeautifulSoup(html)
if 'tmc.tv' in str(soup) or 'tf1.fr' in str(soup):
debut_id = str(soup.find('div', attrs={'class' : 'unique' }))
if 'nt1.tv' in str(soup) or 'hd1.tv' in str(soup):
debut_id = str(soup.find('section', attrs={'class' : 'player-unique' }))
id = [x.strip() for x in re.findall("mediaId :([^,]*)", debut_id)][0]
id_url1 = get_wat(id)
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', random.choice(listeUserAgents))]
data = opener.open(id_url1).read()
opener.close()
if data[0:4] == 'http':
ua = random.choice(listeUserAgents)
arguments = 'curl "%s" -L -g -A "%s" -o "%s.mp4"' % (data, ua, no)
print arguments
process = subprocess.Popen(arguments, stdout=subprocess.PIPE, shell=True).communicate()[0]
if data[0:4] == 'rtmp':
host = re.search('rtmpte://(.*)/ondemand', data).group(1)
host = host.replace('rtmpte', 'rtmpe')
data0 = re.search('rtmpte://(.*)h264', data).group(0)
cmds = 'rtmpdump -r "%s" -c 443 -m 10 -w b23434cbed89c9eaf520373c4c6f26e1f7326896dee4b1719e8d9acda0c19e99 -x 343427 -o "%s.mp4" " --resume"' % (data0, str(no))
f = open(str(no), 'w')
f.write(cmds)
f.close()
arguments = shlex.split( cmds )
print arguments
cpt = 0
while True:
p = subprocess.Popen( arguments,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if p.returncode != 0:
print "Erreur : le sous-process s\'est terminé avec (le code d\'erreur est " + str(p.returncode) + ")"
# status = False
if cpt > 5:
break
cpt += 1
time.sleep(3)
else:
# status = True
break
if __name__ == "__main__":
Hors ligne
#2681 Le 16/02/2013, à 01:15
angeline
Re : TVDownloader: télécharger les médias du net !
Bonsoir à tous.
Ce soir, je découvre que "www.francetvinfo.fr" a encore changé de protocole, et plus possible télécharger le journal de France2 le 20 heures.
Je suis en Amérique du sud.
Est-ce vrai aussi pour vous ?
Merci.
ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ
Hors ligne
#2682 Le 16/02/2013, à 08:52
gl38
Re : TVDownloader: télécharger les médias du net !
Le journal de 20h de France 2 du 15/2 se télécharge normalement chez moi (en France).
Cordialement,
Guy
Hors ligne
#2683 Le 16/02/2013, à 10:09
k3c
Re : TVDownloader: télécharger les médias du net !
@ angeline
avec pluzzdl 0.9.4 je viens de télécharger le journal de 20 h
gg@gg-SATELLITE-L755:~$ pluzzdl -v http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] main.py pluzzdl 0.9.4 avec Python 2.7.3 (i686)
[DEBUG ] main.py OS : Linux #58-Ubuntu SMP Thu Jan 24 15:51:02 UTC 2013
[DEBUG ] Navigateur.py GET http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] PluzzDL.py ID de l'émission : 77106215
[DEBUG ] Navigateur.py GET http://www.pluzz.fr/appftv/webservices/video/getInfosOeuvre.php?mode=zeri&id-diffusion=77106215
[DEBUG ] PluzzDL.py Lien MMS : mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/Autre/Autre/2013/S07/J5/738525_jt20h_20130215.wmv
[DEBUG ] PluzzDL.py Lien RTMP : None
[DEBUG ] PluzzDL.py URL manifest : http://ftvodhdsecz-f.akamaihd.net/z/streaming-adaptatif/2013/S07/J5/77106215-20130215-,398,632,934,k.mp4.csmil/manifest.f4m
[DEBUG ] PluzzDL.py URL m3u8 : http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215.m3u8
[DEBUG ] PluzzDL.py Utilisation de DRM : non
[DEBUG ] PluzzDL.py Chaine : France 2
[DEBUG ] Historique.py Historique chargé
[DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215.m3u8
[DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215-840k.m3u8
[DEBUG ] PluzzDL.py Nombre de fragments : 242
[INFO ] PluzzDL.py Début du téléchargement des fragments
et ça se finit par
[DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215-840k/77106215-20130215-240.ts
[DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215-840k/77106215-20130215-241.ts
[INFO ] PluzzDL.py Fin du téléchargement
[INFO ] PluzzDL.py Création du fichier MKV (vidéo finale) ; veuillez attendre quelques instants
[INFO ] PluzzDL.py Fin !
[DEBUG ] Historique.py Historique sauvé
gg@gg-SATELLITE-L755:~$
Hors ligne
#2684 Le 16/02/2013, à 11:29
mulder29
Re : TVDownloader: télécharger les médias du net !
Ah mince, et toujours pas de solution pour moi ? :S
Hors ligne
#2685 Le 16/02/2013, à 12:16
thom83
Re : TVDownloader: télécharger les médias du net !
Bonjour,
@ k3c
J'ai testé la version 0.7 ci-dessus (la partie inférieure) avec succès après avoir ajouté le «main()» qui va bien.
Est-il possible d'améliorer cette version en favorisant les variantes HD des émissions plutôt qu'en SD, quitte à ce que cela prenne plus de place sur le disque ?
Cela ferait une différence sur un écran un peu grand...
Dernière modification par thom83 (Le 16/02/2013, à 12:17)
Hors ligne
#2686 Le 16/02/2013, à 12:33
ynad
Re : TVDownloader: télécharger les médias du net !
@ mulder29
voila comment j'ai fait:
j'ai créer un répertoire D8
dans ce répertoire j'ai copier coller le script #2646 page 106 de k3C dans un éditeur de texte et sauvegarder en d8.py
dans le même répertoire j'ai ouvert un terminal et lancer la commande:
python d8.py http://www.d8.tv/d8-series/pid5313-d8-h.html
si la vidéo est toujours en ligne elle se charge dans ce répertoire
ce script est valable pour d8, k3c en a fait d'autres pour tf1 etc.
il y a pluzdl pour le site de pluzz.
espérant t'aider un peu...
Hors ligne
#2687 Le 16/02/2013, à 13:39
k3c
Re : TVDownloader: télécharger les médias du net !
@ thom83
je prux sortir un hack rapidement, quitte à faire propre plus tard
Hors ligne
#2688 Le 16/02/2013, à 14:05
mulder29
Re : TVDownloader: télécharger les médias du net !
On me met encore
m = re.search('\d{6}$',sys.argv[1])
bash: Erreur de syntaxe près du symbole inattendu « ( »
~$ if m is None:
> try:
> id = s.findAll('div',attrs={"class":u"block-common block-player-programme"})[0]('canal:player')[0]['videoid']
bash: Erreur de syntaxe près du symbole inattendu « ( »
~$ except:
Commande 'except:' non trouvée, vouliez-vous dire :
La commande 'except' du paquet 'qmail' (universe)
except: : commande introuvable
~$
Display all 2596 possibilities? (y or n)
~$ t 'imposiible de trouver l\'id de la video'
>
Sans doute là que ça coince.
J'ai tapé la ligne de commande dans le Terminal, rien ne se passe.
(en revanche, ma flèche du curseur est devenue une croix)
Hors ligne
#2689 Le 16/02/2013, à 14:10
angeline
Re : TVDownloader: télécharger les médias du net !
@K3c,
Merci, j'ai le même début, mais pas la même fin
cb@cb-desktop:~$ pluzzdl -v http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] main.py pluzzdl 0.9.4 avec Python 2.7.3 (i686)
[DEBUG ] main.py OS : Linux #58-Ubuntu SMP Thu Jan 24 15:51:02 UTC 2013
[DEBUG ] Navigateur.py GET http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] PluzzDL.py ID de l'émission : 77106215
[DEBUG ] Navigateur.py GET http://www.pluzz.fr/appftv/webservices/video/getInfosOeuvre.php?mode=zeri&id-diffusion=77106215
[DEBUG ] PluzzDL.py Lien MMS : mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/Autre/Autre/2013/S07/J5/738525_jt20h_20130215.wmv
[DEBUG ] PluzzDL.py Lien RTMP : None
[DEBUG ] PluzzDL.py URL manifest : http://ftvodhdsecz-f.akamaihd.net/z/streaming-adaptatif/2013/S07/J5/77106215-20130215-,398,632,934,k.mp4.csmil/manifest.f4m
[DEBUG ] PluzzDL.py URL m3u8 : http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215.m3u8
[DEBUG ] PluzzDL.py Utilisation de DRM : non
[DEBUG ] PluzzDL.py Chaine : France 2
[DEBUG ] Historique.py Historique chargé
[DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215.m3u8
[DEBUG ] Navigateur.py Forbidden
Traceback (most recent call last):
File "/usr/share/pluzzdl/main.py", line 91, in <module>
progressFnct = progressFnct )
File "/usr/share/pluzzdl/PluzzDL.py", line 119, in __init__
downloader.telecharger()
File "/usr/share/pluzzdl/PluzzDL.py", line 259, in telecharger
self.m3u8 = self.navigateur.getFichier( self.m3u8URL )
File "/usr/share/pluzzdl/Navigateur.py", line 58, in getFichier
page = self.urlOpener.open( requete, timeout = self.timeOut )
File "/usr/lib/python2.7/urllib2.py", line 406, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 519, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 444, in error
return self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 527, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
[DEBUG ] Historique.py Historique sauvé
Je sèche.
PS.: cela va si mal que cela en France... que les infos ne doivent pas sortir de l'hexagone ?
Edit: Oubliez la ligne au dessus... Avec Opera, cela se charge, mais très lentement, (en pointillés) du à mon internet très lent, et ce n'est pas regardable! D'où la nécessité de télécharger.
Dernière modification par angeline (Le 16/02/2013, à 14:25)
ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ
Hors ligne
#2690 Le 16/02/2013, à 15:05
k3c
Re : TVDownloader: télécharger les médias du net !
@ mulder29
tu exécutes du bash, pas du python
@ angeline
n'étant pas en France, il te faudrait un proxy France,non ?
Hors ligne
#2691 Le 16/02/2013, à 15:12
mulder29
Re : TVDownloader: télécharger les médias du net !
ok et comment je fais pour passer en mode "python" ?
Hors ligne
#2692 Le 16/02/2013, à 15:13
angeline
Re : TVDownloader: télécharger les médias du net !
@K3c
Par Opera ou Firefox, je ne passe pas par un proxy actuellement.
Avec Opera, j'ai droit à un bonus de 50 secondes de pub... qui fonctionne très bien !
Par Firefox, c'est bloqué par AdBlock, mais le journal dans tous les cas arrive trop lentement.
Le pb me parait autre part.
ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ
Hors ligne
#2693 Le 16/02/2013, à 15:53
angeline
Re : TVDownloader: télécharger les médias du net !
@Kc2
Si je récupère
[DEBUG ] PluzzDL.py Lien MMS : mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/Autre/Autre/2013/S07/J5/738525_jt20h_20130215.wmv
que je change le "mms" en "rtsp" le journal est téléchargeable par mon downloader préféré !
Mais pas par "pluzzdl"
ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ
Hors ligne
#2694 Le 16/02/2013, à 23:22
angeline
Re : TVDownloader: télécharger les médias du net !
C'était trop beau... cela n'a pas duré.
[DEBUG ] PluzzDL.py Lien MMS : None
[DEBUG ] PluzzDL.py Lien RTMP : None
Donc, comment passer par un proxy S.V.P.
ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ
Hors ligne
#2695 Le 16/02/2013, à 23:28
mulder29
Re : TVDownloader: télécharger les médias du net !
Ok, j'ai installé idle, j'ai lancé une python shell et j'ai ouvert mon dossier leafpad d8.py en prenant soin de copier/coller le texte
J'ai ensuite copié dans le terminal le lien
python d8.py http://www.d8.tv/d8-series/pid5313-d8-h.html
et... il n'a l'air de rien se passer en fait.
Hors ligne
#2696 Le 17/02/2013, à 00:11
k3c
Re : TVDownloader: télécharger les médias du net !
@ angeline
$ pluzzdl --help
usage: pluzzdl [options] urlEmission
Télécharge les émissions de Pluzz
positional arguments:
urlEmission URL de l'émission Pluzz a charger
optional arguments:
-h, --help show this help message and exit
-b, --progressbar affiche la progression du téléchargement
-p PROXY, --proxy PROXY
utilise un proxy HTTP au format suivant
http://URL:PORT
-s, --sock si un proxy est fourni avec l'option -p, un proxy
SOCKS5 est utilisé au format suivant ADRESSE:PORT
-v, --verbose affiche les informations de debugage
-t, --soustitres récupère le fichier de sous-titres de la vidéo (si
disponible)
--nocolor désactive la couleur dans le terminal
--version show program's version number and exit
donc pluzzdl -p http://1.2.3.4:80 ...
en supposant que 1.2.3.4:80 est un proxy français valide
@ mulder 29
quand je lance ta commande, ça m'affiche
python d8.py http://www.d8.tv/d8-series/pid5313-d8-h.html
rtmpdump -r "rtmp://vod-fms.canalplus.fr/ondemand/videos/1302/1047160_20_1500k.mp4" -o "H.mp4"
en fait cette procédure lance juste la commande ci-dessus
Hors ligne
#2697 Le 17/02/2013, à 00:51
angeline
Re : TVDownloader: télécharger les médias du net !
@K3c
Merci pour la réponse.
Cependant, je doute !
J'ai essayé 6/7 proxy... pas un ne veut coopérer.
Par un navigateur: Firefox, Opéra, ou Chromium, l'émission passe. Sans proxy.
Par pluzzdll, toujours la même interdiction
cb@cb-desktop:~$ pluzzdl -v http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] main.py pluzzdl 0.9.4 avec Python 2.7.3 (i686)
[DEBUG ] main.py OS : Linux #58-Ubuntu SMP Thu Jan 24 15:51:02 UTC 2013
[DEBUG ] Navigateur.py GET http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] PluzzDL.py ID de l'émission : 77496935
[DEBUG ] Navigateur.py GET http://www.pluzz.fr/appftv/webservices/video/getInfosOeuvre.php?mode=zeri&id-diffusion=77496935
[DEBUG ] PluzzDL.py Lien MMS : mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/Autre/Autre/2013/S07/J6/740386_jt20h_20130216.wmv
[DEBUG ] PluzzDL.py Lien RTMP : None
[DEBUG ] PluzzDL.py URL manifest : http://ftvodhdsecz-f.akamaihd.net/z/streaming-adaptatif/2013/S07/J6/77496935-20130216-,398,632,934,k.mp4.csmil/manifest.f4m
[DEBUG ] PluzzDL.py URL m3u8 : http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J6/77496935-20130216.m3u8
[DEBUG ] PluzzDL.py Utilisation de DRM : non
[DEBUG ] PluzzDL.py Chaine : France 2
[DEBUG ] Historique.py Historique chargé
[DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J6/77496935-20130216.m3u8
[DEBUG ] Navigateur.py Forbidden
Traceback (most recent call last):
File "/usr/share/pluzzdl/main.py", line 91, in <module>
progressFnct = progressFnct )
File "/usr/share/pluzzdl/PluzzDL.py", line 119, in __init__
downloader.telecharger()
File "/usr/share/pluzzdl/PluzzDL.py", line 259, in telecharger
self.m3u8 = self.navigateur.getFichier( self.m3u8URL )
File "/usr/share/pluzzdl/Navigateur.py", line 58, in getFichier
page = self.urlOpener.open( requete, timeout = self.timeOut )
File "/usr/lib/python2.7/urllib2.py", line 406, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 519, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 444, in error
return self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 527, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
[DEBUG ] Historique.py Historique sauvé
Par chance, France télévision s'est réveillé, et maintenant une URL en mms apparait.
Il est 18h ici, je télécharge.
Avec proxy j'obtiens:
pluzzdl -v -p http://176.31.247.227:8085 http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] main.py pluzzdl 0.9.4 avec Python 2.7.3 (i686)
[DEBUG ] main.py OS : Linux #58-Ubuntu SMP Thu Jan 24 15:51:02 UTC 2013
[DEBUG ] Navigateur.py GET http://pluzz.francetv.fr/videos/jt20h.html
[CRITICAL] PluzzDL.py Impossible de récupérer l'ID de l'émission
Mais je pense que peu de proxy laissent passer les infos de vidéo, du moins dans les gratuits.
Je reste à l'écoute.
Dernière modification par angeline (Le 17/02/2013, à 00:53)
ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ
Hors ligne
#2698 Le 17/02/2013, à 02:17
mulder29
Re : TVDownloader: télécharger les médias du net !
@ mulder 29
quand je lance ta commande, ça m'affiche
python d8.py http://www.d8.tv/d8-series/pid5313-d8-h.html
rtmpdump -r "rtmp://vod-fms.canalplus.fr/ondemand/videos/1302/1047160_20_1500k.mp4" -o "H.mp4"
en fait cette procédure lance juste la commande ci-dessus
Euh, moi, ça reste sur la ligne sur python...
et aucune autre réaction o_O
Ok, donc il y a vraiment un bug dans mon système et python est inutilisable chez moi.
Hors ligne
#2699 Le 17/02/2013, à 02:20
k3c
Re : TVDownloader: télécharger les médias du net !
si tu tapes dans un terminal
python
ça t'affiche quoi ?
Hors ligne
#2700 Le 17/02/2013, à 10:59
mulder29
Re : TVDownloader: télécharger les médias du net !
Ça m'affiche :
Python 2.7.3 (default, Aug 1 2012, 05:16:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
par rapport à la commande fait précédemment, tu en déduis ?
Hors ligne
|
I am using a treeview with checkboxes. I want the user to be able to click a checkbox and it will add that item to a favourites list. But currently I cannot get the boxes to toggle at all. Here's my code:
def draw_columns(self,treeview):
self.ren = gtk.CellRendererToggle()
self.ren.connect('toggled',self.on_toggle,treeview.get_model())
self.tvfav = gtk.TreeViewColumn('Fav',self.ren,text=7)
for i in [self.tvfav,'andall the other columns']:
treeview.append_column(i)
def on_toggle(self,cell,path_str,model):
toggle_item = model.get_value(iter,column)
toggle_item = not toggle_item
# This method didn't work either
## model[path_str][1] = not model[path_str][1]
if toggle_item:
#Add it to the favourite list if it isn't already
pass
else:
#remove it from the favourite list
pass
model.set(iter,column,toggle_item)
def __init__(self):'
....
self.liststore = gtk.ListStore(str,int, int, int,str, 'gboolean', str)
self.treeview = gtk.TreeView(self.liststore)
....
What am I doing wrong that the boxes can't be checked? Also, how would I set the toggle when items are appended to the treeview like this:
if name in favourites:
#Append to list with checkbox on
self.liststore.append([name,x,y,z,ss,True,sss])
|
I use Django nani http://readthedocs.org/docs/django-nani/en/latest/ and want to define two models (one inherits another):
class ItemBase(TranslatableModel):
translations = TranslatedFields(
name = models.CharField(max_length=40)
)
slug = models.SlugField(unique=True, max_length=40)
description = models.CharField(max_length=1000)
worth = models.PositiveIntegerField()
class EquipBase(ItemBase):
def __init__(self, *args, **kwargs):
super(EquipBase, self).__init__(*args, **kwargs)
level = models.PositiveSmallIntegerField()
However, I do get the following error when using syncdb.
django.core.exceptions.ImproperlyConfigured: No TranslatedFields found on <class 'main.world.items.models.EquipBase'>, subclasses of TranslatableModel must define TranslatedFields.
What's the solution?
|
If you're just looking to see whether one is in the other (and don't care about frequency, etc.), you could try using set's to store unique occurrences from each file, and then find the intersection of the two sets, which would represent emails that were present in both files (note that the with statement with two files is a Python2.7+ feature):
>>> l1 = set()
>>> l2 = set()
>>> with open('FILEA.txt', 'rb') as f1, open('FILEB.txt', 'rb') as f2:
... for line in f1.readlines():
... l1.add(line.strip())
... for line in f2.readlines():
... l2.add(line.strip())
...
>>>
>>> l1
set(['another@gmail.com', 'andanother@hotmail.com', 'this@email.com'])
>>> l2
set(['unique@somehost.com', 'this@email.com', 'not@example.com'])
>>> l1 & l2
set(['this@email.com'])
With sets, you can also perform other (potentially) helpful operations:
Identify items that are in both sets (union):
>>> l1 | l2
set(['another@gmail.com', 'unique@somehost.com', 'andanother@hotmail.com', 'this@email.com', 'not@example.com'])
Items that are in one set but not the other (difference):
>>> l1 - l2
set(['another@gmail.com', 'andanother@hotmail.com'])
>>> l2 - l1
set(['not@example.com', 'unique@somehost.com'])
Items that are unique to each set (think of it as the union less the intersection) (symmetric_difference):
>>> l1 ^ l2
set(['another@gmail.com', 'not@example.com', 'unique@somehost.com', 'andanother@hotmail.com'])
Lastly, you can also perform those operations using methods instead of the operators. To use the methods, take a set, append one of the names in parentheses above and make the other set the argument:
>>> l1.intersection(l2)
set(['this@email.com'])
My files looked like this:
FILEA.txt
this@email.com
another@gmail.com
andanother@hotmail.com
FILEB.txt
not@example.com
this@email.com
unique@somehost.com
|
Zetsu15
Probléme Gnome Shell Extension
Salut A Tous
Je Suis Nouveau Sur Le Forum Mais Il Ya Longtemps Que Jai Débuter Avec Ubuntu
Jai Installé La Version 11.10 Et Gnome 3.2, jai tout mis a jour, installé gnome tweak tool, les extensions de chez Web upd8, bref tout marché nickel jusqu'a ce que je redémarre ma machine, les extensions marche normalement ( ils sont affichés sur le panneau etc ) mais je ne peut plus y accéder dans gnome tweak tool
Quand jaccéde a Shell Extensions il n'affiche aucune extension a part l'install shell extension , dans theme devant la rubrique Shell Théme il ya un ptit triangle en jaune ki affiche "could not list shell extension"
jai désinstaller toute les extension, gnome tweak tool, je les ai réinstaller, redémarrer a mainte fois la machine rien n'y fais
Voici le rapport du terminal quand je le lance g.t.t
gnome-tweak-tool
WARNING : Could not list shell extensions
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/gtweak/tweaks/tweak_shell.py", line 62, in __init__
extensions = self._shell.list_extensions()
File "/usr/lib/python2.7/dist-packages/gtweak/gshellwrapper.py", line 107, in list_extensions
return self._proxy.proxy.ListExtensions()
File "/usr/lib/python2.7/dist-packages/gi/overrides/Gio.py", line 148, in __call__
kwargs.get('flags', 0), kwargs.get('timeout', -1), None)
File "/usr/lib/python2.7/dist-packages/gi/types.py", line 43, in function
return info.invoke(*args, **kwargs)
GError: Le délai d'attente est épuisé
Aucun schéma connu pour « /desktop/gnome/shell/windows/button_layout »
Aucun schéma connu pour « /desktop/gnome/shell/windows/button_layout »
WARNING : Error listing extensions
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/gtweak/tweaks/tweak_shell_extensions.py", line 153, in __init__
for extension in shell.list_extensions().values():
File "/usr/lib/python2.7/dist-packages/gtweak/gshellwrapper.py", line 107, in list_extensions
return self._proxy.proxy.ListExtensions()
File "/usr/lib/python2.7/dist-packages/gi/overrides/Gio.py", line 148, in __call__
kwargs.get('flags', 0), kwargs.get('timeout', -1), None)
File "/usr/lib/python2.7/dist-packages/gi/types.py", line 43, in function
return info.invoke(*args, **kwargs)
GError: Le délai d'attente est épuisé
Aucun schéma connu pour « /desktop/gnome/shell/windows/theme »
Aucun schéma connu pour « /desktop/gnome/shell/windows/theme »
Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed
Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed
Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed
Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed
Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed
Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed
Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed
Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed
Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed
Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed
Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed
Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed
Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed
Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed
Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed
Ah oui jai oublié, maintenant je ne vois plus les bouttons maximizer et minimiser, méme s'ils sont encore activé dans g.t.t :s
HelP Please ((
Dernière modification par Zetsu15 (Le 16/11/2011, à 13:56)
Hors ligne
stef28
Re : Probléme Gnome Shell Extension
J'ai exactement le même problème .... pas de solution en vue ?
stef
Hors ligne
Major Grubert
Re : Probléme Gnome Shell Extension
Aucune idée. Peut-être que certaines extensions sont incompatibles entre elles et causent le pb ?
Les désinstaller toutes. Nettoyer le cache. En installer une. L'activer. Tester (éventuellement avec un redémarrage). Si ça marche passer à la suivante.
Mais bon...
Pour en savoir plus sur Gnome Shell.
. Lenovo Yoga 13 : Windows 8.1 / Ubuntu Gnome 14.04
. Asus x7010 : Ubuntu 14.04 (Gnome Shell)
. Asus Eeepc : Xubuntu 14.04 (32b)
Hors ligne
stef28
Re : Probléme Gnome Shell Extension
En fait, j'ai enlevé toutes mes extensions et redémarré ... rien de changé
Dernière modification par stef28 (Le 20/11/2011, à 22:37)
stef
Hors ligne
willcoyote
Re : Probléme Gnome Shell Extension
Salut
Pour voir les erreurs avec les extension, il y a une autre solution
ALT + F2 et taper : lg puis error
touche echap pour quitter ce menu
et inutile de redémarrer
ALT + F2 puis r
pour redemarrer gnome shell
archlinux+kde
Hors ligne
stef28
Re : Probléme Gnome Shell Extension
Merci du tuyau ... mais ça ne résous pas mon problème
stef
Hors ligne
Zetsu15
Re : Probléme Gnome Shell Extension
Re Salut A Tous Le Monde
En Fait J'ai fait Et Refait Toute Les Manip Auparavant
Avec LG il affiche Aucune Extensions Installé Alors Que J'en ai Une disaine D'installé
Désinstaller Nettoyer Réinstaller Tout Y Compri ( Extensions GTT Gnome Shell )
Rien N'y Fait
Du Coup Jai Réinstallé Ubuntu Et Gnome En Espérant Que Ca Se Repdouise Plus
Dernière modification par Zetsu15 (Le 20/11/2011, à 23:12)
Hors ligne
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.