text stringlengths 256 65.5k |
|---|
1.0 Overview
Basic description of article scope - target audience, who this is for, what IP Masquerading is not
2.0 Deployment
Description of the solution to be implemented in this article - one Linux router, one Windows 95 client
2.1 Linux Router Box Specification
2.2 Windows 95 Masquerading Client Box Specification
3.0 How Your Network Should Look
This section is intended to give the reader an idea of how their network should currently look to be able to benefit from IP Masquerading.
4.0 Linux Router Configuration
This section describes the configuration of the linux router to allow it to act as an IP Masquerading firewall.
4.1 Overview of Linux Router Configuration
4.1.1 - A Word on IP Addressing and Private Address Ranges
4.2 Assigning an IP Address to the Linux Network Interface Card
4.3 Assigning an IP Address to the Linux Network Interface Card At Boot Time
4.4 Configuring the PPP/Modem Dialup Connection
4.4.1 What Is A Domain Name Server Anyway?
4.4.2 Configuring The Linux Router To Use DNS
4.5 Installing The Masquerading Firewall
4.5.1 What Is A Masquerading Firewall Anyway?
4.5.2 What Is IPCHAINS?
4.5.3 Checking To See If IPCHAINS Is Installed
4.5.4 Installing IPCHAINS
4.5.5 Installing and Configuring The 'rc.firemasq' Script
4.5.6 Setting Up The 'rc.firemasq' script
4.5.7 Running The Script
5.0 Configuring the Windows 95 Masquerading Client
This section describes the configuration of the Win95 machine to allow it to connect to the internet via the Linux router.
5.1 Installing TCP/IP On The Windows 95 Machine
5.2 Assigning A Static IP Address Of 192.168.0.10 To The Windows 95 Machine
5.3 Configuring The Masqueraded Windows 95 Machine To Use The Linux Router As A Gateway
5.4 Configuring The Masqueraded Windows 95 Machine To Use The External DNS Server
6.0 Testing the IP Masquerading Setup
6.1 Bring Up The PPP Internet Connection On The Linux Router
6.2 Testing Connectivity From The Linux Router To The External Network/Internet
6.3 Test Connectivity From The Windows 95 Masqueraded Client To The Linux Router
6.4 Test Connectivity From The Windows 95 Masqueraded Client To The External Network/Internet
7.0 Checking The Firemasq Logs
7.1 Configuring The Destination Of 'ipchains' Log Output
7.2 A Note On Creating Rules That Log When Matched
7.3 Viewing 'ipchains' Logs
7.4 A Tip On Monitoring Log Files
8.0 Conclusion
Closing remarks and a note on getting help.
Appendix A: Reference Section
A list of references used in this document and recommended reading.
Appendix B: Original 'firemasq' Script
This text is aimed at the home LAN user who wants to use a single internet connection to allow more than one machine access to the internet
at the same time. This is commonly called 'IP Masquerading'. We will deploy a linux masquerading firewall solution using ipchains to allow the internet connection from the linux router to the internet to be shared with one other machine on the Local Area Network (LAN).
Important
IP Masqueradingis not IP Spoofingin the sense of hiding one's IP address in order to deceive a target host for matters of becoming anonymous. IP Masquerading simply allows more than one machine to share the same IP address - the machines which are not allocated the single IP address are theMasqueraded Clients, they useMasqueraded IP Addressesto communicate to the external network or internet.
The method of deployment we shall describe is as follows:
2.1 Linux Router Specification
One P166 32MB 1.6GB HDD, configured as a Linux router with support for Firewalling and IP Masquerading:This machine will be built using Linux Mandrake release 7.1 (helium), Kernel 2.2.15-4mdk. Support for firewalling and IP masquerading will be implemented using the 'ipchains' TCP/IP packet filter. The router will be connected to the internet via a Point-to-Point Protocol (PPP) connection using a US Robotics 56k modem. In turn the router will be connected to the Windows 95 client via an Ethernet connection using a Compaq Netelligent 10/100 Network Interface Card (NIC).
The NIC will be assigned an IP address of 192.168.0.1 (the connection to the Win95 client) and the external/PPP interface will be assigned an IP address dynamically on each successful 'dialup' to the ISP.
Note: Any Linux distribution will suffice- provided that the kernel has built in support for IP Masquerading.
2.2 Windows 95 Masquerading Client Specification
One P166 48MB 20GB HDD, configured as a Windows 95 Masqueraded Client:This machine will be built simply with Windows 95 OSR2. This machine will be the masqueraded client, the machine which will share the connection to the internet with the Linux machine. The client will be connected to the router via an ethernet interface using a 3com 3c509 NIC.
The client will be assigned a static IP address of 192.168.0.10.
Please take the time to have a quick look at the following ascii art diagram. It shows a very basic network structure:one machine connected to the other by a network cable (ETH0) in the diagram below) and one machine connected to the internet via a modem (PPP0 in the diagram below).
_________________________________________
| __________ LAN _______________ |
_/\__/\_ | | | | | |
| | | | Firewall | | Masqueraded | |
/ Internet \--(PPP0)--| System |--(ETH0)--| Workstation/s | |
\_ _ _ _/ | |__________| |_______________| |
\/ \/ \/ |_________________________________________|
This is how the network should look from a basic connectivity point of view. The firewall/router machine has the connection to the internet (via a PPP) and the masqueraded client(s) are connected on a LAN to the firewall/router using TCP/IP. In the following sections we will discuss the configuration of the network in more depth - for now you should be happy if you're network resembles the diagram above!
Important
For the Configuration of the Linux Router you should be logged in suid=0 (ie a login with root privileges - logging in as root works best;).
Our diagram at the end of the last section showed the status of our network so far:
_________________________________________
| __________ LAN _______________ |
_/\__/\_ | | | | | |
| | | | Firewall | | Masqueraded | |
/ Internet \--(PPP0)--| System |--(ETH0)--| Workstation/s | |
\_ _ _ _/ | |__________| |_______________| |
\/ \/ \/ |_________________________________________|
We will now concentrate on configuring the Linux/Firewall routing machine. The following diagram shows in more detail how the Linux router's network interfaces will be configured:
__________
(ppp0, dyn. IP) | | (eth0, 192.168.0.1)
\| Firewall |/
to internet<-----| System |-----> to win95 box
|__________|
We see in the diagram that the NIC connecting the Linux router to the masqueraded client (
eth0) will be assigned the address '192.168.0.1' and the PPP/dialup interface connecting the Linux router to the internet (ppp0), will beassigned an IP address dynamically.
This section covers the following:
4.1 - Assigning an IP Address to the Linux Network Interface Card
4.2 - Configuring the PPP/modem dialup connection
4.3 - Configuring which nameserver the router should use
4.4 - Installing the firewall / packet filter 'ipchains'
4.5 - Installing a script 'rc.firemasq' which will create the ipchains rule-set allowing us to use the machine as a masquerading firewall router
4.1 -Assigning an IP Address to the Linux Network Interface Card
One of the stock tools used in configuring networking under Linux is 'ifconfig'. 'ifconfig' is short for 'Network
InterfaceConfiguration'. A network interface in Linux is a device which allows network communication through it.
For example, the first network card/interface is named
eth0, the second NICeth1and so on. Similarly, the first PPP or dialup interface is namedppp0etc. A very useful interface in Linux is theLoopback Interface, namedloin Linux - the 'lo' interface allows us to test servers/daemons which we may have running by connecting to our own machine using the 'lo' interface.
By assigning an IP address to the network interface, we give the machine an address on the local network, an address which will allow the masqueraded client (the win95 machine) to connect to the router for the purposes of sharing the internet connection.
Section 4.1.1 - A Word on IP Addressing and Private Address Ranges
We will use the private address range 192.168.0.0 to 192.168.0.255 (or 192.168.0.0/24) for our LAN; all addresses within this range are private and cannot be assigned to machines for communication on the internet - hence it is perfectly fine for LAN machines to be assigned addresses from this range (for more information see RFC1918: Address Allocation for Private Internets).
Important
If you already have an IP address assigned to your Network Interface card and are happy with your setup, please feel free to use it - obviously however you will need to substituteyouraddress range/IP addresses for those used here (192.168.0.0/24).
We will assign the address '192.168.0.1' to the network interface card, eth0; this should be the network card that connects your linux machine to the windows 95 client - if not, replace 'eth0' for the device which connects your linux machine to the win95 machine.
To do so we need to use ifconfig, issuing the command 'ifconfig eth0 192.168.0.1 netmask 255.255.255.0 up' at the bash command line:
[root@localhost /root]# ifconfig eth0 192.168.0.1 netmask 255.255.255.0 up
eepro100.c: $Revision: 1.20.2.3 $ 2000/03/02 Modified by Andrey V. Savochkin and others
This configures the first NIC to use the address 192.168.0.1 with a network mask of 255.255.255.0 and brings the interface up (ignore the netmask and up parts if you like - ifconfig defaults to a netmask of 255.255.255.0 and assumes you want to bring the interface up if you don't specify 'up' as an argument).
Important
Note the line:eepro100.c: $Revision: 1.20.2.3 $ 2000/03/02 Modified by Andrey V. Savochkin and others.
This means that Linux is using the driver/module 'eepro100.c' for my network card - you must ensure the correct modules are installed for your network card - See the 'Net3-HOWTO' for further details.
We can check that the Network Card eth0 has been assigned the address correctly now using ifconfig without any arguments:
[root@localhost /root]# ifconfig eth0 eth0 Link encap:Ethernet HWaddr 00:08:C7:BB:75:79 inet addr:192.168.0.1 Bcast:192.168.0.255 Mask:255.255.255.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:1 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:100 Interrupt:10 Base address:0x6000
The important part here is that pertaining to '
eth0' of course. We see the address 192.168.0.1 has been assigned correctly, with various other very useful details (which aren't actually useful to us here!=). If you have trouble assigning the address to eth0 at this point, I suggest you read the NET-HOWTO and Ethernet-HOWTO - see reference section for further details.
4.2 Assigning the IP Address to the Network Card At Boot Time
To assign the IP address to the network card at boot, you will need to use the 'netconf' utility (Linux Mandrake, though there should be a similar configuration tool for most other Linux distributions;). 'netconf' basically modifies various startup scripts located within '/etc/rc.d' and it's subdirectories so that each time the machine is booted, the IP address you specify for eth0 in 'netconf' is allocated to eth0.
'netconf' is pretty straightforward under Linux Mandrake, so I won't go into massive detail here - a brief overview:
Run 'netconf' from the command line.
Select 'Basic Host Information'.
Under 'Adaptor 1', change 'IP Address' to '192.168.0.1' and change 'Net device' to 'eth0'(providing your network cards kernel modules have been installed, the correct kernel module should be selected for you).
Select 'Accept' and when prompted to activate the changes, do so. (Check to see what modifications have been made if you like;-).
If all is well, when issuing the command 'ifconfig' you should see the interface 'eth0' assigned the address '192.168.0.1' and after rebooting the eth0 interface should automatically be assigned the address.
4.3 Configuring the PPP/Modem Dialup Connection.
The Point-to-Point Protocol connection can be tricky to set up for the uninitiated user - my advise is to set aside a good few hours, get a bucket of coffee, print out the 'PPP-HOWTO' and read, play, read, play, etc...
We will use 'netconf' again to set up and configure our PPP connection. 'netconf' really does take the work out of setting up your network, although I highly recommend you attempt to understand fully what files netconf modifies and the way in which your network is initiated - again
pleaseread the relevant HOWTO's mentioned in this article.
Run 'netconf' from the command line.
Select 'PPP/SLIP/PLIP' from the netconf menu.
Select 'Add' to add a PPP device.
When prompted to select a type of interface, choose 'PPP' and then 'Accept'.
Complete the details 'Phone Number', 'Login Name' and 'Password' for your login to your ISP's server. Also make sure you select the correct modem port, 'ttyS0' being the DOS equivalent of 'COM1', 'ttyS1'==COM2, etc... Unless you know you use PAP to authenticate, leave the PAP checkbox alone - you can always come back later and change it. When you're done, select 'Accept'.
Select 'Quit' to exit the PPP configuration box.
Select 'Quit' to exit 'netconf'.
That's it! Your PPP connection should now be configured correctly. If all is well you should be able to connect to the internet now via your modem by issuing 'ifup ppp0' from the command line. If you are unable to connect from the linux router to the internet at this point, you should consult the PPP-HOWTO for full details on initiating a PPP connection. Please see the References section for full details on obtaining help before contacting me or others for help;-).
4.4 Configuring Which Nameserver The Router Should Use.
4.4.1 What Is A Domain Name Server Anyway?
Currently we should be able to make a connection to the internet okay, but we will be unable to do anything productive. For example, attempting to view a website 'www.asite.com' on the internet will result in failure - this is because our machine has no way of finding out where exactly 'www.asite.com' is located on the internet - our machine has no way of resolving 'www.asite.com' (the fully qualified domain name or FQDN) into it's associated IP address (of the form 'w.x.y.z (ie 213.1.23.233)).
To be able to correctly resolve FQDN's to their corresponding IP addresses, our machine must use a
DNS Nameserver.
You should be able to obtain the IP address of your nearest DNS nameserver from your ISP. If this isn't feasible for whatever reason, there are various ways of determining what DNS server you should use. We will cover one method here involving the use of an internet connected windows machine:
Using a Win95 machine, dialup to the internet.
After connecting and authenticating, run the command 'winipcfg.exe' from the 'Run' item on the 'Start' menu. 'winipcfg.exe' is a very simple but useful tool installed as part of Microsoft's implementation of the TCP/IP protocol suite (other useful tools installed with MS TCP/IP include 'netstat.exe', 'ping.exe', 'arp.exe', 'route.exe', 'telnet.exe', 'snmp.exe' and 'ftp.exe').
Click on the 'More Info' button in the 'winipcfg' dialog box.
The DNS server allocated to you by your ISP should be listed in the 'DNS Server' section! Make a note of this address for further reference.
4.4.2 Configuring The Linux Router To Use DNS
Now we have the IP address of the DNS server, we will move on to discuss configuring our Linux router to use that DNS server for name resolution:
Run 'netconf' from the command-line.
Select 'Nameserver specification (DNS)'.
Check the checkbox next to 'DNS is required for normal operation'.
For 'default domain', just put in the top level domain of your ISP (ie 'lineone.net' for me, 'rr.com', 'aol.com', 'microshoft.com' etc).
For 'IP of nameserver 1' you need to put the IP address of a nameserver that's authoritative for your ISP (as located above).
Leave the rest, unless you wish to add another nameserver for the sake of redundancy (just in case the first nameserver falls down!).
Just out of interest, the above procedure simply adds a couple of lines to the file
/etc/resolv.conffile:domain lineone.net nameserver 194.72.6.51
Note, this is my name server and at a pinch anyone could use it, anywhere in the world! However it's not advisable since if you live in Australia a great deal of time would be wasted using the same NS as me, halfway around the world!
If you have any problems with the configuration of either of the interfaces eth0 or ppp0, or your LAN in general, you
mustconsult the relevant HOWTO's before mailing me or asking others for help. People don't mind helping, as long as you're in a position to understand what it is you need help with.
I highly recommend reading all the relevant HOWTO's before asking for help - namely the Ethernet-HOWTO (for finding out if your ethernet network card is supported and what the relevant kernel modules are), the NET3-HOWTO (for information on setting up your LAN) and the PPP-HOWTO (for information on setting up PPP, surprise surprise;-). See the Reference Section at the end of this article for full details.
4.5 Installing The Masquerading Firewall
4.5.1 What Is A Masquerading Firewall Anyway?
A masquerading firewall is simply an application/kernel modification that acts as a go-between for the masqueraded machines (the winbox in our case) and the internet. It receives requests from the masqueraded client(s) and forwards those requests on to the internet address of the target machine. In this way, a masquerading firewall is a
packet filter- it filters network traffic based on information contained in the headers of network packets.
4.5.2 What Is IPCHAINS?
'ipchains' is a network packet filter as described above. It works closely with the Linux kernel to handle all network traffic arriving and departing from a given network interface (or interfaces).
'ipchains' is initialized with just three rules or 'chains', input, output and forward. When a packet arrives at a network interface it's fate is determined by the input chain; if the packet is accepted by the input chain, the kernel forwards the packet according to the destination address. If the destination address is another machine on the LAN, then the forward and output chains determine the fate of the packet and if the packet is acceptable to these chains, it is routed to the destination machine.
Each of these input, output and forward 'chains' are simply sets of one or more rules which can be built up - one rule at a time. Each rule examines the header information of the packet, and if the information concerns the rule, the rule jumps to accept, reject or deny the packet. If the packet doesn't concern the rule, then the next rule in the chain is checked in the same way. Finally if no rules are relevant to the packet, a default action would usually be set by the sysadmin to deny or reject the packet on the grounds that no rules exist to determine the packet's fate (otherwise potentially harmful packets would be allowed through).
For a masquerading firewall, it makes sense to create three sets of custom chains: one for packets arriving from the internet/external network, one for packets departing to the internet/external network and one for packets which are to be forwarded from the router to the masqueraded clients. This is the approach that we will take, using an incoming chain (inet-in), an outgoing chain (inet-out) and the built in forwarding chain set (forward).
4.5.3 Checking To See If IPCHAINS Is Installed
It's likely that 'ipchains' is already installed on your system (although having said that my 'vanilla' install of mandrake 7.1 doesn't include ipchains;-).
To check whether or not you have ipchains installed, issue 'whereis ipchains' at the command line:
[root@munkbox /etc/rc.d/init.d]# whereis ipchains
ipchains:
We see on my box that ipchains
is notinstalled (if it were we would see something like: ipchains: /usr/bin/ipchains <some path to man pages>:=).
If ipchains is installed on your machine, please feel free to skip ahead to section 4.5.5.
4.5.4 Installing IPCHAINS
Right, lets install it (this assumes installing from the mandrake installation cdrom using the 'rpm' installer - for other distributions installation should be straightforward).
From the command line, issue the command 'rpm -i /mnt/cdrom/Mandrake/RPMS/ipchain*' (modifying the location as required for your system).
We can confirm the installation of ipchains by issuing the command 'whereis ipchains' again:
[root@munkbox /etc/rc.d/init.d]# whereis ipchains
ipchains: /sbin/ipchains /usr/man/man8/ipchains.8.bz2
The fact that the whereis utility has located the ipchains binary and it's man page let's us know that ipchains was installed successfully.
4.5.5 Installing and Configuring the 'rc.firemasq' Script
Time for the fun part! We have the physical network setup and configured; now all that remains is to create a set of rules which will allow the Linux router to forward network traffic to/from the win95 machine and the external network/internet. Rather than create each rule one by one at the command-line (which we could do each time), we will place all the commands for bringing up the firewall into one single script, rc.firemasq.
Essentially the rc.firemasq script works as follows:
ipchains is initialised by first flushing any existing chains/rules
we create new chains for incoming, outgoing and forwarding packets
we assign rules to these chains dictating how packets will be handled
we have the script execute every time a new connection to the internet is made by the linux router
Rather than reinvent the wheel, we will use a script created by Dr. Teeth aptly called
.'firemasq'
In the following section, we will cover the the action of each line of the script - in this way you will be able to modify the script to cater for your own LAN requirements, understanding (hopefully;^=) how the script works.
I'll paste the full-script at the end of this article in it's entirety - there are some very useful comments made by Dr. Teeth within the original version of the script - many thanks go to Dr Teeth.
4.5.6 Setting up the 'rc.firemasq' script
We now create a script that will bring the firewall up every time a connection is made to the internet by the linux router.
Paste everything that follows (from ###### START OF SCRIPT to ###### END OF SCRIPT) into a file called '/etc/rc.d/rc.firemasq' (
make sure you understand the script first!). The '/etc/rc.d' directory is the standard location on Linux systems for custom scripts created after installation intended for bringing services up after booting.
Set the file permissions on
'/etc/rc.d/rc.firemasq'to make the file executable -'chmod +x /etc/rc.d/rc.firemasq'will do the trick.
####### START OF SCRIPT!
#!/bin/sh
# Change IPCHAINS to the correct path for your system
IPCHAINS=/sbin/ipchains
# Change INETDEV to the network device connceted to the Internet (ppp0/eth0)
# This is ppp0 by default for dial-up connections. Most cable modem users
# will probably want eth0 or possibly eth1. When in doubt look at the command
# 'ifconfig'.
INETDEV="ppp0"
# Change LAN to the correct network address and network mask for your LAN
# this can be found by using ifconfig from one of the clients
LAN="192.168.0.0/24"
# Change LANDEV to the network device connected to your LAN
LANDEV="eth0"
# There should be no need to change this: you may need to play with it a little.
# If you have problems, try the command on the command-line, substituing $LANDEV
#for 'eth0' (or 'eth1', etc if you're a cable user).
LOCALIP=`ifconfig $LANDEV | grep inet | cut -d : -f 2 | cut -d B -f 1`
echo ""
echo "FireMasq version 0.7 by Dr. Teeth (2000)"
echo "Rehashed(!) by munk (2001) for http://black.box.sk
echo "---------------------------------------------------------"
echo "Local Network Device: $LANDEV"
echo "Local IP: $LOCALIP"
echo "Local Network Address: $LAN"
echo "External Network Device: $INETDEV"
echo "---------------------------------------------------------"
echo ""
echo "========================================================="
echo " IMPORTANT!"
echo "========================================================="
echo "= If you get an error regarding IP Forwarding not being
echo "= enabled, please check your documentation for details"
echo "= "
echo "=On some distributions you will be required to issue"
echo "=the command:"
echo "=echo "1" > /proc/sys/net/ipv4/ip_forward"
echo "= to enable ip forwarding (ie redhat/mandrake),
echo "= whilst on others a flag may need setting in "
ech0 "= 'etc/rc.d/rc.config' (SuSe I think). On other systems"
ech0 "= the process for enabling forwarding my be different"
ech0 "= yet again. Please check the documentation"
ech0 "= for your distribution."
echo "========================================================="
echo ""
#Set default chain policy
echo -n "Setting default chain policies..."
$IPCHAINS -P input DENY
$IPCHAINS -P forward DENY
$IPCHAINS -P output ACCEPT
echo " Done!"
#Flush all chains: start fresh
echo -n "Flushing chains..."
$IPCHAINS -F
$IPCHAINS -X
echo " Done!"
#Add custom chains
echo -n "Adding custom chains..."
$IPCHAINS -N inet-in # incoming from internet
$IPCHAINS -N inet-out # outgoing onto internet
echo " Done!"
#Set input rules
echo -n "Setting rules for input chain..."
#Any LAN address to any other LAN address is ok:
$IPCHAINS -A input -s $LAN -d $LAN -j ACCEPT
#Loopback interface comms all ok:
$IPCHAINS -A input -s 0.0.0.0/0 -d 0.0.0.0/0 -i lo -j ACCEPT
#Any LAN address to anywhere (including internet) is ok:
$IPCHAINS -A input -s $LAN -d 0.0.0.0/0 -j ACCEPT
#Any comms on the internet interface should be handled by the 'inet-in' chain:
$IPCHAINS -A input -s 0.0.0.0/0 -d 0.0.0.0/0 -i $INETDEV -j inet-in
echo " Done!"
#Set forward rules
echo -n "Setting rules for forward chain..."
#Forwarding LAN TO LAN ok:
$IPCHAINS -A forward -s $LAN -d $LAN -j ACCEPT
#Forwarding LAN to internet ok:
$IPCHAINS -A forward -s $LOCALIP -d 0.0.0.0/0 -j ACCEPT
echo " Done!"
#Activate masquerade
echo -n "Activating masquerade..."
$IPCHAINS -A forward -s $LAN -d 0.0.0.0/0 -j MASQ
#If you have trouble with timeouts, change this line:
$IPCHAINS -M -S 7200 10 60
echo " Done!"
#Set output rules
echo -n "Setting rules for output chain..."
$IPCHAINS -A output -s $LAN -d $LAN -j ACCEPT
$IPCHAINS -A output -s 0.0.0.0/0 -d 0.0.0.0/0 -i lo -j ACCEPT
$IPCHAINS -A output -s $LAN -d 0.0.0.0/0 -j ACCEPT
$IPCHAINS -A output -s 0.0.0.0/0 -d 0.0.0.0/0 -i $INETDEV -j inet-out
echo " Done!"
#Set inet-in rules
echo "Setting rules for internet device incoming chain:"
echo -n " Setup port blocking on vulnerable ports..."
#These ports don't have to be blocked, but as they are
#these rules let you know when you're being attacked on
#the corresponding ports by logging the attack to /var/log/messages
#(or wherever your ipchains logging is done).
#Block NFS
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 2049 -j DENY -l
$IPCHAINS -A inet-in -p udp -s 0.0.0.0/0 -d 0.0.0.0/0 2049 -j DENY -l
#Block postgres
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 postgres -j DENY -l
$IPCHAINS -A inet-in -p udp -s 0.0.0.0/0 -d 0.0.0.0/0 postgres -j DENY -l
#Block X
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 5999:6003 -j DENY -l
$IPCHAINS -A inet-in -p udp -s 0.0.0.0/0 -d 0.0.0.0/0 5999:6003 -j DENY -l
#Block XFS
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 7100 -j DENY -l
$IPCHAINS -A inet-in -p udp -s 0.0.0.0/0 -d 0.0.0.0/0 7100 -j DENY -l
#Block Back Orifice
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 31337 -j DENY -l
$IPCHAINS -A inet-in -p udp -s 0.0.0.0/0 -d 0.0.0.0/0 31337 -j DENY -l
#Block netbus
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 12345:12346 -j DENY -l
$IPCHAINS -A inet-in -p udp -s 0.0.0.0/0 -d 0.0.0.0/0 12345:12346 -j DENY -l
echo " Done!"
echo -n " Allowing ssh, dns, and icmp (ping/traceroute) traffic..."
#Vital for basic communications
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 ssh -d 0.0.0.0/0 -j ACCEPT
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 ssh -j ACCEPT
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 auth -j ACCEPT
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 1023:65535 -j ACCEPT
$IPCHAINS -A inet-in -p udp -s 0.0.0.0/0 -d 0.0.0.0/0 1023:65535 -j ACCEPT
$IPCHAINS -A inet-in -p icmp -s 0.0.0.0/0 -d 0.0.0.0/0 -j ACCEPT
echo " Done!"
echo -n " Setting default input to DENY..."
#This is a 'catchall' rule. If ipchains finds an incoming packet
#NOT covered by the above rules, it will stop the packetand log it
$IPCHAINS -A inet-in -s 0.0.0.0/0 -d 0.0.0.0/0 -j DENY -l
echo " Done!"
#Set inet-out rules
echo "Setting rules for internet device outgoing chain:"
echo -n " Setting TOS flags for www, telnet, ssh, and ftp..."
#TOS flags affect how ipchains prioritizes packets:
#From the IPCHAINS-HOWTO:
#TOS Name Value Typical Uses
#"Minimum Delay" 0x01 0x10 www, ftp, telnet, ssh
#"Maximum Throughput" 0x01 0x08 ftp-data
#"Maximum Reliability" 0x01 0x04 snmp
#"Minimum Cost" 0x01 0x02 nntp
$IPCHAINS -A inet-out -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 www -t 0x01 0x10
$IPCHAINS -A inet-out -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 telnet -t 0x01 0x10
$IPCHAINS -A inet-out -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 ssh -t 0x01 0x10
$IPCHAINS -A inet-out -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 ftp -t 0x01 0x10
$IPCHAINS -A inet-out -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 ftp-data -t 0x01 0x08
echo " Done!"
####### END OF SCRIPT!
4.5.7 Running the script
By now you should have saved the script to a file called '/etc/rc.d/rc.firemasq' and made it executable by issuing 'chmod +x /etc/rc.d/rc.firemasq'. You now need to ensure that the script is run every time your PPP interface is brought up.
The method you use to bring up the firewall every time your machine attachs to the internet will differ from distribution to disrtibution. Ideally on systems that use the '
pppd' PPP daemon for initiating a PPP connection, the best place to execute code every time a PPP connection is made is by adding the code to the file '/etc/ppp/ip-up'.
Place the line
'/etc/rc.d/rc.firemasq&'on a line by itself in the file '/etc/ppp/ip-up', preferably near the top of the ip-up script; here is a snippet from my '/etc/ppp/ip-up' file:
#!/bin/bash
LOGDEVICE=$6
REALDEVICE=$1
export PATH=/sbin:/usr/sbin:/bin:/usr/bin
#Bring up the firemasq in background:
/etc/rc.d/rc.firemasq&
Important
Make sure that you run the '/etc/rc.d/rc.firemasq' in the background, otherwise the execution of other commands in the '/etc/ppp/ip-up' may not occur!
In this section we will install and configure TPC/IP on the Windows 95 machine. The following sections assume you
do notalready have TCP/IP installed on the Windows 95 machine; if you already have TCP/IP installed on your machine, check to make sure that it is configured as specified here.
This section is broken down as follows:
5.1 Installing TCP/IP on the Windows 95 machine
5.2 Assigning a static IP address of 192.168.0.10 to the Windows 95 machine
5.3 Configuring the masqueraded Windows 95 machine to use the Linux router as a gateway (specifying '192.168.0.1' as a Gateway), and
5.4 Configuring the masqueraded Windows 95 machine to use the external DNS server (as covered above)
5.1 Installing TCP/IP On The Windows 95 Masqueraded Client
In Control Panel, open the 'Network' applet.
Ensure your network interface card drivers have been installed correctly (if so they will likely be bound to the NetBEUI and IPX/SPX protocols) - if not, install drivers as required.
Click 'Add' and in the following dialog box, select to add the Microsoft TCP/IP Protocol.
Check to make sure that TCP/IP has been bound to the Network Interface card - you can do this by checking the 'Bindings' tab of the properties for the network card.
Remove all other protocols and services which are not necessary - for the purposes of this article,
the only protocol required is TCP/IP - no services are required.
You should now see only two items in the Network dialog box, one for your Network Interface Card, and the other for TCP/IP.
5.2 Assigning A Static IP Address To The Windows 95 Masqueraded Client
Open the properties dialog for the TCP/IP Protocol.
Select the 'IP Address' tab.
Select the radio 'Assign Static IP Address'.
Enter a static IP address of '192.168.0.10.
Enter '255.255.255.0' as the netmask.
5.3 Configuring The Win95 Machine To Use The Linux Router As A Gateway
Select the 'Gateway' tab in the TCP/IP properties dialog.
Enter '192.168.0.1' as the default gateway.
5.4 Configuring The Win95 Machine To Use The External DNS Server
Select the 'DNS' tab.
Enter the IP address of your DNS server.
Finally, apply the changes to the TCP/IP Protocol settings by clicking 'OK' in the TCP/IP Dialog box, and finally apply the new network settings by click 'OK' in the Network Applet dialog box.
In this section we will test the configuration of the masqueraded network.
This section covers:
6.1 Bring Up The PPP Internet Connection On The Linux Router
6.2 Testing Connectivity From The Linux Router To The External Network/Internet
6.3 Test Connectivity From The Windows 95 Masqueraded Client To The Linux Router
6.4 Test Connectivity From The Windows 95 Masqueraded Client To The External Network/Internet
6.1 Bringing Up the PPP Internet Connection on the Linux Router
Using the preferred method for your distribution, bring up the PPP interface on the linux router. Under Linux Mandrake we use
ifup ppp0from the command-line, or perhaps run 'kppp' from X windows. As mentioned above bringing PPP is worthy of an article in itself, please do see the References section for details (the PPP-HOWTO).
From the command-line, run
ifconfig. In the output you should see something similar to this:<metadata lang=Dockerfile prob=0.14 />
ppp0 Link encap:Point-Point Protocol
inet addr:10.144.153.104 P-t-P:10.144.153.51 Mask:255.255.255.0
UP POINTOPOINT RUNNING MTU:552 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0
TX packets:0 errors:0 dropped:0 overruns:0
If you are unable to get to this point, you should consult the 'PPP-HOWTO'.
6.2 Testing Connectivity From The Linux Router To The External Network/Internet
To test connectivity from the linux router to the external network/internet, issue
'ping -c 4 <NAME OF DNS SERVER>', obviously replacing <NAME OF DNS SERVER> with the address of your DNS Server. The '-c 4' switch simply tells the ping command to send 4 ping requests and then exit.
If all is well, you should see something like the following output:
[root@gateway /etc]# ping -c 4 194.72.6.57
PING 194.72.6.57 (194.72.6.57): 56 octets data
64 octets from 194.72.6.57: icmp_seq=0 ttl=128 time=0.9 ms
64 octets from 194.72.6.57: icmp_seq=1 ttl=128 time=0.8 ms
64 octets from 194.72.6.57: icmp_seq=2 ttl=128 time=0.8 ms
64 octets from 194.72.6.57: icmp_seq=3 ttl=128 time=0.8 ms
If you receive timeout messages, even though you are connected to the external network/internet successfully, this usually indicates that the linux router is unable to communicate with the external network/internet due to name resolution problems. In this case you should check your
'/etc/resolv.conf'file to ensure that the linux router is using the DNS server it should be. See the 'Networking-HOWTO' for full details.
6.3 Testing Connectivity From The Win95 Client To The Linux Router
On the Windows 95 masqueraded client, open a DOS box and issue the command
'ping 192.168.0.1'.
If all is well you should see something like the following output:
C:\WINDOWS\DESKTOP>ping 192.168.0.1
Pinging 192.168.0.1 with 32 bytes of data:
Reply from 192.168.0.1: bytes=32 time=1ms TTL=255
Reply from 192.168.0.1: bytes=32 time=1ms TTL=255
Reply from 192.168.0.1: bytes=32 time<10ms TTL=255
Reply from 192.168.0.1: bytes=32 time<10ms TTL=255
Ping statistics for 192.168.0.1:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 1ms, Average = 0ms
If you have trouble at this point, you should check the network card and TCP/IP settings on the Windows 95 machine, ensuring the network card is installed correctly (using 'Device Manager') and ensuring TCP/IP has been installed and configured correctly (see above).
6.4 Testing Connectivity From The Win95 Client To The External Network/Internet
On the Windows 95 masqueraded client, open a DOS box and issue the command
'ping <NAME OF DNS SERVER>', obviously replacing <NAME OF DNS SERVER> with the IP address of your DNS Server.
If all is well, similar to the above, you should see something like the following output:
C:\WINDOWS\DESKTOP>ping 194.72.6.57
Pinging 194.72.6.57 with 32 bytes of data:
Reply from 194.72.6.57: bytes=32 time=1ms TTL=255
Reply from 194.72.6.57: bytes=32 time=1ms TTL=255
Reply from 194.72.6.57: bytes=32 time<10ms TTL=255
Reply from 194.72.6.57: bytes=32 time<10ms TTL=255
Ping statistics for 194.72.6.57:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 1ms, Average = 0ms
If you have trouble at this point then you should check the TCP/IP settings on the Windows 95 machine, particularly ensuring that the default Gateway is correctly set to '192.168.0.1' see above.
In this section we will look briefly at the logging functionality of '
ipchains'.
This section will cover the following:
7.1 Configuring The Destination Of 'ipchains' Log Output
7.2 A Note On Creating Rules That Log When Matched
7.3 Viewing 'ipchains' Logs
7.4 A Tip On Monitoring Log Files
7.1 Configuring The Destination Of 'ipchains' Log Output
Straight from the '
IPCHAINS-HOWTO':
On standard Linux systems, this kernel output is captured by klogd
(the kernel logging daemon) which hands it to syslogd (the system
logging daemon). The `/etc/syslog.conf' controls the behaviour of
syslogd, by specifying a destination for each `facility' (in our case,
the facility is "kernel") and `level' (for ipchains, the level used is
"info").
For example, my (Debian) /etc/syslog.conf contains two lines which
match `kern.info':
kern.* -/var/log/kern.log
*.=info;*.=notice;*.=warn;\
auth,authpriv.none;\
cron,daemon.none;\
mail,news.none -/var/log/messages
These mean that the messags are duplicated in `/var/log/kern.log' and
`/var/log/messages'. For more details, see `man syslog.conf'.
The upshot of this is that the output from ipchains rules which are set to log when they are matched is usually sent to '/var/log/messages' by the
syslogdsystem logging daemon, but you should make sure and check '/etc/syslog.conf' just to make sure.
7.2 A Note On Creating Rules That Log When Matched
To create rules that log details when they are matched, use the '-l' switch at the end of the rule. If you look at the '
/etc/rc.d/rc.firemasq' you created earlier, you will find various rules which utilise the logging functionality of ipchains:
#Block Back Orifice
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 31337 -j DENY -l
$IPCHAINS -A inet-in -p udp -s 0.0.0.0/0 -d 0.0.0.0/0 31337 -j DENY -l
Here we see a rule assigned to deny all incoming packets bound for the local port '31337', the port used by the 'Back Orifice' trojan horse server to communicate with remote clients. This logs any attempt to connect to this port, due to the fact that the '-l' switch is specified at the end of the rule.
Note: the logging of attempts to connect to ports used by trojan horses may seem odd since trojan horses such as Back Orifice do not apply to Linux - even if a masquerading client
didhave the Back Orifice trojan horse server on it, a remote BO client would be unable to connect to it through the firewall. However sometimes it is nice to have a record of such attempts, and since ipchains logging comes with very little to no overheard, it might as well be used in instances which might be deemed 'offensive' (such as a probe for a trojan server).
7.3 Viewing 'ipchains' Logs
Presuming that you have checked your '
/etc/syslog.conf' file and know that 'ipchains' is logging to '/var/log/messages', viewing the log file is as simple as using your favourite pager or editor to view '/var/log/messages', ie issuing 'less /var/log/messages' at the command-line.
You will need to scroll to the end of the log file to find the most recent details logged by ipchains. With this in mind, the following tip can be very useful in monitoring ipchains rule matching.
7.4 A Tip On Monitoring Log Files
Rather than open up '
/var/log/messages' and then scroll to the end of the file to see the most recent ipchains logging output, a nice way of constantly monitoring the default log file is to 'tail' the output from the '/var/log/messages' with the '-f' switch:
[root@gateway ~]# tail -f /var/log/messages
Feb 28 20:10:00 gateway CROND[961]: (root) CMD ( /sbin/rmmod -as)
Feb 28 20:17:39 gateway PAM_unix[768]: (system-auth) session opened for user
munk by LOGIN(uid=0)
Feb 28 20:17:39 gateway -- munk[768]: LOGIN ON tty2 BY munk
Feb 28 20:18:29 gateway kernel: Packet log: inet-in DENY ppp0 PROTO=17
207.71.92.221:137 62.6.89.183:137 L=78 S=0x00 I=37898 F=0x0000 T=112 (#19)
Feb 28 20:18:30 gateway kernel: Packet log: inet-in DENY ppp0 PROTO=17
207.71.92.221:137 62.6.89.183:137 L=78 S=0x00 I=38143 F=0x0000 T=112 (#19)
The '-f' switch used with '
tail' causes the file viewed by tail to be monitored in real time; so, as soon as a new log message is created byanyprocess which uses the syslogd daemon, it will be output to the screen by 'tail -f /var/log/messages'. For the extremely security conscious and the paranoid in general(!), a good idea is to dedicate a virtual console to viewing the output from '/var/log/messages' by using the command 'tail -f /var/log/messages'.
Congratulations! If you have managed to get this far then you should now be able to successfully share the single internet connection between your two (or more) machines, safe in the knowledge that all incoming and outgoing connections from/to your LAN are being monitored. The script we have used to setup the masquerading firewall is not overly strict and should only be used as a foundation for building your own personalized script, one which will cater better for your own LAN needs.
I hope you have found the information in this article useful and concise. Please feel free to send me comments on the article (abuse>/dev/null please!) and let me know how you got on. On this note,
make sure you read the following first!!!PLEASE
Trouble-shooting most linux system configurations can at best be difficult and at worst a nightmare, but in terms of reliability and security there is no alternative. I have attempted to make the steps required in configuring your network for IP Masquerading as concise as possible, however it is inevitable that problems will need to be overcome before your setup is complete and fully functioning.
Approximately(!) %100 of linux problems are resoluable by the user, you and me, given the time and more importantly the patience! There is no substitute for reading. Reading gives rise to knowledge and as we all know, knowledge is power; hence it follows that reading empowers the reader. This is undoubtably true with Linux.
The knowledge I pass onto you in this document has come courtesy of almost inumerable sources, coffee being second only to
Documentation. Many thanks to all the authors of the excellent Linux HOWTO's out there, not to mention good friends, man pages, books, internet material, and so on and so forth.
The following Reference section should cover just about every area discussed in this article. Before attempting to get help from anyone else, please do read the relevant documents below.
Linux HOWTOS
First off, check to see if you have the Linux HOWTO's installed on your system by issuing the command '
find / -iname "*howto*"' at the command-line. Check the output and hopefully you'll find that the HOWTO's are already installed on your system.
If the HOWTO's are not installed on your system you have two options: either you can view the HOWTO's online or you can download them and install them on your system. The latter option is preferable! You can find the linux HOWTO's at the Linux Documentation Project (LDP) website, http://www.linuxdoc.org.
The HOWTO's specific to this document are:
Networking-Overview-HOWTO - a good document for beginners to networking using linux.
The Linux Network Administrator's Guide (NAG) - not really a HOWTO, but located at the LDP site; another excellent introduction to networking on linux for beginners and intermediate users.
Net-HOWTO - the reference for setting up your network under linux.
Ethernet-HOWTO - lists ethernet cards supported by linux and their associated drivers; useful if you have problems setting up your network card(s).
Firewall-HOWTO - provides advice for various firewalling scenarios.
IP-Masquerade-HOWTO - specific to masquerading firewall's.
IPCHAINS-HOWTO - by the creator of the ipchains packet filter; good for obtaining deeper knowledge of how chains and rules work.
ISP-Hookup-HOWTO - step by step guide to dialling up to your ISP; good if you have trouble connecting to internet.
PPP-HOWTO - essential reading if you have problems connecting to internet via PPP.
Online Linux Firewall / Security Sites
There are numerous sources of help for setting up your firewall under linux, whether for masquerading or otherwise.
The Original Firemasq Site - the home of the original 'firemasq' script used in this article.
The Linux IP Masquerade Resource - the home of IP Masquerading on the internet!
FAQ: Firewall Forensics (What am I seeing?) - a good site on interpreting your firewall logs.
Linux Security Administrator's Guide - similar to the NAG, but with emphasis on general security - worth a skim read at least.
Total Simplicity Security Scan - test your firewall setup with this online scanner.
Here is the original 'firemasq' script in it's entirety:
#!/bin/sh
# Masqueraing Firewall
# Script for IPChains on Linux 2.2.14 kernel
# Released under the GNU GPL (http://www.fsf.org/copyleft/gpl.html)
# Copyleft 2000 by Dr. Teeth (this is open source, hack away...)
# drteeth@northernlights.bizland.com
# Check http://northernlights.bizland.com for new versions of this program
# and for other computer security related tools and information.
# This is a script for any box running ipchains on a Linux 2.2.x kernel
# (RedHat 6.x, Mandrake 7.x, etc). In particular, this script is for a box
# with a dial-up internet connection; it will turn the box into a firewall
# with masquerading services. All clients that connect to the firewall
# via a local network can simultaneously connect to the Internet, or any
# other network segment the firewall is connected to. This script can also
# be used for today's "high speed internet access" enabled machines, for
# example machines connected to cable modems and dsl routers.
# If you do not need masquerading servives, but you still want to setup a
# firewall for a dial-up, dsl, cable modem, or ethernet connection on a
# single computer, you can download the script "firedog" from the Northern
# Lights Group's site at http://northernlights.bizland.com.
# All denied packets are logged via the kernel's packet logging facilities.
# Check '/var/log/messages' on most systems for a log of denied traffic...
# Any clients using masquerading will "borrow" the IP address of the firewall
# router, so outside machines will always see the firewall, not any of the
# clients on the LAN. This is actually a nice side effect of masquerading, as
# outsiders can't easily get a picture of what's on the inside of the firewall
# if they never see the LAN clients' IP addresses.
# Remember that most dial-up connections have a unique IP address with every
# connection. While you could manually start and stop the firewall, I
# would highly suggest storing this executable in '/sbin' and then starting
# it by adding the line '/sbin/firemasq' to the end of '/etc/ppp/ip-up' (at
# the next-to-last line, before the line 'exit 0'). This will automatically
# start the firewall with the correct IP on every connection, even when the
# connection is lost and it redials.
# Copy the script 'firemasq.down' to '/sbin' as well, then you can deactivate
# the firewall with a simple 'firemasq.down' command if needed.
# This script sets up more than adaquate protection for a dial-up connection.
# Most services are blocked from the outside but not from the inside. For
# example, you can still telnet, ftp, etc. the firewall from the LAN, but hosts
# on the Internet cannot. You may want to add more sections to block the known
# cable modem nets in your area (think script kiddie protection).
# There is a further layer of protection for LAN clients who use IP's from the
# "private" ranges '10.x.x.x', '172.16.x.x - 172.31.x.x', and
# '192.168.0.x - 192.168.255.x'. These clients are in the Internet's
# "blackhole", and routers are not capable of directing traffic to these
# "private" hosts.
# You will need to edit settings for your network, changing the network
# addresses and devices if needed. The path for ipchains is probablly okay,
# but you can change it if nessesary. You only have to change this information
# in the beginning of the script (below). The script will take care of the
# rest.
# You can stop a certain line or section from executing by adding a pound '#'
# character to the begginning of the line...
# Advanced users already know they can add lines with '$IPCHAINS [options]'.
# run 'man ipchains' for more info...
# Change IPCHAINS to the correct path for your system
IPCHAINS=/sbin/ipchains
# Change INETDEV to the network device connceted to the Internet (ppp0/eth0)
# This is ppp0 by default for dial-up connections. Most cable modem users
# will probably want eth0 or possibly eth1. When in doubt look at the command
# 'ifconfig'.
INETDEV="ppp0"
# Change LAN to the correct network address and network mask for your LAN
# this can be found by using ifconfig from one of the clients
LAN="192.168.0.0/24"
# Change LANDEV to the network device connected to your LAN
LANDEV="eth0"
# There should be no need to change this
#LOCALIP=`ifconfig $LANDEV | grep inet | cut -d : -f 2 | cut -d \ -f 1`
LOCALIP=`ifconfig $LANDEV | grep inet | cut -d : -f 2 | cut -d B -f 1`
echo ""
echo "FireMasq version 0.7 by Dr. Teeth (2000)"
echo "---------------------------------------------------------"
echo "Local Network Device: $LANDEV"
echo "Local IP: $LOCALIP"
echo "Local Network Address: $LAN"
echo "External Network Device: $INETDEV"
echo "---------------------------------------------------------"
echo ""
echo "========================================================="
echo "= IMPORTANT! ="
echo "========================================================="
echo "= Make sure that IP Forwarding is on for your network ="
echo "= by checking the file '/etc/sysconfig/network' for ="
echo "= 'FORWARD_IPV4=true' ="
echo "= ="
echo "= This script will not work otherwise! ="
echo "========================================================="
echo ""
#Set default chain policy
echo -n "Setting default chain policies..."
$IPCHAINS -P input DENY
$IPCHAINS -P forward DENY
$IPCHAINS -P output ACCEPT
echo " Done!"
#Flush all chains
echo -n "Flushing chains..."
$IPCHAINS -F
$IPCHAINS -X
echo " Done!"
#Add custom chains
echo -n "Adding custom chains..."
$IPCHAINS -N inet-in
$IPCHAINS -N inet-out
echo " Done!"
#Set input rules
echo -n "Setting rules for input chain..."
$IPCHAINS -A input -s $LAN -d $LAN -j ACCEPT
$IPCHAINS -A input -s 0.0.0.0/0 -d 0.0.0.0/0 -i lo -j ACCEPT
$IPCHAINS -A input -s $LAN -d 0.0.0.0/0 -j ACCEPT
$IPCHAINS -A input -s 0.0.0.0/0 -d 0.0.0.0/0 -i $INETDEV -j inet-in
echo " Done!"
#Set forward rules
echo -n "Setting rules for forward chain..."
$IPCHAINS -A forward -s $LAN -d $LAN -j ACCEPT
$IPCHAINS -A forward -s $LOCALIP -d 0.0.0.0/0 -j ACCEPT
echo " Done!"
#Activate masquerade
echo -n "Activating masquerade..."
$IPCHAINS -A forward -s $LAN -d 0.0.0.0/0 -j MASQ
$IPCHAINS -M -S 7200 10 60
echo " Done!"
#Set output rules
echo -n "Setting rules for output chain..."
$IPCHAINS -A output -s $LAN -d $LAN -j ACCEPT
$IPCHAINS -A output -s 0.0.0.0/0 -d 0.0.0.0/0 -i lo -j ACCEPT
$IPCHAINS -A output -s $LAN -d 0.0.0.0/0 -j ACCEPT
$IPCHAINS -A output -s 0.0.0.0/0 -d 0.0.0.0/0 -i $INETDEV -j inet-out
echo " Done!"
#Set inet-in rules
echo "Setting rules for internet device incoming chain:"
echo -n " Setup port blocking on vulnerable ports..."
#Block NFS
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 2049 -j DENY -l
$IPCHAINS -A inet-in -p udp -s 0.0.0.0/0 -d 0.0.0.0/0 2049 -j DENY -l
#Block postgres
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 postgres -j DENY -l
$IPCHAINS -A inet-in -p udp -s 0.0.0.0/0 -d 0.0.0.0/0 postgres -j DENY -l
#Block X
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 5999:6003 -j DENY -l
$IPCHAINS -A inet-in -p udp -s 0.0.0.0/0 -d 0.0.0.0/0 5999:6003 -j DENY -l
#Block XFS
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 7100 -j DENY -l
$IPCHAINS -A inet-in -p udp -s 0.0.0.0/0 -d 0.0.0.0/0 7100 -j DENY -l
#Block Back Orifice
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 31337 -j DENY -l
$IPCHAINS -A inet-in -p udp -s 0.0.0.0/0 -d 0.0.0.0/0 31337 -j DENY -l
#Block netbus
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 12345:12346 -j DENY -l
$IPCHAINS -A inet-in -p udp -s 0.0.0.0/0 -d 0.0.0.0/0 12345:12346 -j DENY -l
echo " Done!"
echo -n " Allowing ssh, dns, and icmp (ping/traceroute) traffic..."
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 ssh -d 0.0.0.0/0 -j ACCEPT
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 ssh -j ACCEPT
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 auth -j ACCEPT
$IPCHAINS -A inet-in -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 1023:65535 -j ACCEPT
$IPCHAINS -A inet-in -p udp -s 0.0.0.0/0 -d 0.0.0.0/0 1023:65535 -j ACCEPT
$IPCHAINS -A inet-in -p icmp -s 0.0.0.0/0 -d 0.0.0.0/0 -j ACCEPT
echo " Done!"
echo -n " Setting default input to DENY..."
$IPCHAINS -A inet-in -s 0.0.0.0/0 -d 0.0.0.0/0 -j DENY -l
echo " Done!"
#Set inet-out rules
echo "Setting rules for internet device outgoing chain:"
echo -n " Setting TOS flags for www, telnet, ssh, and ftp..."
$IPCHAINS -A inet-out -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 www -t 0x01 0x10
$IPCHAINS -A inet-out -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 telnet -t 0x01 0x10
$IPCHAINS -A inet-out -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 ssh -t 0x01 0x10
$IPCHAINS -A inet-out -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 ftp -t 0x01 0x10
$IPCHAINS -A inet-out -p tcp -s 0.0.0.0/0 -d 0.0.0.0/0 ftp-data -t 0x01 0x08
echo " Done!" |
I'm trying to scrape information about new album releases of a site, and I'm handling this via Nokogiri. The idea would be to create a nice array that would contain items like so
[ 0 => ['The Wall', 'Pink Floyd', '1979'], 1 => ['Led Zeppelin I', 'Led Zeppelin', '1969'] ]
This is my current code. I'm a total ruby newbie so any suggestion would be greatly appreciated.
@events = Array.new()
# for every date we encounter
doc.css("#main .head_type_1").each do |item|
date = item.text
# get every albumtitle
doc.css(".albumTitle").each_with_index do |album, index|
album = album.text
@events[index]['album'] = album
@events[index]['release_date'] = date
end
#get every artistname
doc.css(".artistName").each do |artist|
artist = artist.text
@events[index]['artist'] = artist
end
end
puts @events
P.S. the format of the page I'm trying to scrape is a bit weird:
<tr><th class="head_type_1">20 October 1989</th></tr>
<tr><td class="artistName">Jean Luc-Ponty</td><td class="albumTitle">Some example album</td></tr>
<tr><td class="artistName">Some Other Artist</td><td class="albumTitle">Some example album</td></tr>
<tr><td class="artistName">Some Other Artist</td><td class="albumTitle">Some example album</td></tr>
<tr><th class="head_type_1">29 October 1989</th></tr>
<tr><td class="artistName">Some Other Artist</td><td class="albumTitle">Some example album</td></tr>
When I try to run this within the ruby interpreter I get the following errors:
get_events.rb:25:in `block (2 levels) in <main>': undefined method `[]=' for nil:NilClass (NoMethodError)
from /Users/adrian/.rvm/gems/ruby-1.9.3-p286/gems/nokogiri-1.5.5/lib/nokogiri/xml/node_set.rb:239:in `block in each'
from /Users/adrian/.rvm/gems/ruby-1.9.3-p286/gems/nokogiri-1.5.5/lib/nokogiri/xml/node_set.rb:238:in `upto'
from /Users/adrian/.rvm/gems/ruby-1.9.3-p286/gems/nokogiri-1.5.5/lib/nokogiri/xml/node_set.rb:238:in `each'
from get_events.rb:23:in `each_with_index'
from get_events.rb:23:in `block in <main>'
from /Users/adrian/.rvm/gems/ruby-1.9.3-p286/gems/nokogiri-1.5.5/lib/nokogiri/xml/node_set.rb:239:in `block in each'
from /Users/adrian/.rvm/gems/ruby-1.9.3-p286/gems/nokogiri-1.5.5/lib/nokogiri/xml/node_set.rb:238:in `upto'
from /Users/adrian/.rvm/gems/ruby-1.9.3-p286/gems/nokogiri-1.5.5/lib/nokogiri/xml/node_set.rb:238:in `each'
from get_events.rb:18:in `<main>'
How do I fix this? |
Leo 7
Re : A quoi ressemble votre environnement - printemps/été 2012
J'adore ton unity Mario_26
Est-ce que tu peux me donner le lien du wall STP, je le touve très zoli.
Merci d'avance
A+
hp 625: Ubuntu LTS xfce / Mac Mini ppc G4: Debian stable xfce / Les choses les plus simples sont les meilleures !
Hors ligne
Major Grubert
Re : A quoi ressemble votre environnement - printemps/été 2012
Très élégant, tu as les sources ?
Hors ligne
cherrak
Re : A quoi ressemble votre environnement - printemps/été 2012
J'adore ton unity Mario_26 smile
Est-ce que tu peux me donner le lien du wall STP, je le touve très zoli.
Merci d'avance
A+
Quand a moi j'aimerai bien ton conky stp (ma copine l'adore)
Tres beau bureau en tous cas
titou345
Re : A quoi ressemble votre environnement - printemps/été 2012
J'adore ton unity Mario_26
Est-ce que tu peux me donner le lien du wall STP, je le touve très zoli.
Merci d'avance
A+
C'est un des (beaux) fonds d'écran par défaut de Ubuntu 12.04 que tu peux retrouver ici :
Machin a dit truc-bidule.
Bref, moi je suis cultivé quoi.
Hors ligne
titou345
Re : A quoi ressemble votre environnement - printemps/été 2012
Comment tu appliques les thèmes d'icônes sur Precise ?
Machin a dit truc-bidule.
Bref, moi je suis cultivé quoi.
Hors ligne
Laurent_chébran
Re : A quoi ressemble votre environnement - printemps/été 2012
Comment tu appliques les thèmes d'icônes sur Precise ?
Tu vas planter ton ficher dans usr/share/icons en démarrant nautilus en root et ensuite tu changes le thème en passant par gnome-tweak-tool..
Hors ligne
Leo 7
Re : A quoi ressemble votre environnement - printemps/été 2012
@titou345: Merci
hp 625: Ubuntu LTS xfce / Mac Mini ppc G4: Debian stable xfce / Les choses les plus simples sont les meilleures !
Hors ligne
titou345
Re : A quoi ressemble votre environnement - printemps/été 2012
titou345 a écrit :
Comment tu appliques les thèmes d'icônes sur Precise ?
Tu vas planter ton ficher dans usr/share/icons en démarrant nautilus en root et ensuite tu changes le thème en passant par gnome-tweak-tool..
Merci à toi. J'avais un doute sur la compatibilité de Gnome-tweak-tool avec la dernière version de Unity.
Machin a dit truc-bidule.
Bref, moi je suis cultivé quoi.
Hors ligne
hells_dark
Re : A quoi ressemble votre environnement - printemps/été 2012
Très élégant, tu as les sources ?
conky
#!/usr/bin/conky -d -c
## .conkyrc configuration
alignment top_right
background yes
cpu_avg_samples 2
default_color fff # szary 5f5f5f
default_outline_color 000000 # Black
default_shade_color 000000 # Black
double_buffer yes
draw_borders no
draw_graph_borders no
draw_outline no
draw_shades no
gap_x 0
gap_y 450
max_specials 1024
max_user_text 10000
maximum_width 150
minimum_size 150
net_avg_samples 2
no_buffers yes
override_utf8_locale yes
own_window yes
own_window_colour 000000 # Black
own_window_hints undecorated,below,sticky,skip_taskbar,skip_pager
own_window_transparent yes
#own_window_type normal
pad_percents 2
short_units yes
stippled_borders 3
text_buffer_size 8000
total_run_times 0
update_interval 1.0
uppercase no
use_spacer right
use_xft yes
xftalpha 1
xftfont Freesans:pixelsize=9
TEXT
${font helvetica:pixelsize=11}
${offset 50}Galaxy S3
${offset 50}${texeci 180 ~/.conky/scripts/rebours.sh 05/03/2012}
${offset 50}Ubuntu 12.04
${offset 50}${texeci 180 ~/.conky/scripts/rebours.sh 04/26/2012}
${offset 50}Mails
${offset 50}${texeci 180 python ~/.conky/scripts/check_gmail_cpt.py} message(s)
${image ~/.conky/images/android.png -p 20,25}
${image ~/.conky/images/ubuntu.png -p 20,72}
${image ~/.conky/images/mail.gif -p 20,118}
compte à rebours
#!/bin/bash
# Conky CountDown - Script de compte à rebours
upd=$(date +%s -d $1)
acts=$(date +%m/%d/%Y)
act=$(date +%s -d $acts)
diff=$(($upd-$act))
jours=$(($diff/3600/24))
if [ $jours -le 0 ]
then
echo "Date atteinte !"
else
echo "$jours jours"
fi
exit 0
gmail
import os
import string
#Enter your username and password below within double quotes
# eg. username="username" and password="password"
username="username"
password="password"
com="wget -O - https://"+username+":"+password+"@mail.google.com/mail/feed/atom --no-check-certificate"
temp=os.popen(com)
msg=temp.read()
index=string.find(msg,"<fullcount>")
index2=string.find(msg,"</fullcount>")
fc=int(msg[index+11:index2])
print fc
Hors ligne
Major Grubert
Re : A quoi ressemble votre environnement - printemps/été 2012
merci, je regarde ça demain
Hors ligne
Theo46300
Re : A quoi ressemble votre environnement - printemps/été 2012
Tous bureau sont très jolis ici
Très beau bureau hells_dark tu pourrai donné le lien du wallpaper stp.
Dernière modification par Theo46300 (Le 04/05/2012, à 07:07)
Ubuntu 12.04 (32 bit)-gnome-shell
Packard-bell easynote mx51
Une fois que l'on a découvert Linux on ne peut plus s'en passer.
Hors ligne
The Uploader
Re : A quoi ressemble votre environnement - printemps/été 2012
Après le Xfce "à la Unity", voici le Xfce "à la Gnome Shell" :
http://forum.xfce.org/viewtopic.php?id=6928
La classe!
Dernière modification par The Uploader (Le 04/05/2012, à 11:17)
Passer de Ubuntu 10.04 à Xubuntu 12.04 LTS
Archlinux + KDE sur ASUS N56VV.
ALSA, SysV, DBus, Xorg = Windows 98 !
systemd, kdbus, ALSA + PulseAudio, Wayland = modern OS (10 years after Windows, but still...) ! Deal with it !
Hors ligne
Major Grubert
Re : A quoi ressemble votre environnement - printemps/été 2012
GS c'est avant tout un mode exposition, pas tellement une apparence. Enfin je trouve.
Hors ligne
Mario_26
Re : A quoi ressemble votre environnement - printemps/été 2012
Salut !
@ Leo 7 : Effectivement c'est un des Wall qui se trouve dans Ubuntu 12.04...
@ cherrak : Le Conky se trouve sur Gnome Look ici, à toi de l'adapter à ta sauce
Je vois énormement de Arch, bien que nous somme sur le forum de Ubuntu... Je vous montre donc la mienne
Très simple mais aussi très efficace !!
++
Hors ligne
cherrak
Re : A quoi ressemble votre environnement - printemps/été 2012
Ok merci !
Tres joli bureau
Major Grubert
Re : A quoi ressemble votre environnement - printemps/été 2012
Petit succès pour toi hells
Pour moi, top bureau :
. Gnome shell : une preuve du bon goût
. Un conky discret et élégant
. Un fond d'écran distingué
On partage les mêmes valeurs
Hors ligne
Heliox
Re : A quoi ressemble votre environnement - printemps/été 2012
[HS]
Pour ceux que ça intéresse, sur Fedora il est possible d'avoir les thèmes Ambiance et Radiance (ceux inclus par défaut avec Ubuntu) dans Gnome 3 :
# yum install light-theme-gnome
Reste Gnome-Shell qui n'est pas en accord avec ces thèmes…
[/HS]
Dernière modification par Heliox (Le 05/05/2012, à 12:33)
titou345
Re : A quoi ressemble votre environnement - printemps/été 2012
Très épuré, très classe, bravo.
Tu utilises Gnome Shell avec Ubuntu ? Quel est ton thème ?
Merci.
Dernière modification par titou345 (Le 06/05/2012, à 00:23)
Machin a dit truc-bidule.
Bref, moi je suis cultivé quoi.
Hors ligne
Leo 7
Re : A quoi ressemble votre environnement - printemps/été 2012
hp 625: Ubuntu LTS xfce / Mac Mini ppc G4: Debian stable xfce / Les choses les plus simples sont les meilleures !
Hors ligne
pololasi
Re : A quoi ressemble votre environnement - printemps/été 2012
Voici le mien du moment, sous crunchbang :
Toujours aussi classe et précis tes environnements.
Thinkpad X 200 ; Intel Core2 Duo CPU P8600 ; 2 Go de DDR3 ; Intel 4500MHD Xubuntu 14.04.1 LTS 64 bits
Athlon XP 3000+ ; Asus A7V400MX ; ATI Radeon X1600 ; 2 giga de ram Xubuntu 12.04.3 LTS 32 bits
Hors ligne |
I have some inherited code for FlexLM that is converting an integer to a pointer that needs to work on both 32bit and 64bit machines. The integer is being filled in from argc of the arguments to the program using scanf to read the integer value.
How should I reliably read the argc string to get a value suitable for assigning to a pointer so that it works on both 32bit and 64bit machines?
Presently the code looks something like this:
// FlexLM includes this:
typedef char * LM_A_VAL_TYPE; /* so that it will be big enough for */
/* any data type on any system */
// My main() includes this:
[...]
if (!strcmp(argv[i], "-maxlen")) {
int max = 0;
i++;
if (i >= argc) {
break;
}
sscanf(argv[i], "%d", &max);
if (!max) {
fprintf(stderr, "Error: -maxlen %s Invalid line length\n", argv[i]);
} else {
lc_set_attr(lm_job, LM_A_MAX_LICENSE_LEN, (LM_A_VAL_TYPE)max);
}
}
[...]
At first I was thinking I could use uintptr_t, but how would I get scanf to know the size accordingly? Perhaps I should just read it as a pointer value using %p, but the man page gives me doubts about it working reliably:
p Matches an implementation-defined set of sequences, which shall be the
same as the set of sequences that is produced by the %p conversion
specification of the corresponding fprintf() functions. The
application shall ensure that the corresponding argument is a pointer
to a pointer to void. The interpretation of the input item is
implementation-defined. If the input item is a value converted earlier
during the same program execution, the pointer that results shall
compare equal to that value; otherwise, the behavior of the %p
conversion specification is undefined.
I'd rather not use #ifdef to make two separate versions based on pointer size as that seems like an ugly wart on the code to me. |
ZhangHuangbin wrote:
*) You should remove it from Postfix, that's why you need this plugin for per-user restriction.
Check!
It works now. I just updated the plugin a little:
"""Reject sender login mismatch (sender in mail header and SASL username)."""
import logging
from libs import SMTP_ACTIONS
REQUIRE_LOCAL_SENDER = False
REQUIRE_LOCAL_RECIPIENT = False
SENDER_SEARCH_ATTRLIST = []
RECIPIENT_SEARCH_ATTRLIST = []
# Allow sender login mismatch for below senders.
ALLOWED_SENDERS = ['some-email-address@here.com']
def restriction(**kwargs):
# The sender appears in 'From:' header.
sender = kwargs['sender']
# Username used to perform SMTP auth
sasl_username = kwargs['smtp_session_data'].get('sasl_username', '').lower()
logging.debug('Sender: %s, SASL username: %s' % (sender, sasl_username))
if sasl_username: # Is a outgoing email
# Compare them
if sender != sasl_username:
if sasl_username in ALLOWED_SENDERS:
return SMTP_ACTIONS['default']
else:
# Log message without reject.
logging.info('Sender login mismatch.')
# Reject without reason.
#return SMTP_ACTIONS['reject']
# Reject with reason.
# There must be a space between smtp action and reason text.
return SMTP_ACTIONS['reject'] + ' ' + 'Sender login mismatch.'
return SMTP_ACTIONS['default']
Within the "else" tree, there was no return statement active.
So it always returned SMTP_ACTIONS['default'] even if it should have returned SMTP_ACTIONS['reject'].
Thank you very much! A very nice feature!
Best,
Achim |
I have a line from A to B and a circle positioned at C with the radius R.
What is a good algorithm to use to check whether the line intersects the circle? And at what coordinate along the circles edge it occurred?
Taking
Compute:
Then the intersection is found by..
(h,k) = center of circle.
So we get:
So solving the quadratic equation:
float a = d.Dot( d ) ;
float b = 2*f.Dot( d ) ;
float c = f.Dot( f ) - r*r ;
float discriminant = b*b-4*a*c;
if( discriminant < 0 )
{
// no intersection
}
else
{
// ray didn't totally miss sphere,
// so there is a solution to
// the equation.
discriminant = sqrt( discriminant );
// either solution may be on or off the ray so need to test both
// t1 is always the smaller value, because BOTH discriminant and
// a are nonnegative.
float t1 = (-b - discriminant)/(2*a);
float t2 = (-b + discriminant)/(2*a);
// 3x HIT cases:
// -o-> --|--> | | --|->
// Impale(t1 hit,t2 hit), Poke(t1 hit,t2>1), ExitWound(t1<0, t2 hit),
// 3x MISS cases:
// -> o o -> | -> |
// FallShort (t1>1,t2>1), Past (t1<0,t2<0), CompletelyInside(t1<0, t2>1)
if( t1 >= 0 && t1 <= 1 )
{
// t1 is the intersection, and it's closer than t2
// (since t1 uses -b - discriminant)
// Impale, Poke
return true ;
}
// here t1 didn't intersect so we are either started
// inside the sphere or completely past it
if( t2 >= 0 && t2 <= 1 )
{
// ExitWound
return true ;
}
// no intn: FallShort, Past, CompletelyInside
return false ;
}
No one seems to consider projection, am I completely off track here?
Project the vector
Like this:
Okay, I won't give you code, but since you have tagged this algorithm, I don't think that will matter to you. First, you have to get a vector perpendicular to the line.
You will have an unknown variable in
That is,
This will give you the closest point on the line to the circle.
I would use the algorithm to compute the distance between a point (circle center) and a line (line AB). This can then be used to determine the intersection points of the line with the circle.
Let say we have the points A, B, C. Ax and Ay are the x and y components of the A points. Same for B and C. The scalar R is the circle radius.
Here is the algorithm
// compute the euclidean distance between A and B
LAB = sqrt( (Bx-Ax)²+(By-Ay)² )
// compute the direction vector D from A to B
Dx = (Bx-Ax)/LAB
Dy = (By-Ay)/LAB
// Now the line equation is x = Dx*t + Ax, y = Dy*t + Ay with 0 <= t <= 1.
// compute the value t of the closest point to the circle center (Cx, Cy)
t = Dx*(Cx-Ax) + Dy*(Cy-Ay)
// This is the projection of C on the line from A to B.
// compute the coordinates of the point E on line and closest to C
Ex = t*Dx+Ax
Ey = t*Dy+Ay
// compute the euclidean distance from E to C
LEC = sqrt( (Ex-Cx)²+(Ey-Cy)² )
// test if the line intersects the circle
if( LEC < R )
{
// compute distance from t to circle intersection point
dt = sqrt( R² - LEC²)
// compute first intersection point
Fx = (t-dt)*Dx + Ax
Fy = (t-dt)*Dy + Ay
// compute second intersection point
Gx = (t+dt)*Dx + Ax
Gy = (t+dt)*Dy + Ay
}
// else test if the line is tangent to circle
else if( LEC == R )
// tangent point to circle is E
else
// line doesn't touch circle
Another method uses the triangle ABC area formula. The intersection test is simpler and more efficient than the projection method, but finding the coordinates of the intersection point requires more work. At least it will be delayed to the point it is required.
The formula to compute the triangle area is : area = bh/2
where b is the base length and h is the height. We chose the segment AB to be the base so that h is the shortest distance from C, the circle center, to the line.
Since the triangle area can also be computed by a vector dot product we can determine h.
// compute the triangle area times 2 (area = area2/2)
area2 = abs( (Bx-Ax)*(Cy-Ay) - (Cx-Ax)(By-Ay) )
// compute the AB segment length
LAB = sqrt( (Bx-Ax)² + (By-Ay)² )
// compute the triangle height
h = area2/LAB
// if the line intersects the circle
if( h < R )
{
...
}
You could optimize the code by using the fast inverse square root computation described here to get a good approximation of 1/LAB.
Computing the intersection point is not that difficult. Here it goes
// compute the line AB direction vector components
Dx = (Bx-Ax)/LAB
Dy = (By-Ay)/LAB
// compute the distance from A toward B of closest point to C
t = Dx*(Cx-Ax) + Dy*(Cy-Ay)
// t should be equal to sqrt( (Cx-Ax)² + (Cy-Ay)² - h² )
// compute the intersection point distance from t
dt = sqrt( R² - h² )
// compute first intersection point coordinate
Ex = Ax + (t-dt)*Dx
Ey = Ay + (t-dt)*Dy
// compute second intersection point coordinate
Fx = Ax + (t+dt)*Dx
Fy = Ay + (t+dt)*Dy
If h = R then the line AB is tangent to the circle and the value dt = 0 and E = F. The point coordinates are those of E and F.
You should check that A is different of B and the segment length is not null if this may happen in your application.
You can find a point on a infinite line that is nearest to circle center by projecting vector AC onto vector AB. Calculate the distance between that point and circle center. If it is greater that R, there is no intersection. If the distance is equal to R, line is a tangent of the circle and the point nearest to circle center is actually the intersection point. If distance less that R, then there are 2 intersection points. They lie at the same distance from the point nearest to circle center. That distance can easily be calculated using Pythagorean theorem. Here's algorithm in pseudocode:
{
dX = bX - aX;
dY = bY - aY;
if ((dX == 0) && (dY == 0))
{
// A and B are the same points, no way to calculate intersection
return;
}
dl = (dX * dX + dY * dY);
t = ((cX - aX) * dX + (cY - aY) * dY) / dl;
// point on a line nearest to circle center
nearestX = aX + t * dX;
nearestY = aY + t * dY;
dist = point_dist(nearestX, nearestY, cX, cY);
if (dist == R)
{
// line segment touches circle; one intersection point
iX = nearestX;
iY = nearestY;
if (t < 0 || t > 1)
{
// intersection point is not actually within line segment
}
}
else if (dist < R)
{
// two possible intersection points
dt = sqrt(R * R - dist * dist) / sqrt(dl);
// intersection point nearest to A
t1 = t - dt;
i1X = aX + t1 * dX;
i1Y = aY + t1 * dY;
if (t1 < 0 || t1 > 1)
{
// intersection point is not actually within line segment
}
// intersection point farthest from A
t2 = t + dt;
i2X = aX + t2 * dX;
i2Y = aY + t2 * dY;
if (t2 < 0 || t2 > 1)
{
// intersection point is not actually within line segment
}
}
else
{
// no intersection
}
}
EDIT: added code to check whether found intersection points actually are within line segment.
You'll need some math here:
Suppose A = (Xa, Ya), B = (Xb, Yb) and C = (Xc, Yc). Any point on the line from A to B has coordinates (alpha*Xa + (1-alpha)
If the point P has distance R to C, it must be on the circle. What you want is to solve
distance(P, C) = R
that is
(alpha*Xa + (1-alpha)*Xb)^2 + (alpha*Ya + (1-alpha)*Yb)^2 = R^2
alpha^2*Xa^2 + alpha^2*Xb^2 - 2*alpha*Xb^2 + Xb^2 + alpha^2*Ya^2 + alpha^2*Yb^2 - 2*alpha*Yb^2 + Yb^2=R^2
(Xa^2 + Xb^2 + Ya^2 + Yb^2)*alpha^2 - 2*(Xb^2 + Yb^2)*alpha + (Xb^2 + Yb^2 - R^2) = 0
if you apply the ABC-formula to this equation to solve it for alpha, and compute the coordinates of P using the solution(s) for alpha, you get the intersection points, if any exist.
If you find the distance between the center of the sphere (since it's 3D I assume you mean sphere and not circle) and the line, then check if that distance is less than the radius that will do the trick.
The collision point is obviously the closest point between the line and the sphere (which will be calculated when you're calculating the distance between the sphere and the line)
Distance between a point and a line:
If the line's coordinates are A.x, A.y and B.x, B.y and the circles center is C.x, C.y then the lines formulae are:
x = A.x * t + B.x * (1 - t)
y = A.y * t + B.y * (1 - t)
where 0<=t<=1
and the circle is
(C.x - x)^2 + (C.y - y)^2 = R^2
if you substitute x and y formulae of the line into the circles formula you get a second order equation of t and its solutions are the intersection points (if there are any). If you get a t which is smaller than 0 or greater than 1 then its not a solution but it shows that the line is 'pointing' to the direction of the circle.
This solution I found seemed a little easier to follow then some of the other ones.
Taking:
p1 and p2 as the points for the line, and
c as the center point for the circle and r for the radius
I would solve for the equation of the line in slope-intercept form. However, I didn't want to have to deal with difficult equations with
p3 = p1 - c
p4 = p2 - c
By the way, whenever I subtract points from each other I am subtracting the
Anyway, I now solve for the equation of the line with
m = (p4_y - p3_y) / (p4_x - p3) (the underscore is an attempt at subscript)
y = mx + b
y - mx = b (just put in a point for x and y, and insert the m we found)
Ok. Now I need to set these equations equal. First I need to solve the circle's equation for
x^2 + y^2 = r^2
y^2 = r^2 - x^2
y = sqrt(r^2 - x^2)
Then I set them equal:
mx + b = sqrt(r^2 - x^2)
And solve for the quadratic equation (
(mx + b)^2 = r^2 - x^2
(mx)^2 + 2mbx + b^2 = r^2 - x^2
0 = m^2 * x^2 + x^2 + 2mbx + b^2 - r^2
0 = (m^2 + 1) * x^2 + 2mbx + b^2 - r^2
Now I have my
a = m^2 + 1
b = 2mb
c = b^2 - r^2
So I put this into the quadratic formula:
(-b ± sqrt(b^2 - 4ac)) / 2a
And substitute in by values then simplify as much as possible:
(-2mb ± sqrt(b^2 - 4ac)) / 2a
(-2mb ± sqrt((-2mb)^2 - 4(m^2 + 1)(b^2 - r^2))) / 2(m^2 + 1)
(-2mb ± sqrt(4m^2 * b^2 - 4(m^2 * b^2 - m^2 * r^2 + b^2 - r^2))) / 2m^2 + 2
(-2mb ± sqrt(4 * (m^2 * b^2 - (m^2 * b^2 - m^2 * r^2 + b^2 - r^2))))/ 2m^2 + 2
(-2mb ± sqrt(4 * (m^2 * b^2 - m^2 * b^2 + m^2 * r^2 - b^2 + r^2)))/ 2m^2 + 2
(-2mb ± sqrt(4 * (m^2 * r^2 - b^2 + r^2)))/ 2m^2 + 2
(-2mb ± sqrt(4) * sqrt(m^2 * r^2 - b^2 + r^2))/ 2m^2 + 2
(-2mb ± 2 * sqrt(m^2 * r^2 - b^2 + r^2))/ 2m^2 + 2
(-2mb ± 2 * sqrt(m^2 * r^2 + r^2 - b^2))/ 2m^2 + 2
(-2mb ± 2 * sqrt(r^2 * (m^2 + 1) - b^2))/ 2m^2 + 2
This is almost as far as it will simplify. Finally, separate out to equations with the ±:
(-2mb + 2 * sqrt(r^2 * (m^2 + 1) - b^2))/ 2m^2 + 2 or
(-2mb - 2 * sqrt(r^2 * (m^2 + 1) - b^2))/ 2m^2 + 2
Then simply plug the result of both of those equations into the
function interceptOnCircle(p1,p2,c,r){
//p1 is the first line point
//p2 is the second line point
//c is the circle's center
//r is the circle's radius
var p3 = {x:p1.x - c.x, y:p1.y - c.y} //shifted line points
var p4 = {x:p2.x - c.x, y:p2.y - c.y}
var m = (p4.y - p3.y) / (p4.x - p3.x); //slope of the line
var b = p3.y - m * p3.x; //y-intercept of line
var underRadical = Math.pow((Math.pow(r,2)*(Math.pow(m,2)+1)),2)-Math.pow(b,2)); //the value under the square root sign
if (underRadical < 0){
//line completely missed
return false;
} else {
var t1 = (-2*m*b+2*Math.sqrt(underRadical))/(2 * Math.pow(m,2) + 2); //one of the intercept x's
var t2 = (-2*m*b-2*Math.sqrt(underRadical))/(2 * Math.pow(m,2) + 2); //other intercept's x
var i1 = {x:t1,y:m*t1+b} //intercept point 1
var i2 = {x:t2,y:m*t2+b} //intercept point 2
return [i1,i2];
}
}
I hope this helps!
P.S. If anyone finds any errors or has any suggestions, please comment. I am very new and welcome all help/suggestions.
This Java Function returns a DVec2 Object. It takes a DVec2 for the center of the circle, the radius of the circle, and a Line.
public static DVec2 CircLine(DVec2 C, double r, Line line)
{
DVec2 A = line.p1;
DVec2 B = line.p2;
DVec2 P;
DVec2 AC = new DVec2( C );
AC.sub(A);
DVec2 AB = new DVec2( B );
AB.sub(A);
double ab2 = AB.dot(AB);
double acab = AC.dot(AB);
double t = acab / ab2;
if (t < 0.0)
t = 0.0;
else if (t > 1.0)
t = 1.0;
//P = A + t * AB;
P = new DVec2( AB );
P.mul( t );
P.add( A );
DVec2 H = new DVec2( P );
H.sub( C );
double h2 = H.dot(H);
double r2 = r * r;
if(h2 > r2)
return null;
else
return P;
}
Just an addition to this thread... Below is a version of the code posted by pahlevan, but for C#/XNA and tidied up a little:
/// <summary>
/// Intersects a line and a circle.
/// </summary>
/// <param name="location">the location of the circle</param>
/// <param name="radius">the radius of the circle</param>
/// <param name="lineFrom">the starting point of the line</param>
/// <param name="lineTo">the ending point of the line</param>
/// <returns>true if the line and circle intersect each other</returns>
public static bool IntersectLineCircle(Vector2 location, float radius, Vector2 lineFrom, Vector2 lineTo)
{
float ab2, acab, h2;
Vector2 ac = location - lineFrom;
Vector2 ab = lineTo - lineFrom;
Vector2.Dot(ref ab, ref ab, out ab2);
Vector2.Dot(ref ac, ref ab, out acab);
float t = acab / ab2;
if (t < 0)
t = 0;
else if (t > 1)
t = 1;
Vector2 h = ((ab * t) + lineFrom) - location;
Vector2.Dot(ref h, ref h, out h2);
return (h2 <= (radius * radius));
}
' VB.NET - Code
Function CheckLineSegmentCircleIntersection(x1 As Double, y1 As Double, x2 As Double, y2 As Double, xc As Double, yc As Double, r As Double) As Boolean
Static xd As Double = 0.0F
Static yd As Double = 0.0F
Static t As Double = 0.0F
Static d As Double = 0.0F
Static dx_2_1 As Double = 0.0F
Static dy_2_1 As Double = 0.0F
dx_2_1 = x2 - x1
dy_2_1 = y2 - y1
t = ((yc - y1) * dy_2_1 + (xc - x1) * dx_2_1) / (dy_2_1 * dy_2_1 + dx_2_1 * dx_2_1)
If 0 <= t And t <= 1 Then
xd = x1 + t * dx_2_1
yd = y1 + t * dy_2_1
d = Math.Sqrt((xd - xc) * (xd - xc) + (yd - yc) * (yd - yc))
Return d <= r
Else
d = Math.Sqrt((xc - x1) * (xc - x1) + (yc - y1) * (yc - y1))
If d <= r Then
Return True
Else
d = Math.Sqrt((xc - x2) * (xc - x2) + (yc - y2) * (yc - y2))
If d <= r Then
Return True
Else
Return False
End If
End If
End If
End Function
|
I'm trying to become more proficient in Python and have decided to run through the Project Euler problems.
In any case, the problem that I'm on (17) wants me to count all the letters in the English words for each natural number up to 1,000. In other words, one + two would have 6 letters, and so on continuing that for all numbers to 1,000.
I wrote this code, which produces the correct answer (21,124). However, I'm wondering if there's a more pythonic way to do this.
I have a function (num2eng) which translates the given integer into English words but does not include the word "and".
for i in range (1, COUNTTO + 1):
container = num2eng(i)
container = container.replace(' ', '')
print container
if i > 100:
if not i % 100 == 0:
length = length + container.__len__() + 3 # account for 'and' in numbers over 100
else:
length = length + container.__len__()
else:
length = length + container.__len__()
print length
There is some repetition in my code and some nesting, both of which seem un-pythonic.
I'm specifically looking for ways to make the script shorter and with simpler loops; I think that's my biggest weakness in general. |
A while back, I detailed how I went about deploying TurboGears apps with workingenv and supervisord. That's still the basic approach that I'm using for the TG apps that I still maintain and keep running. Lately though, I've been doing more of my work with Django and the landscape of Python deployment tools has changed significantly enough that I thought it was about time I explained how (and why) I'm deploying things these days.
I still have the same basic needs. I write a lot of small applications that get deployed on one server and I don't want to spend all my time doing the upgrade dance when a new version of a library comes out. If I've got a bunch of apps written with Django 0.97 that are running and I want to deploy another app on the same server that's written against Django 1.0, I don't want to have to upgrade all my old ones (since there were some non backwards compatible changes introduced). Similarly, I don't want the presence of my old legacy apps preventing me from being able to use the latest versions of libraries for my new apps. Generally, this means that the approach of installing libraries into the global site-packages just does not work for me.
I should also mention that while the approach detailed in my old post uses workingenv's "--requirements" flag to give it a list of URLs of packages to install, I actually moved away from that quite a while ago instead opting to bundle all the needed eggs in a directory right alongside the application's code so the entire deployment process could be done without relying on the network. I just had too many problems with either PyPI or the TG website being unavailable at the wrong time and breaking my deployments. It also meant that I couldn't bootstrap a new environment if I was on a laptop without network access.
My old post explained in some depth how I got around that problem for the TurboGears apps I was deploying by using workingenv to isolate each application's libraries in a way that I could just bundle the libraries needed for each along with the application and not have to worry about what else was on the system.
Things are slightly different now with Django for a couple reasons.
First, mod_wsgi has matured and, for my purposes, seems to be the best way to deploy Django applications. That means I'm back to Apache and don't need the whole setup with lighttpd proxying back to individual application web server processes each being monitored and controlled by supervisord.
Second, the Django community as a whole seems to have not bought into setuptools and eggs as the preferred distribution method and have stuck with distutils instead. My old approach relied on having all the required libraries bundled as eggs. With TurboGears, that was rarely an issue since TG was completely tied to setuptools. But with Django, I find that more often than not, the library I want to use isn't available as an egg, so I ended up having to download the source tarball and manually build an egg for each library. That got tedious after a while. Ideally, a new approach would allow me bundle both eggs and source tarballs. Failing that, source tarballs currently seem to be the path of least resistance in a Django ecosystem.
Finally, workingenv has been all but deprecated in favor of virtualenv (and/or the combination of virtualenv and pip depending on what set of workingenv features one is replacing). Virtualenv has a number of advantages over workingenv that I won't bother enumerating here. Pip is also an important new player in town. Conveniently, pip happens to use source tarballs instead of eggs.
I'm just going to dive into it.
In each project, I have a 'requirements' directory. That, in turn, has a 'src' directory in which I've dumped source tarballs for every library that the project requires. That includes Django itself, database drivers, everything.
Also in 'requirements' are 'libs.txt' and 'apps.txt' text files. Those are just lists of the contents of the 'src' directory since pip currently isn't (yet) smart enough to figure out the order that it needs to install things when you just give it a directory full of tarballs. I separate them into 'libs' and 'apps' just for convenience. 'libs' are plain python libraries and 'apps' are full-fledged django apps.
At the top level of the project, there is a 'bootstrap.py' file with the following contents:
#!/usr/bin/env python
import os
import sys
import subprocess
import shutil
pwd = os.path.dirname(__file__)
vedir = os.path.join(pwd,"ve")
if os.path.exists(vedir):
shutil.rmtree(vedir)
subprocess.call([os.path.join(pwd,"pip.py"),"install",
"-E",os.path.join(pwd,"ve"),
"--enable-site-packages",
"--requirement",os.path.join(pwd,"requirements/apps.txt")])
That just looks for a directory named 've', blows it away if it's there, then runs a command that basically works out to
$ pip.py install -E ve --enable-site-packages --requirement requirements/apps.txt
In other words, telling pip to install all the packages specified in requirements/apps.txt (which in turn has a reference to libs.txt) into a new virtualenv directory called 've'. The only real reason that's done in Python is to easily make it self-aware of it's location so the script can be run from any directory and it will figure out how to put the 've' directory in the right place. Bash makes that harder than it ought to be.
I also include a copy of pip.py in the top level project directory so pip doesn't even have to be globally installed on a system to bootstrap. (I think I can also drop virtualenv.py in there too but I already have that installed on every system I admin so I haven't bothered yet).
I actually have all of this set up in a Paster template (along with a whole bunch of other customizations) so instead of the usual
$ django-admin.py startproject foo
I run
$ paster create --template=mydjangotemplate foo
and I get a stock Django project directory plus the requirements directory full of source tarballs and the bootstrap.py. The copy of 'manage.py' that my paster template drops in there has the '#!/usr/bin/env python' line replaced with '#!ve/bin/python'. So the next couple steps for me to bring up a running dev server look like:
$ cd foo
$ chmod +x bootstrap.py manage.py # paster templates don't let you set permissions
$ ./bootstrap.py # installs all my requirements into 've'
$ createdb foo # i pretty much always use postgresql and my custom settings.py are configured for it
$ ./manage.py runserver
I'd like to stress that that happens on a system that has Paste and virtualenv installed but does not need to have Django, psycopg2, or any of the other libraries that are used installed. They are included in the template and get installed into the virtualenv for that one project.
I check everything except the 've' directory into version control (usually git these days). That includes all the source tarballs. It's a bit wasteful of disk space and bandwidth but I haven't found that it's that much overhead in practice.
When I deploy to production (via our automated system at work), the project is checked out of version control, rsync'ed to the production server then
$ ssh productionserver /path/to/myapp/bootstrap.py
is run and everything gets installed into a virtualenv on the production server. Other applications on the same server are unaffected. My mod_wsgi configs point to '/path/to/myapp/ve/lib/python2.5/site-packages' and so on (they are autogenerated by my paste template as well).
I plan on going into more detail on the paste template magic I use in the future, but that should give you a bit of a sense for why I like it so much.
A few caveats: |
bipede
Re : Besoin de testeurs pour Pap'rass
Merci bipede
Il n'y a pas de quoi
Ca fonctionne pour ton scanner ?
Hors ligne
jeremix
Re : Besoin de testeurs pour Pap'rass
Oui, ça fonctionne, mais je retape la valeur voulu à chaque fois (au cas où ça provoquerais un problème), car cela m'affiche 2 résolutions différentes.
ubuntucounter user 8236
Hors ligne
bipede
Re : Besoin de testeurs pour Pap'rass
Oui, ça fonctionne, mais je retape la valeur voulu à chaque fois (au cas où ça provoquerais un problème), car cela m'affiche 2 résolutions différentes.
http://img209.imageshack.us/img209/8752 … trezp3.png
J'ai vu le problème, c'est juste un petit bug d'affichage que j'ai rectifié...
La version 2.02 est disponible sous forme de .deb à cet endroit. Je recompilerai pour win32 dès que possible...
Hors ligne
thierrybo
Re : Besoin de testeurs pour Pap'rass
Arg, gros bug chez moi ! Après la v1 .1, j'avais installé paprass 2.01 puis de 2.02 sans scanner de nouveau document. Aujourd'hui je veux scanner, rien ne se passe après avoir cliqué sur commencer.
La fenêtre de sélection du scanner n'apparaît plus. J'ai toujours la version 1.1 installée en parallèle qui tourne sans problème.
Thierry
Hors ligne
bipede
Re : Besoin de testeurs pour Pap'rass
Arg, gros bug chez moi ! Après la v1 .1, j'avais installé paprass 2.01 puis de 2.02 sans scanner de nouveau document. Aujourd'hui je veux scanner, rien ne se passe après avoir cliqué sur commencer.
La fenêtre de sélection du scanner n'apparaît plus. J'ai toujours la version 1.1 installée en parallèle qui tourne sans problème.
Thierry
Lance paprass depuis un terminal et dis-moi ce qu'il te raconte...
Hors ligne
thierrybo
Re : Besoin de testeurs pour Pap'rass
Jusqu'au moment où je clique "Numériser", rien (en 1.1 j'ai la fenêtre de sélection du scanner qui s'affiche). Si je clique sur "Commencer " :
Traceback (most recent call last):
File "/usr/share/paprass/paprass", line 3279, in Commencer
dlg = InitScanner(u"Choix du scanner", listeScanner)
File "/usr/share/paprass/paprass", line 2899, in __init__
self.listechoix = wx.Choice(self, -1, choice=choix)
File "/usr/lib/python2.5/site-packages/wx-2.8-gtk2-unicode/wx/_controls.py", line 493, in __init__
_controls_.Choice_swiginit(self,_controls_.new_Choice(*args, **kwargs))
TypeError: 'choice' is an invalid keyword argument for this function
Hors ligne
bipede
Re : Besoin de testeurs pour Pap'rass
Jusqu'au moment où je clique "Numériser", rien (en 1.1 j'ai la fenêtre de sélection du scanner qui s'affiche). Si je clique sur "Commencer " :
Traceback (most recent call last):
File "/usr/share/paprass/paprass", line 3279, in Commencer
dlg = InitScanner(u"Choix du scanner", listeScanner)
File "/usr/share/paprass/paprass", line 2899, in __init__
self.listechoix = wx.Choice(self, -1, choice=choix)
File "/usr/lib/python2.5/site-packages/wx-2.8-gtk2-unicode/wx/_controls.py", line 493, in __init__
_controls_.Choice_swiginit(self,_controls_.new_Choice(*args, **kwargs))
TypeError: 'choice' is an invalid keyword argument for this function
Voila l'intérêt de tester...
Tu as certainement plusieurs matériels reconnus par sane, et comme chez moi je n'en possède qu'un seul, je n'avais pas repéré le bug...
C'est réparé, et la version 2.03 est disponible sous forme de deb à cet endroit.
Tiens moi au courant...
Dernière modification par bipede (Le 10/06/2008, à 18:08)
Hors ligne
thierrybo
Re : Besoin de testeurs pour Pap'rass
Maintenant la fenêtre de sélection du scanner n'apparait toujours pas, et en cliquant sur "Commencer" :
Traceback (most recent call last):
File "/usr/share/paprass/paprass", line 3279, in Commencer
dlg = InitScanner(u"Choix du scanner", listeScanner)
File "/usr/share/paprass/paprass", line 2900, in __init__
if SCANVAR.GetDevice() != "INDEFINI":
AttributeError: ScanVar instance has no attribute 'GetDevice'
Hors ligne
bipede
Re : Besoin de testeurs pour Pap'rass
Maintenant la fenêtre de sélection du scanner n'apparait toujours pas, et en cliquant sur "Commencer" :
Traceback (most recent call last):
File "/usr/share/paprass/paprass", line 3279, in Commencer
dlg = InitScanner(u"Choix du scanner", listeScanner)
File "/usr/share/paprass/paprass", line 2900, in __init__
if SCANVAR.GetDevice() != "INDEFINI":
AttributeError: ScanVar instance has no attribute 'GetDevice'
Hou la la!
Deux bugs dans la même procédure...
J'ai fait fort là...
C'est réparé avec la version 2.04
Avec toutes mes excuses...
Hors ligne
thierrybo
Re : Besoin de testeurs pour Pap'rass
Cà avance ! Maintenant la fenêtre de sélection apparaît en cliquant sur Commencer, mais dès que je valide le scanner :
Traceback (most recent call last):
File "/usr/share/paprass/paprass", line 3283, in Commencer
if val == gtk.RESPONSE_OK and len(resu) > 0:
NameError: global name 'gtk' is not defined
Hors ligne
bipede
Re : Besoin de testeurs pour Pap'rass
Cà avance ! Maintenant la fenêtre de sélection apparaît en cliquant sur Commencer, mais dès que je valide le scanner :
Traceback (most recent call last):
File "/usr/share/paprass/paprass", line 3283, in Commencer
if val == gtk.RESPONSE_OK and len(resu) > 0:
NameError: global name 'gtk' is not defined
Faut se rendre à l'évidence... Je suis nul...
Je n'ose plus dire que c'est réparé, mais la version 2.05 tente de le faire....
Hors ligne
netmaxim
Re : Besoin de testeurs pour Pap'rass
Salut bipede,
Je suis tombé sur ton blog puis sur ce thread, c'est très intéressant !
Et je te tire mon chapeau, quelle "sympacité" ! On voit le boulot de passioné !
Petite question :
Est-ce que les pdf générés sont indéxés par leur contenu (ocr) ?
Est-ce que tu as prévu de le faire ?
Si c'est déjà le cas, désolé, je pose la question avant de tester ;-)
Je m'en vais de ce pas tester.
Petite suggestion : pour pouvoir faire "sudo aptitude install paprass", ce qui serait vraiment pratique
(surtout pour les update)
http://www.debianaddict.org/article31.html
Hors ligne
thierrybo
Re : Besoin de testeurs pour Pap'rass
OK, merci çà marche, super.
Maintenant je reviens sur l'ergonomie . Tu n'as pas remis des choses que tu avais ajouté ajoutées dans la 1.1 à ma demande notamment :
- Quand on clique sur Numériser, comme on veut forcément utiliser le scanner, dans la V1.1 la procédure commence automatiquement avec la demande de sélection éventuelle du scanner, sans avoir à cliquer sur Commencer.
- Dans la fonction Classer, le classement n'est plus dans l'ordre alpha de la 1.1
- Il ne l'est pas non plus dans Configurer / Définir le plan de Classement (mais il ne l'était pas non plus en 1.1)
Dernière modification par thierrybo (Le 14/06/2008, à 11:06)
Hors ligne
Thibaud
Re : Besoin de testeurs pour Pap'rass
Bonjour !
Merci et bravo pour ce travail et ce logiciel qui a l'air très intéressant.
Cependant, je me demande quel est son apport quand on dispose d'un moteur de recherche comme tracker ou beagle ? Ne peut-on pas simplement nommer les documents et choisir les dossiers dans lesquels on les classe ?
Merci pour les explications,
Thibaud.
Hors ligne
bipede
Re : Besoin de testeurs pour Pap'rass
Bonjour !
Merci et bravo pour ce travail et ce logiciel qui a l'air très intéressant.
Cependant, je me demande quel est son apport quand on dispose d'un moteur de recherche comme tracker ou beagle ? Ne peut-on pas simplement nommer les documents et choisir les dossiers dans lesquels on les classe ?
Merci pour les explications,
Thibaud.
Je pense que ce n'est pas la même chose...
Bien sûr, il est toujours possible de créer une arborescence sur son disque, et de donner des noms significatifs à ses fichiers, mais ça ne remplacera jamais un logiciel spécifique qui gère un plan de classement, ne serait-ce que par la souplesse et la simplicité des mises à jours du plan.
Tracker ou Beagle sont d'excellents logiciels d'indexation du contenu des disques, mais sont faits pour de la recherche rapide de fichiers. Ce ne sont pas des gestionnaires de contenu...
Ceci dit, si tes besoins sont parfaitement satisfaits par Tracker ou Beagle, Pap'rass te sera inutile... C'est ça l'avantage du libre... On peut choisir les outils qui correspondent à nos besoins, et on est parfaitement libre de ses choix...
Hors ligne
g_barthe
Re : Besoin de testeurs pour Pap'rass
Salut Bipède,
Je test depuis 1 semaine et ca me parait fantastique.
Par contre je me place en novice ubuntu (pas mon cas).
Dans le paramétrage pour choisir le visualiseur de fichier pdf, suivant la distrib, il est différent. Moi par exemple étant sous KDE, j'ai du mettre kpdf.
Alors serait t'il envisageable de manière simple (faut pas que tu ais 4j de développement intensif derrière non plus) de proposer les logiciels de visu de pdf installé sur la machine le tout dans une liste déroulante.
Cela histoire de simplifier le paramétrage pour les nouveaux venus sur Ubuntu qui n'ont pas forcément l'habitude des commandes pour lancer un soft.
Sinon beau boulot.
@+
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
g_barthe
Re : Besoin de testeurs pour Pap'rass
Je vais rajouter encore un truc mais je cherchais à envoyer par mail un doc que j'ai classé.
Et là... bah apparement c'est pas faisable.
Est-ce que ce genre de fonction serait faisable assez facilement et si ca interesse du monde évidement.
Encore merci.
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
g_barthe
Re : Besoin de testeurs pour Pap'rass
Bonjour,
Le projet est-il toujours en activité ???
Merci.
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
bipede
Re : Besoin de testeurs pour Pap'rass
Bonjour,
Le projet est-il toujours en activité ???
Merci.
Je viens de revenir de vacances
Je suis en train de créer un site plus rationnel et plus pratique pour mes développements en python, avec un suivi des versions plus efficace.
Je retiens tes suggestions, et je te demanderai des précisions complémentaires quand je serai prêt à y retravailler...
Hors ligne
g_barthe
Re : Besoin de testeurs pour Pap'rass
pas de soucis désolé je savais pas que tu étais en vacances.
Si tu cherches un truc pour héberger ton projet tu peux aller sur codingteam (gratuit et complet).
Hésite pas à poser des questions sur ce que je t'ai demandé.
@+
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
clapas34
Re : Besoin de testeurs pour Pap'rass
Bonjour, une question toute bête sur paprass que je teste en ce moment.
Le scan fonctionne bien, j'ajoute des documents et je crée le plan de classement .. oui mais voilà ...
Je ne vois pas comment classer un document. Après avoir fait click droit et avoir choisi une rubrique, je valide et il ne se passe rien. Après contrôle le document n'est pas classé.
Paprass V2.05 et ubuntu 8.04
Hors ligne
bipede
Re : Besoin de testeurs pour Pap'rass
@clapas34
Bonjour,
Ton plan de classement est bien composé de Classeurs-dossiers-chemises ?
En effet, tu ne peux classer les documents que dans des chemises, et si tu t'es arrêté au niveau classeur ou dossier dans ton plan, ça ne peut pas fonctionner...
Sinon, tu peux lancer pap'rass depuis un terminal, et si tu as des messages qui s'y affichent au moment du classement, peux-tu me les communiquer ?
Hors ligne
clapas34
Re : Besoin de testeurs pour Pap'rass
Bingo ... en plein dans le mille !
Merci Bipède, ce n'était que cela. Je n'avait pas vu qu'il faut pousser l'arborescence jusqu'en bas, les fameuses chemises.
Hors ligne
shrek_master
Re : Besoin de testeurs pour Pap'rass
Bonjour
Voici mes quelques remarques :
Petite question, sauf erreur, je voudrai savoir s'il n'est pas possible de bouger l'ordre de présentation des documents de manière personnaliser. Du genre j'ai scanné mes bulletins de paie dans le désordre et j'aimerai les reclasser dans l'ordre mensuel, voir décroissant manuellement.
Peux-t-on faire cela aussi pour le système de classement.
Est-il possible d'intégrer une sauvegarde de la base de documents sur un disque dur externe, une clé usb. Cela est la partie simple.
Sinon j'avais plutôt pensé à une gravure DVD ou passage possible en fichier ISO.
MERCI
François
Excellent logiciel et j'ai été très surpris de l'intégration dans ubuntu en fichier .deb.
anonym_user
Re : Besoin de testeurs pour Pap'rass
Salut,
Excellente idée ce soft !
J'ai juste un petit problème : les doc ne se classe pas dans les chemises que je crée. Après chaque tentative de classement la recherche sur le classeur m'indique qu'il est vide. La recherche par mot clé retrouve le doc mais le document reste considéré comme non classé.
Y a t-il quelque chose à configurer qui m'a échappé ?
Je suis nouveau sur Ubuntu (Hardy) mais je deviens de plus en plus accroc. Encore quelques config et j'aurai presque tout ce dont j'ai besoin... |
I trying to build a tree with BioPython, Phylo module.
What I've done so far is this image:
each name has a four digit number followed by - and a number: this number refer to the number of times that sequence is represented. That means 1578 - 22, that node should represent 22sequences.
So now I known how to change each size of the node. Each node has a different size, this is easy doing an array of the different values:
fh = open(MEDIA_ROOT + "groupsnp.txt")
list_size = {}
for line in fh:
if '>' in line:
labels = line.split('>')
label = labels[-1]
label = label.split()
num = line.split('-')
size = num[-1]
size = size.split()
for lab in label:
for number in size:
list_size[lab] = int(number)
a = array(list_size.values())
But the array is arbitrary, I would like to put the correct node size into the right node, I tried this:
for elem in list_size.keys():
if labels == elem:
Phylo.draw_graphviz(tree_xml, prog="neato", node_size=a)
but nothing appears when I use the if statement.
Anyway of doing this?
I would really appreciate!
Thanks everybody |
I’ve been working with python for a while to create some addons for Blender which allowing me to import and export various formats that aren’t supported by default. One of these file formats I’ve been working with compresses the vertices/uv/tangent/normal data to reduce the space used. This data is usually stored as 32bit floating point values but in this case it is reduced to 16bit floating point or Half Precision floating point. Halfing the final size of this data.
I had a hard time recreating this with python, I’d never used python before starting using Blender so my understanding was still fairly new and most examples online I failed to understand or struggled to implement.
Finally I cobbled together something that works from different examples online and got the results I wanted. Like most things on my site I felt the need to share this with anyone else who may be trying a similar thing.
Here is my class in python
class Float16Compressor:
def __init__(self):
self.temp = 0
def compress(self,float32):
F16_EXPONENT_BITS = 0x1F
F16_EXPONENT_SHIFT = 10
F16_EXPONENT_BIAS = 15
F16_MANTISSA_BITS = 0x3ff
F16_MANTISSA_SHIFT = (23 - F16_EXPONENT_SHIFT)
F16_MAX_EXPONENT = (F16_EXPONENT_BITS << F16_EXPONENT_SHIFT)
a = struct.pack('>f',float32)
b = binascii.hexlify(a)
f32 = int(b,16)
f16 = 0
sign = (f32 >> 16) & 0x8000
exponent = ((f32 >> 23) & 0xff) - 127
mantissa = f32 & 0x007fffff
if exponent == 128:
f16 = sign | F16_MAX_EXPONENT
if mantissa:
f16 |= (mantissa & F16_MANTISSA_BITS)
elif exponent > 15:
f16 = sign | F16_MAX_EXPONENT
elif exponent > -15:
exponent += F16_EXPONENT_BIAS
mantissa >>= F16_MANTISSA_SHIFT
f16 = sign | exponent << F16_EXPONENT_SHIFT | mantissa
else:
f16 = sign
return f16
def decompress(self,float16):
s = int((float16 >> 15) & 0x00000001) # sign
e = int((float16 >> 10) & 0x0000001f) # exponent
f = int(float16 & 0x000003ff) # fraction
if e == 0:
if f == 0:
return int(s << 31)
else:
while not (f & 0x00000400):
f = f << 1
e -= 1
e += 1
f &= ~0x00000400
#print(s,e,f)
elif e == 31:
if f == 0:
return int((s << 31) | 0x7f800000)
else:
return int((s << 31) | 0x7f800000 | (f << 13))
e = e + (127 -15)
f = f << 13
return int((s << 31) | (e << 23) | f)
and here is how to use it
#read half float from file and print float
h = struct.unpack(">H",file.read(struct.calcsize(">H")))[0]
fcomp = Float16Compressor()
temp = fcomp.decompress(h)
str = struct.pack('I',temp)
f = struct.unpack('f',str)[0]
print(f)
#write half float to file from float
fcomp = Float16Compressor()
f16 = fcomp.compress(float32)
file.write(struct.pack(">H",f16))
|
When I try importing urllib2 , i get the following error
import urllib2
File "/usr/lib/python2.7/urllib2.py", line 94, in <module>
import httplib
File "/usr/lib/python2.7/httplib.py", line 79, in <module>
import mimetools
File "/usr/lib/python2.7/mimetools.py", line 6, in <module>
import tempfile
File "/usr/lib/python2.7/tempfile.py", line 34, in <module>
from random import Random as _Random
ImportError: cannot import name Random
i know that there is no module called Random, but i did check urllib2.py and there was code which imported Random.
I am using Python 2.7 |
Javascript compiled regex
JavaScript performance comparison
Info
Add .compile() documentation!
Preparation code
<script>
Benchmark.prototype.setup = function() {
var normal = /\(\d+,\d+,\d+,\d+\)/;
var object = new RegExp('\\(\\d+,\\d+,\\d+,\\d+\\)');
var compiled1 = new RegExp('\\(\\d+,\\d+,\\d+,\\d+\\)');
compiled1.compile();
var compiled2 = new RegExp()
compiled2.compile('\\(\\d+,\\d+,\\d+,\\d+\\)');
var compiled3 = /\(\d+,\d+,\d+,\d+\)/;
compiled3.compile();
var globalNormal = /\(\d+,\d+,\d+,\d+\)/g;
var someText = "(1234,12451,32352,43456)\n(858,9564,454,76467)\n(17183,4482,3558,345)\n(343477,344,38955,669)\n(890434,347845,555,885769)\n(5664,334,767,34447)\n(45,4574,455647,44477)\n(1234,12451,32352,43456)\n(858,9564,454,76467)\n(17183,4482,3558,345)\n(343477,344,38955,669)\n(890434,347845,555,885769)\n(5664,334,767,34447)\n(45,4574,455647,44477)\n(1234,12451,32352,43456)\n(858,9564,454,76467)\n(17183,4482,3558,345)\n(343477,344,38955,669)\n(890434,347845,555,885769)\n(5664,334,767,34447)\n(45,4574,455647,44477)\n(1234,12451,32352,43456)\n(858,9564,454,76467)\n(17183,4482,3558,345)\n(343477,344,38955,669)\n(890434,347845,555,885769)\n(5664,334,767,34447)\n(45,4574,455647,44477)\n(1234,12451,32352,43456)\n(858,9564,454,76467)\n(17183,4482,3558,345)\n(343477,344,38955,669)\n(890434,347845,555,885769)\n(5664,334,767,34447)\n(45,4574,455647,44477)\n(1234,12451,32352,43456)\n(858,9564,454,76467)\n(17183,4482,3558,345)\n(343477,344,38955,669)\n(890434,347845,555,885769)\n(5664,334,767,34447)\n(45,4574,455647,44477)";
var someTextArray = someText.split('\n');
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
Test Ops/sec pending…
compiled1 RegExp
for (i in someTextArray) {
compiled1.exec(someTextArray[i]);
}
pending…
compiled2 RegExp
for (i in someTextArray) {
compiled2.exec(someTextArray[i]);
}
pending…
compiled3 RegExp literal
for (i in someTextArray) {
compiled3.exec(someTextArray[i]);
}
pending…
global normal RegExp
globalNormal.exec(''); // to reset the regex
while (match = globalNormal.exec(someText)) {
var a = match;
}
pending…
inline RegExp
for (i in someTextArray) {
/\(\d+,\d+,\d+,\d+\)/.exec(someTextArray[i]);
}
pending…
Compare results of other browsers
Revisions
You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:
Revision 1: published by Dan Andreescu
Revision 2: published by Matthew Flaschen
Revision 3: published by Matthew Flaschen
Revision 4: published
Revision 5: published by Matthew Flaschen
Revision 6: published
Revision 8: published by Klaus
Revision 9: published by Jack
Revision 10: published
Revision 11: published
Revision 12: published
Revision 13: published
Revision 14: published
Revision 15: published
Revision 16: published by Albert Rossinski |
Perl and some other current regex engines support Unicode properties, such as the category, in a regex. E.g. in Perl you can use \p{Ll} to match an arbitrary lower-case letter, or p{Zs} for any space separator. I don't see support for this in either the 2.x nor 3.x lines of Python (with due regrets). Is anybody aware of a good strategy to get a similar effect? Homegrown solutions are welcome.
Perl and some other current regex engines support Unicode properties, such as the category, in a regex. E.g. in Perl you can use
The regex module (an alternative to the standard
You're right that Unicode property classes are not supported by the Python regex parser.
If you wanted to do a nice hack, that would be generally useful, you could create a preprocessor that scans a string for such class tokens (
People would thank you. :)
You can painstakingly use unicodedata on each character:
import unicodedata
def strip_accents(x):
return u''.join(c for c in unicodedata.normalize('NFD', x) if unicodedata.category(c) != 'Mn')
Speaking of homegrown solutions, some time ago I wrote a small program to do just that - convert a unicode category written as
Example usage:
>>> from unicode_hack import regex
>>> pattern = regex(r'^\\p{Lu}(\\p{L}|\\p{N}|_)*')
>>> print pattern.match(u'ÃñÇ_1+2').group(0)
ÃñÇ_1
>>>
Note that while |
I have a simple model with sequence as a attribute as integer. When I am setting sequence as 1 it fail the simple test case ie:
context 'MathFactAttemptData' do
it 'should insert rows' do
math_fact_attempt_data = FactoryGirl.build :math_fact_attempt_data
@params[:request_params] = {
user_data: {
math_fact_attempt_data: [JSON.parse(math_fact_attempt_data.to_json)]
}
}
initial_math_fact_attempt_data_count = MathFactAttemptData.unscoped.count
post api_v3_user_data_path, @params
response.should be_success
response_body = JSON.parse response.body
response_body['user_data'].should be_nil
response_body['seed_data'].should be_nil
MathFactAttemptData.unscoped.count.should == initial_math_fact_attempt_data_count + 1
end
end
Factories:
factory :math_fact_attempt_data do association :user, factory: :student association :math_fact_attempt, factory: :math_fact_attempt association :problem_type, factory: :problem_type num1 1 num2 1 correct_answer 1 response 1 correct 1 #sequence 1 time_spent 1 choice_type "MyString" selected_operator "MyString"end
Uncommenting sequence fails the test case with issue ie:
API v3 POST /user_data.json Entities MathFactAttemptData should insert rows
Failure/Error: math_fact_attempt_data = FactoryGirl.build :math_fact_attempt_data
NoMethodError:
undefined method `to_sym' for 1:Fixnum
# ./spec/requests/api/v3/post_user_data_spec.rb:1116:in `block (5 levels) in <top (required)>'
Finished in 3.7 seconds
1 example, 1 failure
Failed examples:
rspec ./spec/requests/api/v3/post_user_data_spec.rb:1115 # API v3 POST /user_data.json Entities MathFactAttemptData should insert rows
|
Ok, so this is my code. I'm not sure it's in the best place, but it works.
Indentation may be wrong, and it's python so please be careful.
edit /var/www/iredmail/libs/mysql/core.py
Insert immediately after this section:
# Verify password
authenticated = False
if iredpwd.verify_md5_password(password_sql, password) \
or iredpwd.verify_plain_md5_password(password_sql, password) \
or password_sql in [password, '{PLAIN}' + password] \
or iredpwd.verify_ssha_password(password_sql, password) \
or iredpwd.verify_ssha512_password(password_sql, password):
authenticated = True
The following code:
if session.get('admin_is_mail_user'):
if record.get('isglobaladmin', 0) == 1:
if settings.GLOBAL_ADMIN_IP_RESTRICTION and str(session.ip) not in settings.GLOBAL_ADMIN_IP_LIST:
authenticated = False
else:
result = self.conn.select(
'domain_admins',
vars={'username': username, 'domain': 'ALL', },
what='domain',
where='username=$username AND domain=$domain',
limit=1,
)
if len(result) == 1:
if settings.GLOBAL_ADMIN_IP_RESTRICTION and str(session.ip) not in settings.GLOBAL_ADMIN_IP_LIST:
authenticated = False
Afterwards, this existing code below should follow:
if not authenticated:
return (False, 'INVALID_CREDENTIALS')
if verifyPassword is not True:
session['username'] = username
session['logged'] = True
Save.
Edit /var/www/iredadmin/settings.py
Add the following lines, adjusting IP list to suit:
GLOBAL_ADMIN_IP_RESTRICTION = True
GLOBAL_ADMIN_IP_LIST = ['10.0.0.1','10.0.0.2','192.168.1.5']
Save.
Restart httpd, e.g.:
/etc/init.d/httpd restart
That should restrict global admin logins to those IPs specified in settings.py
Please let me know if the code looks okay.
If anyone wishes to use, distribute or modify this code, it's okay with me, provided it is at your own risk and does not otherwise infringe. |
pgraber
Re : Qarte arte.tv browser (ex Qarte+7)
Bonjour,
Je suis sous 12.10 (beta) et j'ai aussi droit à l'erreur mentionnées plusieurs fois sur cette page.
INFO - qarte Main thread: <_MainThread(MainThread, started 139910826301184)>
INFO - ui_main setup main window
INFO - ui_main set page arte+
Erreur de segmentation (core dumped)
J'aimerais vraiment retrouver un qarte fonctionnel (sans être obligé de revenir à 12.04).
Une idée?
Pierre
Hors ligne
VinsS
Re : Qarte arte.tv browser (ex Qarte+7)
Salut Pierre,
Je n'ai pas de moyen de tester ça mais j'ai envie de soupçonner le package PyQt4.
Si tu voulais bien tester le code ci-dessous.
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
print 'setup main window'
self.centralwidget = QtGui.QWidget(MainWindow)
self.gridLayout_3 = QtGui.QGridLayout(self.centralwidget)
self.stackedWidget = QtGui.QStackedWidget(self.centralwidget)
self.page_1 = QtGui.QWidget()
self.hl = QtGui.QHBoxLayout(self.page_1)
print 'Set splitter'
self.splitter = QtGui.QSplitter(self.page_1)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.splitter.sizePolicy()
.hasHeightForWidth())
print 'Set size policy for splitter'
self.splitter.setSizePolicy(sizePolicy)
self.splitter.setOrientation(QtCore.Qt.Vertical)
self.splitter.setChildrenCollapsible(False)
print 'set preview'
self.preview = Preview(self, MainWindow, self.splitter)
self.layoutWidget = QtGui.QWidget(self.splitter)
self.hl_1 = QtGui.QHBoxLayout(self.layoutWidget)
self.hl_1.setSpacing(0)
self.hl_1.setMargin(0)
print 'Set editor'
self.editor = QtGui.QPlainTextEdit(self.layoutWidget)
self.editor.setHorizontalScrollBarPolicy(
QtCore.Qt.ScrollBarAlwaysOff)
self.hl_1.addWidget(self.editor)
print "Set button's widget"
self.bwdg = QtGui.QWidget(self.layoutWidget)
print 'Set widgets'
self.hl_1.addWidget(self.bwdg)
self.hl.addWidget(self.splitter)
class Preview(QtGui.QListWidget):
itemDragged = QtCore.pyqtSignal(int)
def __init__(self, ui, mw, parent=None):
super(Preview, self).__init__(parent)
print 'Setting preview'
self.ui = ui
self.mw = mw
print 'setting drag'
self.setDragEnabled(True)
self.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
self.setDefaultDropAction(QtCore.Qt.MoveAction)
print 'Setting selection'
self.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
print 'Setting icon size'
self.setIconSize(QtCore.QSize(160, 160))
print 'Setting view'
self.setFlow(QtGui.QListView.LeftToRight)
self.setViewMode(QtGui.QListView.IconMode)
print 'connecting signal'
self.itemSelectionChanged.connect(self.selection_changed)
def selection_changed(self):
pass
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Disons que tu l'appelles bugtest.py
python bugtest.py
Si ça crashe, c'est que j'ai sûrement raison, si ça crash pas c'est que j'ai peut-être tort.
Si ça crashe, je ne pourrai faire qu'un rapport de bug sur Launchpad.
Edit: Oups, il me revient quelque chose à l'esprit, Python 2 est bien toujours la version par défaut ?
Pour le savoir, juste entrer
python
en console, la version s'affichera.
Dernière modification par VinsS (Le 19/09/2012, à 22:08)
Hors ligne
pgraber
Re : Qarte arte.tv browser (ex Qarte+7)
Salut Vincent,
12.10 utilise Python 2.7.3 comme version par défaut.
Quant au test, voici ce que j'obtiens :
setup main window
Set splitter
Set size policy for splitter
set preview
(python:21256): Gtk-CRITICAL **: IA__gtk_widget_style_get: assertion `GTK_IS_WIDGET (widget)' failed
(python:21256): Gtk-CRITICAL **: IA__gtk_widget_style_get: assertion `GTK_IS_WIDGET (widget)' failed
Setting preview
setting drag
Setting selection
Setting icon size
Setting view
connecting signal
(python:21256): Gtk-CRITICAL **: IA__gtk_widget_style_get: assertion `GTK_IS_WIDGET (widget)' failed
(python:21256): Gtk-CRITICAL **: IA__gtk_widget_style_get: assertion `GTK_IS_WIDGET (widget)' failed
(python:21256): Gtk-CRITICAL **: IA__gtk_widget_style_get: assertion `GTK_IS_WIDGET (widget)' failed
(python:21256): Gtk-CRITICAL **: IA__gtk_widget_style_get: assertion `GTK_IS_WIDGET (widget)' failed
Set editor
(python:21256): Gtk-CRITICAL **: IA__gtk_widget_style_get: assertion `GTK_IS_WIDGET (widget)' failed
(python:21256): Gtk-CRITICAL **: IA__gtk_widget_style_get: assertion `GTK_IS_WIDGET (widget)' failed
Set button's widget
Set widgets
Le test ne se termine pas correctement.
Il ne sort pas du programme (curseur clignotant après la dernière ligne ci-dessus).
Merci de ton aide,
Pierre
P.-S. J'ai trouvé une explication là (commentaire #5).
Ça marche pour moi en mettant le thème Motif (dans Qt4).
Cela dit, j'espère que ce problème sera corrigé (dans Qt4, je suppose ?).
Dernière modification par pgraber (Le 19/09/2012, à 23:24)
Hors ligne
VinsS
Re : Qarte arte.tv browser (ex Qarte+7)
Le bug est effectivement déjà signalé:
Je suppose que l'on pourra espérer un patch d'ici la release finale de Quantal, en attendant, si un changement de thème résout le problème, il faudra faire avec.
Hors ligne
lemoineo
Re : Qarte arte.tv browser (ex Qarte+7)
Superbe interface
j'avais laissé tombé Arte+7 , Pluzz et autre outil du même genre,
fallait être spécialiste du bash et des installs
là, c'est parfait, c'est parti pour une soirée de téléchargement !!
Encore merci VinsS
Olivier
Dernière modification par lemoineo (Le 20/09/2012, à 21:06)
mon boulot : développeur PHP ?
mes galeries : http://lemoineo.free.fr
Utilisateur Linux dans mes loisirs
le Kitesurf me permet de décrocher du PC !
Hors ligne
ke20
Re : Qarte arte.tv browser (ex Qarte+7)
Salut VinsS,
tout d'abord, bravo pour ce super logiciel.
J'ai un petit problème lorsque j'essaie de télécharger les Tudors.
Il me dit "Ne peut trouver l'URL du stream. Reason: Unknown".
Pour info j'ai découvert qarte car je cherchait pourquoi je n'arrivait pas à regarder les Tudors sur arte+7.
Ils utilisent silverlight et même avec moonlight pas moyen de le fair"e fonctionner.
Une idée?
Merci d'avance
Kevin
[Edit]
Je viens de voir les messages à ce sujet en page 7. J'ai plus qu'à chercher pourquoi ca ne fonctionne pas dans Firefox.
Dernière modification par ke20 (Le 23/09/2012, à 10:04)
Hors ligne
galanga
Re : Qarte arte.tv browser (ex Qarte+7)
@VinsS : Youhoooooouuuu !!! C'est énôôôrmeuuuuhhhh (la version 1.4) !!!
Merci beaucoup, de nouveau
EDIT: juste quelques petits trucs de debuggage trouvés pour le moment :
- avec le téléchargement custom, le fichier résultant a un caractère retour-à-ligne et des espaces à la fin (juste avant l'extension)
- dans arte Live Web, il n'y a plus de menu contextuel sur les images (pour faire "Ajouter à la liste de téléchargement"), ce qui m'a surpris au début (comment kon féééé...) ; par contre j'ai fini par trouver que le bouton + marche bien pour ajouter à la liste
Dernière modification par galanga (Le 29/09/2012, à 07:30)
Hors ligne
fredericseverino
Re : Qarte arte.tv browser (ex Qarte+7)
Merci beaucoup pour ce superbe boulot. C'est très beau, ça fait vraiment pro. Félicitations VinsS.
Je testerai ce soir car sur le campus, l'unif bloque tout sauf le direct download et le smtp.
L'informatique, c'est pas difficile, il suffit de lire.
Hors ligne
tiantac
Re : Qarte arte.tv browser (ex Qarte+7)
Un grand merci pour cette application qui tombe à pic.
Très belle interface, facile d'utilisation.
Félicitation continuez
Hors ligne
k3c
Re : Qarte arte.tv browser (ex Qarte+7)
Bonjour
Les Tudors ayant maintenant des DRM, on ne peut les télécharger.
Au lieu de
raison unknown
on pourrait afficher un message plus explicite.
Bravo pour ce superbe logiciel.
Acer Aspire One 150 8,9 "
Norhtec avec une Clé Usb bootable http://www.norhtec.com/products/mcsr/index.html
Toshiba Satellite L750
Hors ligne
agatzebluz
Re : Qarte arte.tv browser (ex Qarte+7)
Salut VinsS,
tout d'abord, bravo pour ce super logiciel.
J'ai un petit problème lorsque j'essaie de télécharger les Tudors.
Il me dit "Ne peut trouver l'URL du stream. Reason: Unknown".
J'ai le même problème sous Linux Mint 13 de manière très récurrente (plus d'une fois sur 2).
De temps en temps ça bloque et d’autres ça passe.
En tous les cas, c'est un super programme que j'utilise avec bonheur et depuis fort longtemps, merci aux développeurs.
J'essaie de partager ce que je sais sur mon blog http://www.michtoblog.com
Configurations : Linux Mint 13 sur ma Box montée maison / Crunchbang Linux Eeepc 701
Hors ligne
yamo
Re : Qarte arte.tv browser (ex Qarte+7)
Bonsoir,
# apt-cache policy qarte
qarte:
Installed: 1.4.0-dmo1
Candidate: 1.4.0-dmo1
Version table:
*** 1.4.0-dmo1 0
750 http://www.deb-multimedia.org/ wheezy/main i386 Packages
600 http://www.deb-multimedia.org/ sid/main i386 Packages
100 /var/lib/dpkg/status
Hors ligne
claudiux
Re : Qarte arte.tv browser (ex Qarte+7)
Merci et bravo pour cet excellent Qarte !
Hors ligne
eochu
Re : Qarte arte.tv browser (ex Qarte+7)
Bonjour VinsS,
Merci pour cette appli qui semble très bien faite Quelques remarques/questions cependant :
- Le cœur de ton programme est en Python, avec une surcouche graphique. Malheureusement, on ne peut pas utiliser ce programme uniquement en ligne de commande. Qarte dépend de python-qt4 qui lui-même dépend de toute la couche graphique.
En quoi est-ce un problème ? Si je veux utiliser qarte sur un serveur sans X, je ne peux pas, quand bien même le cœur de qarte fonctionne uniquement avec du python en texte.
Tu me répondras peut-être que le public visé par ce programme utilise une interface graphique et que ce n'est donc finalement pas un problème. Néanmoins, et pour éviter de réinventer la roue à chaque fois, ne pourrais-tu pas « splitter » qarte en deux packages, par exemple qarte-common et qarte-qt dont le deuxième dépendrait du premier et de toutes les bibliothèques graphiques, alors que qarte-common pourrait être installé sur une machine sans interface graphique ? Je ne pense pas que la charge de travail soit grande, et ça collerait plus avec la philosophie unix où l'interface graphique est décorrélée du « moteur ».
- Depuis plusieurs mois, j'utilise le script de solsticedhiver (que je peux lancer en ligne de commande), hébergé ici : https://github.com/solsticedhiver/arteVIDEOS.
Travaillez-vous en collaboration lui et toi ? C'est dommage si chacun dans son coin développe la même chose, alors qu'en mutualisant on pourrait gagner du temps pour faire autre chose (corriger des bugs, séparer le graphique du texte , etc.)
En tous cas, merci encore de mettre à disposition ton travail, j'attends tes commentaires
Hors ligne
LRDP
Re : Qarte arte.tv browser (ex Qarte+7)
Bonjour,
Je débarque sur cette page et j'en profite pour féliciter ceux qui travaille pour élaborer et améliorer ce projet. J'essaye d'installer Qarte sur mon lucid lynx tournant sur AMD 64 et l'installation de rtpmdump me répète que je n'ai pas d'architecture i386, ce qui est normal, mais je vois que des colistiers sont en 64 bits et ont pu installer Qarte sans problème... J'ai du rater quelque chose mais je ne trouve pas. Pouvez-vous me conseiller?
Hors ligne
VinsS
Re : Qarte arte.tv browser (ex Qarte+7)
@ LRDP Je vois ici [1] un paquet 64 bits.
Si ça ne convient pas, tu peux forcer l'architecture [2]
[1] http://www.ubuntuupdates.org/package/lu … e/rtmpdump
[2] http://doc.ubuntu-fr.org/ubuntu_64bits "4.1 Utiliser des programmes 32 bits sur Ubuntu 64 bits"
Hors ligne
david96
Re : Qarte arte.tv browser (ex Qarte+7)
ia32 ?
Hors ligne
LRDP
Re : Qarte arte.tv browser (ex Qarte+7)
Bonjour,
Merci pour les liens. Mais si le rtmpdump s'installe, il me renvoit sur des dépendances non valables et si j'adapte les dépendances en installant libc6 et libc6-dev comme demandé, ces dépendances effacent des fichiers qui me semblent importants (nvidia-current, lsb-core, g+ ...) pour Lucid alors que cette dernière mouture de Qarte est plus adaptée au Pangolin. Peut-être faut-il que j'attende de rejoindre Precise? La dernière fois que j'ai bidouillé avec le dossier video et lsb-core, çà a été plutôt catastrophique...
Hors ligne
LRDP
Re : Qarte arte.tv browser (ex Qarte+7)
En plus, j'ai trouvé sur le lien n°2 le moyen de faire tourner un programme 32 bits sur du 64 comme Freebirth qui marchait sur le Mac de mon épouse dans sa boite virtuelle xubuntu, mais pas sur mon AMD64. Super !:cool:
Hors ligne
VinsS
Re : Qarte arte.tv browser (ex Qarte+7)
Bonjour,
... pour Lucid alors que cette dernière mouture de Qarte est plus adaptée au Pangolin. ...
Je développe sous Lucid ...
Le principal est que cela fonctionne.
D'autre part le fonctionnement du programme étant pour le principal, dépendant de la bande passante de chacun et du temps de réponse des sites que je ne remarque aucune différence de vitesse entre Lucid 32 bytes et Quantal 64 bytes.
Hors ligne
eochu
Re : Qarte arte.tv browser (ex Qarte+7)
Salut VinsS,
Aurais-tu le temps de répondre à mon post #192, à propos du développement de Qarte ?
Merci,
Eochu
Hors ligne
VinsS
Re : Qarte arte.tv browser (ex Qarte+7)
@ eochu
Sorry je ne l'avais pas lu comme une question.
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.
Hors ligne |
I've used them for synchronization.
def synchronized(lock):
""" Synchronization decorator """
def wrap(f):
def newFunction(*args, **kw):
lock.acquire()
try:
return f(*args, **kw)
finally:
lock.release()
return newFunction
return wrap
As pointed out in the comments, since Python 2.5 you can use a with statement in conjunction with a threading.Lock (or multiprocessing.Lock since version 2.6) object to simplify the decorator's implementation to just:
def synchronized(lock):
""" Synchronization decorator """
def wrap(f):
def newFunction(*args, **kw):
with lock:
return f(*args, **kw)
return newFunction
return wrap
Regardless, you then use it like this:
import threading
lock = threading.Lock()
@synchronized(lock)
def do_something():
# etc
@synchronzied(lock)
def do_something_else():
# etc
Basically it just puts lock.acquire() / lock.release() on either side of the function call. |
g_barthe
interface python et apprentissage boa constrictor
Bonjour,
Je voudrais commencer à developper qq applications (avec interfaces graphiques) en python (pour windows et linux). Je recherche donc un éditeur qui permettrait de realiser l'interface de maniere simple et non en code pur. J'ai bien trouvé "wxglade" mais la lib wx n'a pas l'air d'etre présente de base avec python sur tous les environnements. (je peux me tromper) mais sous windows apparement je ne l'ai pas.
Il y a la librairie tk qui a l'air d'être prise en compte de manière générale mais la les éditeurs que j'ai trouvé"vtcl" n'arrive pas a se decompresser sous windows et comme je suis amené a developper sous ubuntu et windows je voudrais etre sur une librairie qui soit intégrée facilement à mon environnement de prog.
Y a t'il un avantage d'une librairie par rapport a l'autre ?
merci à vous et j'espère que j'ai été clair.
Dernière modification par g_barthe (Le 02/05/2006, à 18:18)
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
PierreR
Re : interface python et apprentissage boa constrictor
Pour TKinter, il y a peut être COBRA, mais je ne l'ai jamais utilisé.
Sinon, tu dois pouvoir utiliser GTK avec glade. GTK est le toolkit graphique utilisé par Gnome et il existe sous ubuntu et windows (mais pas mac OS). Il est plus complexe -- dans le sens offre plus de fonctionnalités -- que TKinter mais tout dépend de ce que tu veux faire -- GTK n'est pas installé par défaut sous windows par exemple (mais python non plus donc bon).
Hors ligne
g_barthe
Re : interface python et apprentissage boa constrictor
bonjour
j'ai reussi a faire fonctionner qq scripts python sous ubuntu avec la lib wx. Mais j'ai installé vtcl depuis synaptic d'ubuntu en gros c'est glade pour me facilité la tâche de création de l'interface mais il exporte le code source uniquement en C et pas python. La vie d'un nouveau pythonien n'est pas facile tous les jours. Je crois que je vais rester à la création manuelle de l'interface et non pas graphique car je n'arrive pas a comprendre le fonctionnement de vtcl et je ne trouve pas de tuto sur le net.
Je cherche à faire une application un peu scientifique avec qq calculs pour mon boulot en génie climatique (calculs de clim, chauffage, ventilation). En gros ce sera des boutons de validation, zone de saisie...
Merci à vous
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
bipede
Re : interface python et apprentissage boa constrictor
Si tu veux tester un bon rad pour python et wxPython, essaies boa-constructor.
C'est le meilleur à l'heure actuelle. Et il est dans les dépôts...
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
Je peux que recommander d'écrire son code dans un éditeur. Les avantages sont si nombreux.
Pour un bon début : http://wiki.wxpython.org/
PierreR
Re : interface python et apprentissage boa constrictor
Oui, mais là on parlait de l'interface graphique et à écrire à la main c'est vraiment prise de tête quand le truc devient un peu gros.
Désolé de m'être trompé plus haut, je voulais effectivement parler de boa (et pas cobra). Sinon pour glade, il ne faut pas générer le code -- même en C c'est déconseillé et plus supporté depuis un moment -- mais utiliser libglade qui a je crois un wrapper python.
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
@PierreR
Oui, mais là on parlait de l'interface graphique et à écrire à la main c'est vraiment prise de tête quand le truc devient un peu gros.
---
Pas du tout, c'est justement l'inverse qui se produit. Quelle est ton expérience? Sur quoi te bases-tu ? Argumentes !
Etant intimement lié à wxPython, je peux te dire que cette question a été posée des dizaines et des dizaines de fois sur la liste des wxPython users (et revient régulièrement). C'est toujours la même réponse qui revient. La même que celle que j'ai donné.
PS: ...mais là on parlait de l'interface graphique... wxPython ne s'occupe que de l'interface graphique.
PierreR
Re : interface python et apprentissage boa constrictor
Heu, il y du y avoir un quiproquo, je voulais dire que quand on fait une interface graphique, à partir du moment ou le truc devient un peu gros (i.e. s'il y a plus d'un champ de texte et deux boutons) c'est très appréciable de disposer d'une interface graphique comme Glade.
Pour répondre à ta question, je dois avouer que je n'ai jamais utilisé wxwidgets (que ce soit en python ou en C++). Quand je faisais du python, je me contentais de Tkinter et c'est vrai que j'écrivais tout à la main et que je suis encore vivant.
Mais un des avantages que je vois aux éditeurs graphiques et de limiter à 0 u presque le risque de mélanger dans le code ce qui a trait à l'interface graphique et le reste rendant très facile un redesign complet de la dite interface même par quelqu'un qui n'aurai jamais touché une ligne de code. Je pensais au début que ce genre d'outils n'était qu'un "truc de feignant" promesse d'interfaces graphiques déguelasses. mais j'ai récemment participé à un projet qui utilise libglade (en C, je ne sais pas ce que ça donne en python mais ça doit être au moins aussi facile d'utilisation) et j'ai pu faire des changements très profond dans l'interface graphique en seulement quelques heures (et quelques centaines de clics et seulement une grosse dizaine de lignes de codes modifiées).
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
PierreR
Bon si tu le dis.
Quand je remanie complètement une interface graphique contenant disons 10 - 50 contrôles, il me faut tout au plus 10 minutes et à peu près zéro clics de souris et le code application - partie calcul - n'est pas mélangé avec celui de l'interface graphique.
Ajouter deux paires - texte et texte d'entrée - à une fenêtre de dialogue qui en contient déjà 10, dois bien prendre 2 bonnes minutes.
Chacun sa méthode. Je dois dire que j'utilise des "sizers".
PierreR
Re : interface python et apprentissage boa constrictor
Effectivement, les gouts et les couleurs !
Mais je suis d'accord que pour quelqu'un de soigneux -- contrairement à moi -- tout écrire à la main est tout aussi jouable et présente certains avantages. Personellement, j'apprécie particulièrement quand j'utilise glade de voir en direct le résultat, de pouvoir tester le redimensionnement, etc sans avoir à recompiler quoi que ce soit -- en C ou C++, effectivement, la question ne se pose pas avec Python -- et donc sans attendre.
Mais je reconnais effectivement que c'est plus un gout et un avis personnel que quelque chose d'indiscutable, dans le même genre, je n'ai jamais été un grand fan des traitements de texte wysywyg comme openoffice -- je préfère LaTeX ou des éditeurs de page web du même genre alors qu'en fait pour qulqu'un de soigneux ce sont sûrement des outils qui permettent d'arriver aux même résultat avec peut être moins d'effort.
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
PierreR
Ta remarque concernant Python est très judicieuse. En effet, Python étant interprété, il me suffit d'un F5 (run script) dans mon éditeur pour voir le résultat.
J'apprécie aussi ta remarque à propos de LaTeX. Je suis du même avis, mais n'avait pas osé mettre le sujet sur la table (analogie).
Un point que j'affectionne particulièrement quand on travail à la main: la possibilité de créer aisément un classe dérivée d'un classe de base. C'est quelque chose que je fais très souvent et que je vois chez beaucoup de personnes avec qui j'échange du code. Par exemple: un contrôle d'entrée de texte qui n'accepte que les lettres minuscules ou un nombre.
Une petite question. Quand tu parles de "tester le redimensionnement". Cela signifierait-t-il que tu places les contrôles en définissant leurs positions en "pixels" ?
aleph
Re : interface python et apprentissage boa constrictor
Honte de mon orthographe...
PierreR
Re : interface python et apprentissage boa constrictor
On est quitte, je vois que j'ai fait une quantité de fautes de frappe proprement hallucinante.
Pour l'orienté objet, j'avoue qu'en C je n'ai pas encore vraiment pris l'habitude et en C++ je n'ai jamais fait de grosses interfaces graphiques mais j'entend bien l'argument. Notons toutefois qu'il y a toujours la possibilité de faire cela en laissant un "trou" avec l'interface graphique qu'on remplit ensuite à la main -- il y a même un "widget" special pour ça dans glade je crois.
Pour la dernière question, non je ne place jamais les widgets avec des positions absolues, je voulais dire vérifier que j'ai bien choisies les propriétés d'expansion des widgets de ma fenêtre et que c'est bien la vue arborescente et pas le bouton fermer qui occupe toute la place quand on l'agrandit par exemple -- mais ceci est peut être simplement du à mon inexpérience de GTK.
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
PierreR
Merci.
g_barthe
Re : interface python et apprentissage boa constrictor
Bonjour,
J'ai installé boa constrictor sur windows au bureau tout va bien et sur ma machine ubuntu breezy chez moi. Jusque la tout va bien. petit bémol sur Ubuntu ou les éléments de l'interface sont tronqués même en etendant les fenetres mais bon passons.
J'ai testé un exemple trouvé sur le net sous windows et ca fonctionne mais sous linux non. Alors la je me pose des questions sur la portabilité. Doit-on faire qqch de précis. Je joins le code :
fichier Frame1.py :
#Boa:Frame:Frame1
import wx
def create(parent):
return Frame1(parent)
[wxID_FRAME1, wxID_FRAME1STATUSBAR1,
] = [wx.NewId() for _init_ctrls in range(2)]
[wxID_FRAME1MENUFILEITEMS0, wxID_FRAME1MENUFILEITEMS1,
wxID_FRAME1MENUFILEITEMS2, wxID_FRAME1MENUFILEITEMS3,
wxID_FRAME1MENUFILEITEMS4,
] = [wx.NewId() for _init_coll_menuFile_Items in range(5)]
[wxID_FRAME1MENUHELPABOUT] = [wx.NewId() for _init_coll_menuHelp_Items in range(1)]
class Frame1(wx.Frame):
def _init_coll_menuBar1_Menus(self, parent):
# generated method, don't edit
parent.Append(menu=self.menuFile, title='File')
parent.Append(menu=self.menuHelp, title='Help')
def _init_coll_menuHelp_Items(self, parent):
# generated method, don't edit
parent.Append(help='Display general information about Notebook',
id=wxID_FRAME1MENUHELPABOUT, kind=wx.ITEM_NORMAL, text='About')
self.Bind(wx.EVT_MENU, self.OnMenuHelpAboutMenu,
id=wxID_FRAME1MENUHELPABOUT)
def _init_coll_menuFile_Items(self, parent):
# generated method, don't edit
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS0,
kind=wx.ITEM_NORMAL, text='Open')
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS1,
kind=wx.ITEM_NORMAL, text='Save')
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS2,
kind=wx.ITEM_NORMAL, text='Save As')
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS3,
kind=wx.ITEM_NORMAL, text='Close')
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS4,
kind=wx.ITEM_NORMAL, text='Exit')
self.Bind(wx.EVT_MENU, self.OnMenuFileItems0Menu,
id=wxID_FRAME1MENUFILEITEMS0)
self.Bind(wx.EVT_MENU, self.OnMenuFileItems1Menu,
id=wxID_FRAME1MENUFILEITEMS1)
self.Bind(wx.EVT_MENU, self.OnMenuFileItems2Menu,
id=wxID_FRAME1MENUFILEITEMS2)
self.Bind(wx.EVT_MENU, self.OnMenuFileItems3Menu,
id=wxID_FRAME1MENUFILEITEMS3)
self.Bind(wx.EVT_MENU, self.OnMenuFileItems4Menu,
id=wxID_FRAME1MENUFILEITEMS4)
def _init_coll_statusBar1_Fields(self, parent):
# generated method, don't edit
parent.SetFieldsCount(1)
parent.SetStatusText(number=0, text='Status')
parent.SetStatusWidths([-1])
def _init_utils(self):
# generated method, don't edit
self.menuFile = wx.Menu(title='')
self.menuHelp = wx.Menu(title='')
self.menuBar1 = wx.MenuBar()
self._init_coll_menuFile_Items(self.menuFile)
self._init_coll_menuHelp_Items(self.menuHelp)
self._init_coll_menuBar1_Menus(self.menuBar1)
def _init_ctrls(self, prnt):
# generated method, don't edit
wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
pos=wx.Point(466, 359), size=wx.Size(400, 250),
style=wx.DEFAULT_FRAME_STYLE, title='G\xe9nie climatique')
self._init_utils()
self.SetClientSize(wx.Size(392, 216))
self.SetMenuBar(self.menuBar1)
self.statusBar1 = wx.StatusBar(id=wxID_FRAME1STATUSBAR1,
name='statusBar1', parent=self, style=0)
self._init_coll_statusBar1_Fields(self.statusBar1)
self.SetStatusBar(self.statusBar1)
def __init__(self, parent):
self._init_ctrls(parent)
def OnMenuFileItems0Menu(self, event):
event.Skip()
def OnMenuFileItems1Menu(self, event):
event.Skip()
def OnMenuFileItems2Menu(self, event):
event.Skip()
def OnMenuFileItems3Menu(self, event):
event.Skip()
def OnMenuFileItems4Menu(self, event):
event.Skip()
def OnMenuHelpAboutMenu(self, event):
event.Skip()
fichier App1.py :
#Boa:App:BoaApp
import wx
import Frame1
modules ={'Frame1': [1, 'Main frame of Application', 'Frame1.py']}
class BoaApp(wx.App):
def OnInit(self):
wx.InitAllImageHandlers()
self.main = Frame1.create(None)
self.main.Show()
self.SetTopWindow(self.main)
return True
def main():
application = BoaApp(0)
application.MainLoop()
if __name__ == '__main__':
main()
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
bipede
Re : interface python et apprentissage boa constrictor
C'est un problème de codage de caractères :
si tu changes ta ligne :
style=wx.DEFAULT_FRAME_STYLE, title='G\xe9nie climatique')
dans Frame1.py par :
style=wx.DEFAULT_FRAME_STYLE, title='Génie climatique')
Et que tu ajoutes la ligne :
#-*- coding: utf8 -*-
En première ligne de tes deux scripts, ça va marcher...
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
Boa ou les dix doigts ?
La même application écrite à la main. Pour moi, il n'y a pas photo quant à la clarté du code.
Sans compter les imperfections (erreur) dans le code généré par boa.
# -*- coding: iso-8859-1 -*-
#--------------------------------------------------------------------
# Name: simple.py
# Purpose: Small demo
# Author: Jean-Michel Fauth, Switzerland
# Copyright:
# Licence: None, free software
#--------------------------------------------------------------------
# os dev: w2k sp4
# py dev: Python 2.4.2
# wx dev: wxPython 2.6.3.2
# Revision: 2 May 2006
#--------------------------------------------------------------------
import wx
class MyPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id, wx.DefaultPosition, wx.DefaultSize)
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, (300, 200))
self.CentreOnScreen()
# menus
menu1 = wx.Menu()
menu101 = menu1.Append(101, '&Open...\tCtrl+o', 'Ouvre un fichier')
menu103 = menu1.Append(102, '&Save as...\tCtrl+s', 'Enregistre un fichier sous')
menu102 = menu1.Append(103, 'Save\tCtrl+s', 'Enregistre le fichier courant')
menu104 = menu1.Append(104, '&Close')
menu105 = menu1.Append(105, '&Exit', 'Quitte cette application')
menu2 = wx.Menu()
menu201 = menu2.Append(201, '&About...', 'A propos')
menuBar = wx.MenuBar()
menuBar.Append(menu1, '&File')
menuBar.Append(menu2, '&Help')
self.SetMenuBar(menuBar)
# statusbar
sb = wx.StatusBar(self, wx.NewId())
self.SetStatusBar(sb)
self.Bind(wx.EVT_MENU, self.OnMenu101, menu101)
self.Bind(wx.EVT_MENU, self.OnMenu102, menu102)
self.Bind(wx.EVT_MENU, self.OnMenu103, menu103)
self.Bind(wx.EVT_MENU, self.OnMenu104, menu104)
self.Bind(wx.EVT_MENU, self.OnMenu105, menu105)
self.Bind(wx.EVT_MENU, self.OnMenu201, menu201)
# panel contenant les widgets
self.pa = MyPanel(self, wx.NewId())
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
def OnMenu101(self, event):
print 'Menu101'
def OnMenu102(self, event):
print 'Menu102'
def OnMenu103(self, event):
print 'Menu103'
def OnMenu104(self, event):
print 'Menu104'
def OnMenu105(self, event):
print 'Menu105'
self.OnCloseWindow(None)
def OnMenu201(self, event):
print 'Menu201'
def OnCloseWindow(self, event):
self.Destroy()
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, 'Génie climatique')
frame.Show(True)
self.SetTopWindow(frame)
return True
def main():
app = MyApp(False)
app.MainLoop()
if __name__ == '__main__':
main()
#eof
bipede
Re : interface python et apprentissage boa constrictor
Boa ou les dix doigts ?
La même application écrite à la main. Pour moi, il n'y a pas photo quant à la clarté du code.
Sans compter les imperfections (erreur) dans le code généré par boa.
Tu prêches un convaincu
Mais notre ami veut utiliser un RAD.
Quant au code généré par Boa, il n'est pas si sale que cela, et je trouve que l'objet y est bien utilisé...
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
bipede :
Quant au code généré par Boa, il n'est pas si sale que cela, et je trouve que l'objet y est bien utilisé...
---
Il est même très propre, c'est à dire bien conçu. Ce que je veux montrer ici est que l'utilisation d'un IDE n'est pas la panacée.
Le code généré par Boa doit faire deux choses:
- écrire le code de l'application.
- écrire le code de façon à ce que Boa puisque le récupérer et l'éditer à nouveau. D'où une certaine lourdeur. Une structure de code qui ne correspond pas à ce que l'application est censée faire, mais une structure qui est plus conforme à Boa.
Quelques autres commentaires en vrac :
- wx.InitAllImageHandlers() n'est par nécessaire, cette tâche est effectuée en interne par OnInit(), voir wxPython doc. Cette tâche est exécutée deux fois !
- event.Skip() dans les menus est inutile. Un "pass" eut été suffisant. A quoi bon surcharger, la queue des événements. Il faut bien que Boa mette quelque chose.
- Boa ne génère pas l'événement OnCloseWindow(), très important dans la pratique. Cette partie du code doit de toute façon est rajoutée à la main.
- Mon code avait des doc strings dans le function (triple double quoted strings). Il semblerait que ces doc strings se soient perdus en route !
Ma conclusion :
On en arrive à cette absurdité où seuls les personnes sachant développer à la main sont à même de comprendre correctement le code généré par Boa.
Ceci est vrai pour tous les IDEs.
Je ne peux que recommander une visite chez wxPython.org et télécharger la demo.
aleph
Re : interface python et apprentissage boa constrictor
Petite remarque annexe:
L'IDE ne se nomme pas Boa constrictor, mais Boa constructor. En espérant que vous ayez compris la subtilité du nom.
g_barthe
Re : interface python et apprentissage boa constrictor
Je vous remercie tous pour ces différentes remarques et je sais très bien que les IDE ne sont pas une solution très propre. Moi même pour du HTML je fais tout à la main, je gère mieux ce que je fais je trouve. Mais la n'y connaissant rien à python je voulais déjà créer un joli interface graphique de manière rapide sans trop avoir à comprendre la construction ce que je ferais pour le coeur du programme bien sur. Par la suite oui je redécortiquerais la partie interface pour la recoder de manière simple sans boa.
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
Permets moi d'insister. Est-ce que tu as la demo de wxPython ?
Tous les widgets expliqués, le code pour chaque widget, modification et essai, tout ceci interactivement...sans jamais quitter l'application.
g_barthe
Re : interface python et apprentissage boa constrictor
je viens de le télécharger et effectivement je connaissais pas et ca m'a l'air très instructif et très bien fait. Je vais me pencher ( pas top qd meme) bon c nul, sur cette doc et continuer mon apprentissage et je vous tiendrais au courant de l'evolution.
Merci de votre aide.
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
Enfin ! Si j'ose dire. Comme cela fait bientôt 5 ans que je contribue assez fidèlement au projet wxPython, cela me fait plaisir. Je suis sous win, tu me pardonneras.
Bonne continuation.
bipede
Re : interface python et apprentissage boa constrictor
- wx.InitAllImageHandlers() n'est par nécessaire, cette tâche est effectuée en interne par OnInit(), voir wxPython doc. Cette tâche est exécutée deux fois !
Même si sur le reste je suis complètement d'accord avec toi, sur ce point précis non. L'initialisation des handlers d'images n'est pas automatique, et on doit l'ajouter à la méthode OnInit() de la classe wx.App si on veut que tous les formats d'images soient reconnus (j'ai expérimenté).
Je suis content de rencontrer un contributeur au projet wxpython dont je suis un adepte forcené .
Il est dommage que tu ne travailles que sur windows, car j'ai pu constater des différences de comportement de certains wxWidgets entre les deux OS que je n'ai jamais pu m'expliquer.
Hors ligne |
I have a text file contains "A 0001 1212 00 @@ word" in this format, I wanted to print when Accessing word then only 0001 1212 part has to show along with 00 also has to show dynamically
What have you tried? I am not really following your format.
f=open(filepath, 'r')
hold = f.read()
#hold now = 'A 0001 1212 00 @@ word'
holdout = hold.replace( '@@ word','')
#holdout now = 'A 0001 1212 00 '
#the replace call uses this format
#string.replace('what it is looking for', 'what it is going to be')
Is this what you want? Is there only one line in this file? |
I have build my virtual env with this command:
virtualenv env --distribute --no-site-packages
And then I have installed several modules (django etc) into env with pip, the problem is that when I wanted to run the code on the second machine it would not work, here is what I have done:
visgean@rewitaqia:~/scripty/project_name$ source ./env/bin/activate
(env)visgean@rewitaqia:~/scripty/project_name$ python
Python 2.7.1+ (r271:86832, Sep 27 2012, 21:12:17)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.__file__
'/home/visgean/scripty/project_name/env/lib/python2.7/site-packages/django/__init__.pyc'
but when I want to run it on the second machine:
(env)user@debian:~/project_name$ python
Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named django
>>>
I wild error appears! The first machine is ubuntu, the second one is ubuntu. There seems to be some broken links in /home/user/project_name/env/lib/python2.7 , is that the problem? and if so, how should I prevent it/repair it? |
The original question was:
Is there a way to declare macros in Python as they are declared in C:
#define OBJWITHSIZE(_x) (sizeof _x)/(sizeof _x[0])
Here's what I'm trying to find out:
Is there a way to avoid code duplication in Python? In one part of a program I'm writing, I have a function:
def replaceProgramFilesPath(filenameBr):
def getProgramFilesPath():
import os
return os.environ.get("PROGRAMFILES") + chr(92)
return filenameBr.replace("<ProgramFilesPath>",getProgramFilesPath() )
In another part, I've got this code embedded in a string that will later be
output to a python file that will itself be run:
"""
def replaceProgramFilesPath(filenameBr):
def getProgramFilesPath():
import os
return os.environ.get("PROGRAMFILES") + chr(92)
return filenameBr.replace("<ProgramFilesPath>",getProgramFilesPath() )
"""
How can I build a "macro" that will avoid this duplication? |
Phoenamandre
Re : Suivi des bogues d'Ubuntu 12.10
j'ai le même problème que toi avec mon dell xps !
autre bogue, si vous êtes touchés par un problème de maya qui ne veut pas démarrer
https://bugs.launchpad.net/maya/+bug/1047599
Hors ligne
vlotho
Re : Suivi des bogues d'Ubuntu 12.10
Salut j'ai une ribembelle de warning lors d'une mise à jour et ca depuis plusieurs jours :
warning: Schema 'apps.gcdemu' has path '/apps/gcdemu/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'com.canonical.notify-osd' has path '/apps/notify-osd/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'com.canonical.Unity.ApplicationsLens' has path '/desktop/unity/lenses/applications/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'com.canonical.Unity.Runner' has path '/desktop/unity/runner/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'com.canonical.Unity.FilesLens' has path '/desktop/unity/lenses/files/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'com.canonical.indicator.session' has path '/apps/indicator-session/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'com.ubuntu-tweak.tweak' has path '/apps/ubuntu-tweak/tweak/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'com.ubuntu-tweak.apps' has path '/apps/ubuntu-tweak/apps/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'com.ubuntu-tweak.janitor' has path '/apps/ubuntu-tweak/janitor/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'com.ubuntu.update-manager' has path '/apps/update-manager/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard' has path '/apps/onboard/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.auto-show' has path '/apps/onboard/auto-show/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.keyboard' has path '/apps/onboard/keyboard/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.window' has path '/apps/onboard/window/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.window.landscape' has path '/apps/onboard/window/landscape/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.window.portrait' has path '/apps/onboard/window/portrait/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.icon-palette' has path '/apps/onboard/icon-palette/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.icon-palette.landscape' has path '/apps/onboard/icon-palette/landscape/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.icon-palette.portrait' has path '/apps/onboard/icon-palette/portrait/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.universal-access' has path '/apps/onboard/universal-access/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.theme-settings' has path '/apps/onboard/theme-settings/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.lockdown' has path '/apps/onboard/lockdown/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.scanner' has path '/apps/onboard/scanner/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.freedesktop.Geoclue' has path '/apps/geoclue/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.freedesktop.Telepathy.Logger' has path '/apps/telepathy-logger/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.freedesktop.gstreamer-0.10.default-elements' has path '/desktop/gstreamer/0.10/default-elements/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.Vino' has path '/desktop/gnome/remote-access/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.crypto.cache' has path '/desktop/gnome/crypto/cache/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.crypto.pgp' has path '/desktop/gnome/crypto/pgp/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.seahorse' has path '/apps/seahorse/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.seahorse.manager' has path '/apps/seahorse/listing/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.system.locale' has path '/system/locale/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.system.proxy' has path '/system/proxy/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.system.proxy.http' has path '/system/proxy/http/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.system.proxy.https' has path '/system/proxy/https/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.system.proxy.ftp' has path '/system/proxy/ftp/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.system.proxy.socks' has path '/system/proxy/socks/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.sharing.org-yorba-shotwell-publishing-piwigo' has path '/apps/shotwell/sharing/org-yorba-shotwell-publishing-piwigo/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.sharing.org-yorba-shotwell-publishing-yandex-fotki' has path '/apps/shotwell/sharing/org-yorba-shotwell-publishing-yandex-fotki/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell' has path '/apps/shotwell/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.preferences' has path '/apps/shotwell/preferences/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.preferences.ui' has path '/apps/shotwell/preferences/ui/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.preferences.slideshow' has path '/apps/shotwell/preferences/slideshow/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.preferences.window' has path '/apps/shotwell/preferences/window/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.preferences.files' has path '/apps/shotwell/preferences/files/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.crop-settings' has path '/apps/shotwell/crop-settings/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.preferences.editing' has path '/apps/shotwell/preferences/editing/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.sharing' has path '/apps/shotwell/sharing/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.sharing.facebook' has path '/apps/shotwell/sharing/facebook/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.sharing.flickr' has path '/apps/shotwell/sharing/flickr/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.sharing.picasa' has path '/apps/shotwell/sharing/picasa/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.sharing.youtube' has path '/apps/shotwell/sharing/youtube/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.dataimports' has path '/apps/shotwell/dataimports/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.video' has path '/apps/shotwell/video/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.printing' has path '/apps/shotwell/printing/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.plugins' has path '/apps/shotwell/plugins/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.plugins.enable-state' has path '/apps/shotwell/plugins/enable-state/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
Traitement des actions différées (« triggers ») pour « libglib2.0-0:amd64 »...
warning: Schema 'apps.gcdemu' has path '/apps/gcdemu/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'com.canonical.notify-osd' has path '/apps/notify-osd/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'com.canonical.Unity.ApplicationsLens' has path '/desktop/unity/lenses/applications/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'com.canonical.Unity.Runner' has path '/desktop/unity/runner/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'com.canonical.Unity.FilesLens' has path '/desktop/unity/lenses/files/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'com.canonical.indicator.session' has path '/apps/indicator-session/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'com.ubuntu-tweak.tweak' has path '/apps/ubuntu-tweak/tweak/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'com.ubuntu-tweak.apps' has path '/apps/ubuntu-tweak/apps/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'com.ubuntu-tweak.janitor' has path '/apps/ubuntu-tweak/janitor/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'com.ubuntu.update-manager' has path '/apps/update-manager/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard' has path '/apps/onboard/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.auto-show' has path '/apps/onboard/auto-show/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.keyboard' has path '/apps/onboard/keyboard/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.window' has path '/apps/onboard/window/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.window.landscape' has path '/apps/onboard/window/landscape/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.window.portrait' has path '/apps/onboard/window/portrait/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.icon-palette' has path '/apps/onboard/icon-palette/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.icon-palette.landscape' has path '/apps/onboard/icon-palette/landscape/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.icon-palette.portrait' has path '/apps/onboard/icon-palette/portrait/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.universal-access' has path '/apps/onboard/universal-access/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.theme-settings' has path '/apps/onboard/theme-settings/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.lockdown' has path '/apps/onboard/lockdown/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'apps.onboard.scanner' has path '/apps/onboard/scanner/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.freedesktop.Geoclue' has path '/apps/geoclue/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.freedesktop.Telepathy.Logger' has path '/apps/telepathy-logger/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.freedesktop.gstreamer-0.10.default-elements' has path '/desktop/gstreamer/0.10/default-elements/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.Vino' has path '/desktop/gnome/remote-access/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.crypto.cache' has path '/desktop/gnome/crypto/cache/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.crypto.pgp' has path '/desktop/gnome/crypto/pgp/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.seahorse' has path '/apps/seahorse/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.seahorse.manager' has path '/apps/seahorse/listing/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.system.locale' has path '/system/locale/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.system.proxy' has path '/system/proxy/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.system.proxy.http' has path '/system/proxy/http/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.system.proxy.https' has path '/system/proxy/https/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.system.proxy.ftp' has path '/system/proxy/ftp/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.gnome.system.proxy.socks' has path '/system/proxy/socks/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.sharing.org-yorba-shotwell-publishing-piwigo' has path '/apps/shotwell/sharing/org-yorba-shotwell-publishing-piwigo/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.sharing.org-yorba-shotwell-publishing-yandex-fotki' has path '/apps/shotwell/sharing/org-yorba-shotwell-publishing-yandex-fotki/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell' has path '/apps/shotwell/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.preferences' has path '/apps/shotwell/preferences/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.preferences.ui' has path '/apps/shotwell/preferences/ui/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.preferences.slideshow' has path '/apps/shotwell/preferences/slideshow/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.preferences.window' has path '/apps/shotwell/preferences/window/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.preferences.files' has path '/apps/shotwell/preferences/files/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.crop-settings' has path '/apps/shotwell/crop-settings/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.preferences.editing' has path '/apps/shotwell/preferences/editing/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.sharing' has path '/apps/shotwell/sharing/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.sharing.facebook' has path '/apps/shotwell/sharing/facebook/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.sharing.flickr' has path '/apps/shotwell/sharing/flickr/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.sharing.picasa' has path '/apps/shotwell/sharing/picasa/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.sharing.youtube' has path '/apps/shotwell/sharing/youtube/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.dataimports' has path '/apps/shotwell/dataimports/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.video' has path '/apps/shotwell/video/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.printing' has path '/apps/shotwell/printing/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.plugins' has path '/apps/shotwell/plugins/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
warning: Schema 'org.yorba.shotwell.plugins.enable-state' has path '/apps/shotwell/plugins/enable-state/'. Paths starting with '/apps/', '/desktop/' or '/system/' are deprecated.
Quelqu'un a une idée d'une problème ?
Hors ligne
yoyomc
Re : Suivi des bogues d'Ubuntu 12.10
Ca remarche nickel depuis la mise à jour de vendredi dernier
Hors ligne
vlotho
Re : Suivi des bogues d'Ubuntu 12.10
toujours le même problème après la mise à jour de ce soir
Hors ligne
voigi
Re : Suivi des bogues d'Ubuntu 12.10
bonjour
pareil que viotho , un tas de warning , et je suis en en attente du pilote graphique pour carte ati hd 5770
donc j'ai beaucoup d' application que se lance mal donc vlc et totem
erreur de totem :
(totem:9427): Clutter-CRITICAL **: Unable to initialize Clutter: Failed to connected to any renderer:
XServer appears to lack required GLX support
(totem:9427): Totem-WARNING **: Clutter or GTK+ failed to initialise properly
vu le message d' erreur , je suppose que c du a l'absence de pilote graphique
Dernière modification par voigi (Le 19/09/2012, à 11:55)
Hors ligne
vlotho
Re : Suivi des bogues d'Ubuntu 12.10
toujours les même warnings et ce soir après les multiples crash de compiz, j'ai également ce message :
Impossible de se connecter à la base de données des plantages. Veuillez vérifier votre connexion Internet.'int' object has no attribute 'isspace'
Hors ligne
shindz
Re : Suivi des bogues d'Ubuntu 12.10
chez moi, quand j'applique le theme Radiance , j'ai la barre de titre qui reste noire, vous l'avez aussi ?
P IV, 2.80GHz, 1.5 Go de RAM, Nvidia 6200 512Mo, 160Go HDD
Ubuntu 12.04, AKA Pangolin comme OS Principal
Quantal sur partition de test
Membre attitré de la brigade des S.
Hors ligne
vlotho
Re : Suivi des bogues d'Ubuntu 12.10
déjà dés que je ferme les paramètres système compiz crash et quand je change de thème également. Quand je change de Ambience à Radience, pas de problème puis quand je re permutte effectivement la barre superieure reste noire et la barre de droite ne s'ouvre plus ... mais je crois que ff est planté aussi. Le menu du click droit ne reste pas ouvert.
Hors ligne
shindz
Re : Suivi des bogues d'Ubuntu 12.10
il y a un bug qui traine depuis peu sous quantal : j'ai un disque dur externe avec plusieurs partitions à l'interieur. A chaque redemarrage du systeme ces partition se retrouvent renommées : Music, Music1, Music2...Musicn,
ce bug est chiant !
certes il y a une solution avec fstab, mais vaut mieux une soluce out of the box.
A quel paquet dois-je attribuer ce bug ?
Dernière modification par shindz (Le 21/09/2012, à 14:22)
P IV, 2.80GHz, 1.5 Go de RAM, Nvidia 6200 512Mo, 160Go HDD
Ubuntu 12.04, AKA Pangolin comme OS Principal
Quantal sur partition de test
Membre attitré de la brigade des S.
Hors ligne
frenchy82
Re : Suivi des bogues d'Ubuntu 12.10
Bonjour,
Sous Xubuntu 12.10
Apres avoir installé jockey-gtk si on lance le prog via la console
Le programme 'jockey-gtk' n'est pas encore installé. Vous pouvez l'installer en tapant :
sudo apt-get install jockey-gtk
cartes@xubuntu:~$ jockey-gtk
Le programme 'jockey-gtk' n'est pas encore installé. Vous pouvez l'installer en tapant :
sudo apt-get install jockey-gtk
si on lance un apt-get install jockey-gtk
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
jockey-gtk est déjà la plus récente version disponible.
0 mis à jour, 0 nouvellement installés, 0 à enlever et 0 non mis à jour.
le rapport de bug concerné (mais pas trés dynamique cela dit)
Hors ligne
Malizor
Re : Suivi des bogues d'Ubuntu 12.10
Jockey-gtk n'existe plus. Il a été fusionné avec software-properties.
Découvrez le greffon Arte+7 pour totem !
« Vous prouver que j'ai raison serait admettre que je puisse avoir tort. » - Beaumarchais ← Le premier troll ?
Hors ligne
frenchy82
Re : Suivi des bogues d'Ubuntu 12.10
Ok, merci pour l'info
Si jockey-gtk peut être supprimé doit on tout de même conserver le paquet jockey-common?
Hors ligne
Spitfire 95
Re : Suivi des bogues d'Ubuntu 12.10
Non c'est devenu un métapaquet, donc il est vide et ne sert à rien sauf pour les mises à jour des anciennes versions.
==EDIT==
Ah non il n'est pas marqué comme transitional, mais tu peux quand même l'enlever, je l'ai retiré et ça passe sans problème.
Dernière modification par Spitfire 95 (Le 23/09/2012, à 17:28)
Hors ligne
Malizor
Re : Suivi des bogues d'Ubuntu 12.10
Essaye de l'enlever, tu verras bien si d'autres paquets en dépendent.
Mains sinon le common sert toujours pour jockey-kde.
Dernière modification par Malizor (Le 23/09/2012, à 17:28)
Découvrez le greffon Arte+7 pour totem !
« Vous prouver que j'ai raison serait admettre que je puisse avoir tort. » - Beaumarchais ← Le premier troll ?
Hors ligne
frenchy82
Re : Suivi des bogues d'Ubuntu 12.10
Effectivement cela à l'air tout bon.
D'ailleurs on ne trouve plus dans les services au démarrage de la session une entrée qui concernait la recherche de nouveaux drivers "non libre"
Hors ligne
DidRocks
Re : Suivi des bogues d'Ubuntu 12.10
Non c'est devenu un métapaquet, donc il est vide et ne sert à rien sauf pour les mises à jour des anciennes versions.
==EDIT==
Ah non il n'est pas marqué comme transitional, mais tu peux quand même l'enlever, je l'ai retiré et ça passe sans problème.
Oui, on appelle ça un paquet de transition, un métapaquet, c'est autre chose
Hors ligne
Nepenthes
Re : Suivi des bogues d'Ubuntu 12.10
@DidRocks : l'ombre du unity-panel n'apparaît toujours pas avec unity 6.6, alors qu'elle apparaît bien avec la dernière version de unity 6.4 présente dans unity staging. Ça vient du fait que la version de Compiz dans staging est plus récente que celle de proposed ?
Autre problème, lorsque le seul le bureau est apparent, "Bureau Ubuntu" n'apparaît plus dans le unity-panel, c'est normal ?
J'ai aussi tenté d'activer l'option unredirect windows, mais j'avais des freeze réguliers sur le dash et le spread, et parfois même juste après un certain temps d'inactivité (au lieu d'éteindre l'écran, freeze total de Compiz). Il s'agit de problèmes connus ?
Ancien PC portable : Asus N43SL (Intel i7 2630QM, 4Go RAM, nVidia GeForce GT 540M, DD 640Go 5400tpm) - Ubuntu 14.04
Nouveau PC portable : Toshiba SATELLITE S50t-A-117 (Intel i7 3630QM, 6Go RAM, nVidia GeForce GT 740M, DD 1To 5400tpm) - Ubuntu 14.10
Suivi régulier de Bumblebee (gestion de PC portables hybrides Intel/nvidia).
Hors ligne
DidRocks
Re : Suivi des bogues d'Ubuntu 12.10
@Nepenthes: oui, le compiz actuel n'est pas exactement la dernière version qui devrait arriver après la beta2.
Pour le "Bureau Ubuntu" dans le launcher, je ne sais pas, l'option n'est pas par défaut et je ne vérifie pas ça (il y a une team censée vérifier ça)
L'option unredirect windows n'est pas activée par défaut justement à cause de ces problèmes qui sont toujours en cours de résolution
Hors ligne
seb24
Re : Suivi des bogues d'Ubuntu 12.10
@Nepenthes: oui, le compiz actuel n'est pas exactement la dernière version qui devrait arriver après la beta2.
Pour le "Bureau Ubuntu" dans le launcher, je ne sais pas, l'option n'est pas par défaut et je ne vérifie pas ça (il y a une team censée vérifier ça)
L'option unredirect windows n'est pas activée par défaut justement à cause de ces problèmes qui sont toujours en cours de résolution
ET c'est normal qu'avec le PPA Staging d'Unity il veut me supprimer Unity et Ubuntu-Desktop ?
J'attends depuis quelques jours mais c'est toujours pareil. Je peux pas tester la dernière version... sniff.
Membre attitré de la brigade des SUbuntuser.com : Blog sur Ubuntu http://www.ubuntuser.com
Hors ligne
DidRocks
Re : Suivi des bogues d'Ubuntu 12.10
@seb24: ouai, apparemment, ceux qui s'occupent du ppa ne regardent pas assez. Il doit y avoir un ABI break dans compiz
Hors ligne
seb24
Re : Suivi des bogues d'Ubuntu 12.10
ok ok donc j'attends.
Membre attitré de la brigade des SUbuntuser.com : Blog sur Ubuntu http://www.ubuntuser.com
Hors ligne
Nepenthes
Re : Suivi des bogues d'Ubuntu 12.10
@DidRocks : je parlais bien du panel, et non du launcher.
Ancien PC portable : Asus N43SL (Intel i7 2630QM, 4Go RAM, nVidia GeForce GT 540M, DD 640Go 5400tpm) - Ubuntu 14.04
Nouveau PC portable : Toshiba SATELLITE S50t-A-117 (Intel i7 3630QM, 6Go RAM, nVidia GeForce GT 740M, DD 1To 5400tpm) - Ubuntu 14.10
Suivi régulier de Bumblebee (gestion de PC portables hybrides Intel/nvidia).
Hors ligne
DidRocks
Re : Suivi des bogues d'Ubuntu 12.10
@Nepenthes: je ne comprends pas alors Ah si!
Euh non, pas normal, tu as bien Nautilus de quantal d'installé? pas le 3.6 d'un ppa hein (3.6 supprime le menubar)?
Hors ligne
Nepenthes
Re : Suivi des bogues d'Ubuntu 12.10
Oui, j'ai bien nautilus, dans la bonne version. J'ai l'impression que quelque chose s'est mal passé avec ma downgrade depuis le ppa de unity staging, aucun paquet n'a sauté, mais j'ai du réinstaller les indicators et certaines lens, qui n'étaient pas actives malgré leur présence sur le système. J'ai aussi réinstallé nautilus, mais c'est resté sans effet. Ça sent le problème côté scripts d'installation/désinstallation (des hooks manquants ?).
Pour confirmer ma petite expérience, il faut installer le ppa unity staging, mettre à jour, relancer unity, puis supprimer purger le ppa, et relancer unity encore. Normalemnt, il est complètement cassé malgré une procédure normale.
J'ai aussi tenté la suppression des fichiers de conf de l'utilisateur, sans effet.
Dernière modification par Nepenthes (Le 24/09/2012, à 14:58)
Ancien PC portable : Asus N43SL (Intel i7 2630QM, 4Go RAM, nVidia GeForce GT 540M, DD 640Go 5400tpm) - Ubuntu 14.04
Nouveau PC portable : Toshiba SATELLITE S50t-A-117 (Intel i7 3630QM, 6Go RAM, nVidia GeForce GT 740M, DD 1To 5400tpm) - Ubuntu 14.10
Suivi régulier de Bumblebee (gestion de PC portables hybrides Intel/nvidia).
Hors ligne
corto69
Re : Suivi des bogues d'Ubuntu 12.10
Bonjour,
Depuis une mise à jour hier soir, j'ai quelques programmes qui ne se lancent plus:
Thunderbird, Amule, filezilla ,avidemux.
En lançant l'application via la console, voici le retour pour thunderbird
(thunderbird:3842): Gtk-CRITICAL **: _ubuntu_gtk_overlay_scrollbar_new: assertion `os_scrollbar_new' failed
(thunderbird:3842): Gtk-CRITICAL **: IA__gtk_container_add: assertion `GTK_IS_WIDGET (widget)' failed
(thunderbird:3842): Gtk-CRITICAL **: IA__gtk_widget_realize: assertion `GTK_IS_WIDGET (widget)' failed
(thunderbird:3842): GLib-GObject-CRITICAL **: g_object_set_data: assertion `G_IS_OBJECT (object)' failed
(thunderbird:3842): Gtk-CRITICAL **: _ubuntu_gtk_overlay_scrollbar_new: assertion `os_scrollbar_new' failed
(thunderbird:3842): Gtk-CRITICAL **: IA__gtk_container_add: assertion `GTK_IS_WIDGET (widget)' failed
(thunderbird:3842): Gtk-CRITICAL **: IA__gtk_widget_realize: assertion `GTK_IS_WIDGET (widget)' failed
(thunderbird:3842): GLib-GObject-CRITICAL **: g_object_set_data: assertion `G_IS_OBJECT (object)' failed
(thunderbird:3842): Gtk-CRITICAL **: _ubuntu_gtk_overlay_scrollbar_new: assertion `os_scrollbar_new' failed
(thunderbird:3842): Gtk-CRITICAL **: IA__gtk_container_add: assertion `GTK_IS_WIDGET (widget)' failed
(thunderbird:3842): Gtk-CRITICAL **: IA__gtk_widget_realize: assertion `GTK_IS_WIDGET (widget)' failed
(thunderbird:3842): GLib-GObject-CRITICAL **: g_object_set_data: assertion `G_IS_OBJECT (object)' failed
(thunderbird:3842): Gtk-CRITICAL **: _ubuntu_gtk_overlay_scrollbar_new: assertion `os_scrollbar_new' failed
(thunderbird:3842): Gtk-CRITICAL **: IA__gtk_container_add: assertion `GTK_IS_WIDGET (widget)' failed
(thunderbird:3842): Gtk-CRITICAL **: IA__gtk_widget_realize: assertion `GTK_IS_WIDGET (widget)' failed
(thunderbird:3842): GLib-GObject-CRITICAL **: g_object_set_data: assertion `G_IS_OBJECT (object)' failed
(thunderbird:3842): Gtk-CRITICAL **: IA__gtk_widget_style_get: assertion `GTK_IS_WIDGET (widget)' failed
mude@veranda:~$
(crashreporter:3864): Gtk-CRITICAL **: _ubuntu_gtk_overlay_scrollbar_new: assertion `os_scrollbar_new' failed
(crashreporter:3864): Gtk-CRITICAL **: IA__gtk_widget_set_composite_name: assertion `GTK_IS_WIDGET (widget)' failed
(crashreporter:3864): Gtk-CRITICAL **: IA__gtk_widget_set_parent: assertion `GTK_IS_WIDGET (widget)' failed
(crashreporter:3864): GLib-GObject-CRITICAL **: g_object_ref: assertion `G_IS_OBJECT (object)' failed
(crashreporter:3864): Gtk-CRITICAL **: IA__gtk_widget_show: assertion `GTK_IS_WIDGET (widget)' failed
(crashreporter:3864): Gtk-CRITICAL **: IA__gtk_range_get_adjustment: assertion `GTK_IS_RANGE (range)' failed
(crashreporter:3864): GLib-GObject-WARNING **: invalid (NULL) pointer instance
(crashreporter:3864): GLib-GObject-CRITICAL **: g_signal_connect_data: assertion `G_TYPE_CHECK_INSTANCE (instance)' failed
(crashreporter:3864): Gtk-CRITICAL **: gtk_scrolled_window_adjustment_changed: assertion `adjustment != NULL' failed
(crashreporter:3864): Gtk-CRITICAL **: _ubuntu_gtk_overlay_scrollbar_new: assertion `os_scrollbar_new' failed
(crashreporter:3864): Gtk-CRITICAL **: IA__gtk_widget_set_composite_name: assertion `GTK_IS_WIDGET (widget)' failed
(crashreporter:3864): Gtk-CRITICAL **: IA__gtk_widget_set_parent: assertion `GTK_IS_WIDGET (widget)' failed
(crashreporter:3864): GLib-GObject-CRITICAL **: g_object_ref: assertion `G_IS_OBJECT (object)' failed
(crashreporter:3864): Gtk-CRITICAL **: IA__gtk_widget_show: assertion `GTK_IS_WIDGET (widget)' failed
(crashreporter:3864): Gtk-CRITICAL **: IA__gtk_range_get_adjustment: assertion `GTK_IS_RANGE (range)' failed
(crashreporter:3864): GLib-GObject-WARNING **: invalid (NULL) pointer instance
(crashreporter:3864): GLib-GObject-CRITICAL **: g_signal_connect_data: assertion `G_TYPE_CHECK_INSTANCE (instance)' failed
(crashreporter:3864): Gtk-CRITICAL **: gtk_scrolled_window_adjustment_changed: assertion `adjustment != NULL' failed
(crashreporter:3864): Gtk-CRITICAL **: IA__gtk_range_get_adjustment: assertion `GTK_IS_RANGE (range)' failed
(crashreporter:3864): Gtk-CRITICAL **: IA__gtk_range_get_adjustment: assertion `GTK_IS_RANGE (range)' failed
(crashreporter:3864): Gtk-CRITICAL **: IA__gtk_widget_size_request: assertion `GTK_IS_WIDGET (widget)' failed
(crashreporter:3864): Gtk-CRITICAL **: IA__gtk_widget_size_request: assertion `GTK_IS_WIDGET (widget)' failed
(crashreporter:3864): GLib-GObject-CRITICAL **: g_object_get_qdata: assertion `G_IS_OBJECT (object)' failed
(crashreporter:3864): GLib-GObject-CRITICAL **: g_object_get_qdata: assertion `G_IS_OBJECT (object)' failed
De ce que j'ai compris, il doit y avoir un problème avec GTK mais je n'en suis pas sur.
J'ai fait une MAJ ce matin mais sans changement
Puissent tous les Hommes se souvenir qu'ils sont frères
Voltaire
Hors ligne |
Is there the most popular way of adding a text on an image in Python? I found a few completely different approaches, this seems to be best, but it doesn't work:
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
img = Image.open("/full_path/1.jpg")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-C.ttf", 16)
draw.text((0, 0),"Sample Text",(255,255,255),font=font)
img.save('/full_path/sample-out.jpg')
After its running, the picture still doesn't have a text on it. |
mako
Perdu OGMRip et impossible de le réinstaller !
Bonjour,
J'utilise Ubuntu 12.04 sur un Lenovo G580.
Il y a quelques semaines je séchais déjà sur l'utilisation d'OGMRip, que je trouve pourtant génial pour ripper les DVD.
J'avais laissé un message sur le forum resté sans réponse. Je voulais ripper mes DVD sans obtenir des résultats chaotiques aussi bien au niveau du son que de l'image.
Dernièrement j'ai voulu modifier les paramètres d'OGM pour arriver à des résultats en 2 parties, qui étaient souvent de nettement meilleure qualité.
Sauf que j'ai voulu remettre les réglages comme à l'origine et que je n'y suis pas arrivé.
J'ai donc pensé à supprimer OGM et à le réinstaller. Sauf que la réinstallation n'est pas possible : on me précise qu'en installant je serais obligé d'installer aussi des paquets non vérifiés (ou quelque chose du genre). On me propose 2 choix : "Valider" ou "Réparer". J'ai essayé les 2 et rien ne se passe.
En résumé : j'ai tenté de résoudre seul mon problème et me voilà plus dans la mouise.
Merci d'avance pour toute aide !
Mako
"Rien ne se crée, rien ne se perd, tout se digère."
Hors ligne
Slyfox
Re : Perdu OGMRip et impossible de le réinstaller !
Bonjour
Juste comme ça quel est le format de sortie de tes copies de DVD ???
Slyfox
Dernière modification par Slyfox (Le 30/03/2014, à 14:21)
Hors ligne
mako
Re : Perdu OGMRip et impossible de le réinstaller !
@ Slyfox : Ca a changé pas mal de fois.
J'ai tenté de faire :
- du .mkv avec des pistes audio dans plusieurs langues et avec plusieurs pistes de sous-titres intégrés... Sans succès.
- du .avi avec sous-titres séparés (j'aurais bien aimé des fichiers .srt, pratiques à mon goût pour les manips avec Gnome Subtitles). Format d'environ 700 Mo. Sans succès non plus.
- dernièrement j'étais passé à du .avi d'environ 700 Mo, en copiant les films en 2 parties. L'avantage était d'obtenir certains films d'action avec un bon son et une image sans gros carrés dégueulasses. L'inconvénient, c'est que j'étais incapable de rechanger les réglages et que pour trouver des sous-titres supplémentaires sur le net (correspondant au résultat auquel j'étais arrivé) c'était mission impossible.
Voilà.
"Rien ne se crée, rien ne se perd, tout se digère."
Hors ligne
mako
Re : Perdu OGMRip et impossible de le réinstaller !
Ah bein, y avait une autre réponse qui proposait une solution, mais elle a été supprimée avant que j'aie le temps de l'essayer...
Super !
"Rien ne se crée, rien ne se perd, tout se digère."
Hors ligne
Slyfox
Re : Perdu OGMRip et impossible de le réinstaller !
Tu pourrais essayer le soft en lien dans ma signature.
Slyfox
Hors ligne
Gatsu
Re : Perdu OGMRip et impossible de le réinstaller !
ou Handbrake
Hors ligne
Machtheld
Re : Perdu OGMRip et impossible de le réinstaller !
Salut Mako,
Je pense qu'il y a un problème avec le fichier qui contient les sources de logiciels (etc/apt/sources.list). Il faut en recréer un au moyen d'un générateur comme celui-ci: http://repogen.simplylinux.ch/ (remplacer le contenu de ton sources.list par le résultat).
Puis recharger la liste des paquets, et réinstaller OGMRip.
Hors ligne
mako
Re : Perdu OGMRip et impossible de le réinstaller !
Merci pour vos réponses.
Dans l'immédiat je vais surtout me concentrer sur celle de Machtheld ("héros du pouvoir", c'est ça ?), car elle fait allusion à un problème de fond. dernièrement j'ai essayé plusieurs fois d'installer de nouveaux logiciels depuis la Logithèque et ça a échoué.
J'ai jeté un oeil au lien que tu as donné. Ca me rappelle une fenêtre que j'ai vue souvent dans mon ordi (mais je sais plus où elle est ni comment elle s'appelle). Ca sert à quoi en fait ? Quand j'ai vu cette page en anglais et aux termes obscurs, ça ne m'a pas trop mis en confiance...:rolleyes:
"Rien ne se crée, rien ne se perd, tout se digère."
Hors ligne
Machtheld
Re : Perdu OGMRip et impossible de le réinstaller !
Bon. Il y a un fichier qui s'appelle /etc/apt/sources.list, et qui contient les liens vers les paquets dans les dépôts. J'ai aussi Xubuntu 12.4, et apparemment ces liens ne sont plus à jour.
Il faut sauvegarder le contenu de ce fichier, aller sur le lien que je t'ai donné, et générer un nouveau fichier. Pour Xubuntu 12.4 cela donne ça, tu peux l'utiliser tel quel:
#############################################################
################### OFFICIAL UBUNTU REPOS ###################
#############################################################
###### Ubuntu Main Repos
deb http://fr.archive.ubuntu.com/ubuntu/ precise main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise main restricted universe multiverse
###### Ubuntu Update Repos
deb http://fr.archive.ubuntu.com/ubuntu/ precise-security main restricted universe multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ precise-updates main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-security main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-updates main restricted universe multiverse
###### Ubuntu Extras Repo
deb http://extras.ubuntu.com/ubuntu precise main
deb-src http://extras.ubuntu.com/ubuntu precise main
Puis faire la commande:
sudo gedit /etc/apt/sources.list
Ensuite, faire un copier-coller du texte çi-dessus à la place du contenu de ton /etc/apt/sources.list. Sauvegarder et fermer.
Recharger la liste des paquets:
sudo apt-get update
Et ensuite tu réinstalles ton programme
Dernière modification par Machtheld (Le 08/04/2014, à 22:40)
Hors ligne
mako
Re : Perdu OGMRip et impossible de le réinstaller !
En fait si j'utilise le lien que tu m'as donné, il y a un tableau avec des case à cocher. Mais je sais pas à quoi elles correspondent, ces cases...
Je me vois pas trop cocher au hasard.
(La dernière fois que j'ai coché des trucs au hasard mon PC était planté pendant 10 jours, et j'ai passé autant de nuits sur le forum depuis un autre ordi pour tenter de le récupérer. )
"Rien ne se crée, rien ne se perd, tout se digère."
Hors ligne
Machtheld
Re : Perdu OGMRip et impossible de le réinstaller !
Hum. Relis bien ce que j'ai écrit: tu n'as qu'à copier-coller le code que je t'ai donné...
Hors ligne
mako
Re : Perdu OGMRip et impossible de le réinstaller !
J'ai relu. Mais il y a des choses que je ne comprends pas :
- Tu parles de Xubuntu. Je vois pas en quoi ça me concerne.
- Le contenu de ton avant-dernier message ressemble aux commandes qu'il faudrait entrer dans un terminal. Du moins à partir du 1er "sudo". Ce qu'il y a avant, je ne sais pas quoi en faire...
Désolé de te faire répéter, mais j'ai du mal à suivre ce que tu me conseilles. Merci d'être plus précis.
"Rien ne se crée, rien ne se perd, tout se digère."
Hors ligne
mako
Re : Perdu OGMRip et impossible de le réinstaller !
La longue série de données que tu as citée (je sais pas comment les nommer après "OFFICIAL UBUNTU REPOS") m'a fait penser à une fenêtre à laquelle je peux accéder quand je fais des mises à jour ou dans les fenêtres de logiciels. Pour en avoir le coeur net, j'ai tenté une mise à jour. Un message d'erreur, encore et encore :
W:Failed to fetch [url]http://packages.medibuntu.org/dists/precise/Release.gpg[/url] Something wicked happened resolving 'packages.medibuntu.org:http' (-5 - No address associated with hostname)
, W:Failed to fetch [url]http://packages.medibuntu.org/dists/precise/free/binary-amd64/Packages[/url] Something wicked happened resolving 'packages.medibuntu.org:http' (-5 - No address associated with hostname)
, W:Failed to fetch [url]http://packages.medibuntu.org/dists/precise/non-free/binary-amd64/Packages[/url] Something wicked happened resolving 'packages.medibuntu.org:http' (-5 - No address associated with hostname)
, W:Failed to fetch [url]http://packages.medibuntu.org/dists/precise/free/binary-i386/Packages[/url] Something wicked happened resolving 'packages.medibuntu.org:http' (-5 - No address associated with hostname)
, W:Failed to fetch [url]http://packages.medibuntu.org/dists/precise/non-free/binary-i386/Packages[/url] Something wicked happened resolving 'packages.medibuntu.org:http' (-5 - No address associated with hostname)
, W:Failed to fetch [url]http://packages.medibuntu.org/dists/precise/free/i18n/Translation-en[/url] Something wicked happened resolving 'packages.medibuntu.org:http' (-5 - No address associated with hostname)
, W:Failed to fetch [url]http://packages.medibuntu.org/dists/precise/free/i18n/Translation-fr[/url] Something wicked happened resolving 'packages.medibuntu.org:http' (-5 - No address associated with hostname)
, W:Failed to fetch [url]http://packages.medibuntu.org/dists/precise/non-free/i18n/Translation-en[/url] Something wicked happened resolving 'packages.medibuntu.org:http' (-5 - No address associated with hostname)
, W:Failed to fetch [url]http://packages.medibuntu.org/dists/precise/non-free/i18n/Translation-fr[/url] Something wicked happened resolving 'packages.medibuntu.org:http' (-5 - No address associated with hostname)
, E:Some index files failed to download. They have been ignored, or old ones used instead.
Dernière modification par mako (Le 11/04/2014, à 12:42)
"Rien ne se crée, rien ne se perd, tout se digère."
Hors ligne
Machtheld
Re : Perdu OGMRip et impossible de le réinstaller !
Mea culpa, j'ai lu trop vite que tu utilisais Xubuntu.
Cela ne change rien. Il faut que tu ouvres ton fichier /etc/apt/sources.list:
gksudo gedit /etc/apt/sources.list
Tu sauvegardes le contenu (un copier-coller fait l'affaire). Ensuite, tu colles à la place le code que je t'ai donné (le truc qui commence par "official Ubuntu repos").
Tu sauvegardes, tu fermes. Ensuite:
sudo apt-get update
Enfin:
sudo apt-get install ogmrip
Dernière modification par Machtheld (Le 11/04/2014, à 12:53)
Hors ligne
mako
Re : Perdu OGMRip et impossible de le réinstaller !
A nouveau quelque chose que je ne comprends pas : je devrais sauvegarder à la fois le fichier /etc/apt/sources.list actuel...
... et coller à la place le code que tu m'as donné pour re-sauvegarder ?
Ca veut dire que le 1er va être effacé...
Ou alors : où et pourquoi sauvegarder le 1er s'il ne me sert pas ?
Quand j'aurais la réponse, je passerai à l'action.
"Rien ne se crée, rien ne se perd, tout se digère."
Hors ligne
Machtheld
Re : Perdu OGMRip et impossible de le réinstaller !
A nouveau quelque chose que je ne comprends pas : je devrais sauvegarder à la fois le fichier /etc/apt/sources.list actuel...
... et coller à la place le code que tu m'as donné pour re-sauvegarder ?
Ca veut dire que le 1er va être effacé...
Exactement!
Ou alors : où et pourquoi sauvegarder le 1er s'il ne me sert pas ?
Juste au cas où!
Quand j'aurais la réponse, je passerai à l'action.
Hors ligne
Cyrille BORNE
Re : Perdu OGMRip et impossible de le réinstaller !
Bonjour,
J'utilise Ubuntu 12.04 sur un Lenovo G580.
Il y a quelques semaines je séchais déjà sur l'utilisation d'OGMRip, que je trouve pourtant génial pour ripper les DVD.
J'avais laissé un message sur le forum resté sans réponse. Je voulais ripper mes DVD sans obtenir des résultats chaotiques aussi bien au niveau du son que de l'image.
Dernièrement j'ai voulu modifier les paramètres d'OGM pour arriver à des résultats en 2 parties, qui étaient souvent de nettement meilleure qualité.
Sauf que j'ai voulu remettre les réglages comme à l'origine et que je n'y suis pas arrivé.
J'ai donc pensé à supprimer OGM et à le réinstaller. Sauf que la réinstallation n'est pas possible : on me précise qu'en installant je serais obligé d'installer aussi des paquets non vérifiés (ou quelque chose du genre). On me propose 2 choix : "Valider" ou "Réparer". J'ai essayé les 2 et rien ne se passe.
En résumé : j'ai tenté de résoudre seul mon problème et me voilà plus dans la mouise.
Merci d'avance pour toute aide !
Mako
Je n'ai absolument rien compris.
Est ce que tu as fait un apt-get purge et après un apt-get install ogmrip ?
Hors ligne
mako
Re : Perdu OGMRip et impossible de le réinstaller !
@ Machtheld : La 2e commande que tu m'as donnée donne :
mistral@Venus:~$ gksudo gedit /etc/apt/sources.list
mistral@Venus:~$ gksudo gedit /etc/apt/sources.list
mistral@Venus:~$ sudo apt-get update
Réception de : 1 http://extras.ubuntu.com precise Release.gpg [72 B]
Atteint http://ppa.launchpad.net precise Release.gpg
Atteint http://ppa.launchpad.net precise Release.gpg
Atteint http://ppa.launchpad.net precise Release.gpg
Atteint http://fr.archive.ubuntu.com precise Release.gpg
Réception de : 2 http://fr.archive.ubuntu.com precise-security Release.gpg [198 B]
Réception de : 3 http://fr.archive.ubuntu.com precise-updates Release.gpg [198 B]
Atteint http://extras.ubuntu.com precise Release
Atteint http://fr.archive.ubuntu.com precise Release
Atteint http://ppa.launchpad.net precise Release
Atteint http://ppa.launchpad.net precise Release
Réception de : 4 http://fr.archive.ubuntu.com precise-security Release [49,6 kB]
Atteint http://ppa.launchpad.net precise Release
Atteint http://extras.ubuntu.com precise/main Sources
Atteint http://ppa.launchpad.net precise/main Sources
Réception de : 5 http://fr.archive.ubuntu.com precise-updates Release [49,6 kB]
Atteint http://extras.ubuntu.com precise/main amd64 Packages
Atteint http://extras.ubuntu.com precise/main i386 Packages
Ign http://extras.ubuntu.com precise/main TranslationIndex
Atteint http://ppa.launchpad.net precise/main amd64 Packages
Atteint http://ppa.launchpad.net precise/main i386 Packages
Ign http://ppa.launchpad.net precise/main TranslationIndex
Atteint http://ppa.launchpad.net precise/main Sources
Atteint http://ppa.launchpad.net precise/main amd64 Packages
Atteint http://ppa.launchpad.net precise/main i386 Packages
Ign http://ppa.launchpad.net precise/main TranslationIndex
Atteint http://ppa.launchpad.net precise/main Sources
Atteint http://ppa.launchpad.net precise/main amd64 Packages
Atteint http://fr.archive.ubuntu.com precise/main Sources
Atteint http://fr.archive.ubuntu.com precise/restricted Sources
Atteint http://fr.archive.ubuntu.com precise/universe Sources
Atteint http://fr.archive.ubuntu.com precise/multiverse Sources
Atteint http://fr.archive.ubuntu.com precise/main amd64 Packages
Atteint http://fr.archive.ubuntu.com precise/restricted amd64 Packages
Atteint http://fr.archive.ubuntu.com precise/universe amd64 Packages
Atteint http://fr.archive.ubuntu.com precise/multiverse amd64 Packages
Atteint http://fr.archive.ubuntu.com precise/main i386 Packages
Atteint http://ppa.launchpad.net precise/main i386 Packages
Ign http://ppa.launchpad.net precise/main TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/restricted i386 Packages
Atteint http://fr.archive.ubuntu.com precise/universe i386 Packages
Atteint http://fr.archive.ubuntu.com precise/multiverse i386 Packages
Atteint http://fr.archive.ubuntu.com precise/main TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/multiverse TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/restricted TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/universe TranslationIndex
Réception de : 6 http://fr.archive.ubuntu.com precise-security/main Sources [102 kB]
Réception de : 7 http://fr.archive.ubuntu.com precise-security/restricted Sources [2 494 B]
Réception de : 8 http://fr.archive.ubuntu.com precise-security/universe Sources [30,9 kB]
Réception de : 9 http://fr.archive.ubuntu.com precise-security/multiverse Sources [1 797 B]
Réception de : 10 http://fr.archive.ubuntu.com precise-security/main amd64 Packages [376 kB]
Réception de : 11 http://fr.archive.ubuntu.com precise-security/restricted amd64 Packages [4 627 B]
Réception de : 12 http://fr.archive.ubuntu.com precise-security/universe amd64 Packages [91,8 kB]
Réception de : 13 http://fr.archive.ubuntu.com precise-security/multiverse amd64 Packages [2 439 B]
Réception de : 14 http://fr.archive.ubuntu.com precise-security/main i386 Packages [402 kB]
Ign http://extras.ubuntu.com precise/main Translation-fr_FR
Ign http://extras.ubuntu.com precise/main Translation-fr
Ign http://extras.ubuntu.com precise/main Translation-de_DE
Ign http://ppa.launchpad.net precise/main Translation-fr_FR
Ign http://ppa.launchpad.net precise/main Translation-fr
Ign http://ppa.launchpad.net precise/main Translation-de_DE
Ign http://ppa.launchpad.net precise/main Translation-en
Ign http://ppa.launchpad.net precise/main Translation-fr_FR
Ign http://ppa.launchpad.net precise/main Translation-fr
Réception de : 15 http://fr.archive.ubuntu.com precise-security/restricted i386 Packages [4 620 B]
Réception de : 16 http://fr.archive.ubuntu.com precise-security/universe i386 Packages [96,5 kB]
Ign http://extras.ubuntu.com precise/main Translation-en
Ign http://ppa.launchpad.net precise/main Translation-de_DE
Ign http://ppa.launchpad.net precise/main Translation-en
Ign http://ppa.launchpad.net precise/main Translation-fr_FR
Ign http://ppa.launchpad.net precise/main Translation-fr
Réception de : 17 http://fr.archive.ubuntu.com precise-security/multiverse i386 Packages [2 649 B]
Réception de : 18 http://fr.archive.ubuntu.com precise-security/main TranslationIndex [74 B]
Réception de : 19 http://fr.archive.ubuntu.com precise-security/multiverse TranslationIndex [72 B]
Réception de : 20 http://fr.archive.ubuntu.com precise-security/restricted TranslationIndex [72 B]
Réception de : 21 http://fr.archive.ubuntu.com precise-security/universe TranslationIndex [73 B]
Réception de : 22 http://fr.archive.ubuntu.com precise-updates/main Sources [454 kB]
Ign http://ppa.launchpad.net precise/main Translation-de_DE
Ign http://ppa.launchpad.net precise/main Translation-en
Réception de : 23 http://fr.archive.ubuntu.com precise-updates/restricted Sources [8 028 B]
Réception de : 24 http://fr.archive.ubuntu.com precise-updates/universe Sources [106 kB]
Réception de : 25 http://fr.archive.ubuntu.com precise-updates/multiverse Sources [8 909 B]
Réception de : 26 http://fr.archive.ubuntu.com precise-updates/main amd64 Packages [764 kB]
Réception de : 27 http://fr.archive.ubuntu.com precise-updates/restricted amd64 Packages [12,2 kB]
Réception de : 28 http://fr.archive.ubuntu.com precise-updates/universe amd64 Packages [239 kB]
Réception de : 29 http://fr.archive.ubuntu.com precise-updates/multiverse amd64 Packages [15,3 kB]
Réception de : 30 http://fr.archive.ubuntu.com precise-updates/main i386 Packages [788 kB]
Réception de : 31 http://fr.archive.ubuntu.com precise-updates/restricted i386 Packages [12,2 kB]
Réception de : 32 http://fr.archive.ubuntu.com precise-updates/universe i386 Packages [244 kB]
Réception de : 33 http://fr.archive.ubuntu.com precise-updates/multiverse i386 Packages [15,4 kB]
Atteint http://fr.archive.ubuntu.com precise-updates/main TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-updates/restricted TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-updates/universe TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/main Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/main Translation-fr
Atteint http://fr.archive.ubuntu.com precise/main Translation-en
Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-fr
Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com precise/restricted Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/restricted Translation-fr
Atteint http://fr.archive.ubuntu.com precise/restricted Translation-en
Atteint http://fr.archive.ubuntu.com precise/universe Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/universe Translation-fr
Atteint http://fr.archive.ubuntu.com precise/universe Translation-en
Réception de : 34 http://fr.archive.ubuntu.com precise-security/main Translation-en [175 kB]
Réception de : 35 http://fr.archive.ubuntu.com precise-security/multiverse Translation-en [1 299 B]
Réception de : 36 http://fr.archive.ubuntu.com precise-security/restricted Translation-en [1 253 B]
Réception de : 37 http://fr.archive.ubuntu.com precise-security/universe Translation-en [56,7 kB]
Atteint http://fr.archive.ubuntu.com precise-updates/main Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/main 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/restricted Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/restricted Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/universe Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/universe Translation-en
Err http://packages.medibuntu.org precise Release.gpg
Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
Ign http://packages.medibuntu.org precise Release
Ign http://packages.medibuntu.org precise/free amd64 Packages/DiffIndex
Ign http://packages.medibuntu.org precise/non-free amd64 Packages/DiffIndex
Ign http://packages.medibuntu.org precise/free i386 Packages/DiffIndex
Ign http://packages.medibuntu.org precise/non-free i386 Packages/DiffIndex
Ign http://packages.medibuntu.org precise/free TranslationIndex
Ign http://packages.medibuntu.org precise/non-free TranslationIndex
Err http://packages.medibuntu.org precise/free amd64 Packages
Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
Err http://packages.medibuntu.org precise/non-free amd64 Packages
Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
Err http://packages.medibuntu.org precise/free i386 Packages
Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
Err http://packages.medibuntu.org precise/non-free i386 Packages
Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
Err http://packages.medibuntu.org precise/free Translation-fr_FR
Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
Err http://packages.medibuntu.org precise/free Translation-fr
Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
Err http://packages.medibuntu.org precise/free Translation-de_DE
Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
Err http://packages.medibuntu.org precise/free Translation-en
Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
Err http://packages.medibuntu.org precise/non-free Translation-fr_FR
Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
Err http://packages.medibuntu.org precise/non-free Translation-fr
Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
Err http://packages.medibuntu.org precise/non-free Translation-de_DE
Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
Err http://packages.medibuntu.org precise/non-free Translation-en
Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
4 119 ko réceptionnés en 7min 6s (9 666 o/s)
W: Impossible de récupérer http://packages.medibuntu.org/dists/precise/Release.gpg Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
W: Impossible de récupérer http://packages.medibuntu.org/dists/precise/free/binary-amd64/Packages Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
W: Impossible de récupérer http://packages.medibuntu.org/dists/precise/non-free/binary-amd64/Packages Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
W: Impossible de récupérer http://packages.medibuntu.org/dists/precise/free/binary-i386/Packages Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
W: Impossible de récupérer http://packages.medibuntu.org/dists/precise/non-free/binary-i386/Packages Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
W: Impossible de récupérer http://packages.medibuntu.org/dists/precise/free/i18n/Translation-fr_FR Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
W: Impossible de récupérer http://packages.medibuntu.org/dists/precise/free/i18n/Translation-fr Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
W: Impossible de récupérer http://packages.medibuntu.org/dists/precise/free/i18n/Translation-de_DE Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
W: Impossible de récupérer http://packages.medibuntu.org/dists/precise/free/i18n/Translation-en Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
W: Impossible de récupérer http://packages.medibuntu.org/dists/precise/non-free/i18n/Translation-fr_FR Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
W: Impossible de récupérer http://packages.medibuntu.org/dists/precise/non-free/i18n/Translation-fr Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
W: Impossible de récupérer http://packages.medibuntu.org/dists/precise/non-free/i18n/Translation-de_DE Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
W: Impossible de récupérer http://packages.medibuntu.org/dists/precise/non-free/i18n/Translation-en Quelque chose d'imprévisible est survenu lors de la détermination de « packages.medibuntu.org:http » (-5 - Aucune adresse associée avec le nom de l'hôte)
E: Le téléchargement de quelques fichiers d'index a échoué, ils ont été ignorés, ou les anciens ont été utilisés à la place.
Ca sonne pas très positif...
@ Cyrille BORNE : Non.
"Rien ne se crée, rien ne se perd, tout se digère."
Hors ligne
Cyrille BORNE
Re : Perdu OGMRip et impossible de le réinstaller !
peux tu me montrer ton sources.list
Hors ligne
mako
Re : Perdu OGMRip et impossible de le réinstaller !
Celui que j'ai copié pour le garder au cas où :
deb cdrom:[SFR LiveCD, based on Ubuntu 10.10]/ dists/karmic/restricted/binary-i386/
# deb cdrom:[Ubuntu 12.04.2 LTS _Precise Pangolin_ - Release amd64 (20130213)]/ dists/precise/main/binary-i386/
# deb cdrom:[Ubuntu 12.04.2 LTS _Precise Pangolin_ - Release amd64 (20130213)]/ dists/precise/restricted/binary-i386/
# deb cdrom:[Ubuntu 12.04.2 LTS _Precise Pangolin_ - Release amd64 (20130213)]/ precise 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
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://fr.archive.ubuntu.com/ubuntu/ precise-backports main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-backports main restricted universe multiverse
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
## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu precise partner
# deb-src http://archive.canonical.com/ubuntu precise partner
## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
deb http://extras.ubuntu.com/ubuntu precise main
deb-src http://extras.ubuntu.com/ubuntu precise main
deb http://archive.canonical.com/ precise partner
deb-src http://archive.canonical.com/ precise partner
"Rien ne se crée, rien ne se perd, tout se digère."
Hors ligne
Cyrille BORNE
Re : Perdu OGMRip et impossible de le réinstaller !
Comment se fait il que tu as les medibuntu, projet à l'abandon qui sort dans tes commandes et qu'il n’apparaît pas dans ton sources list ? Est ce que tu as installé du ppa en pagaille ?
peux tu faire un sudo rm /etc/apt/sources.list.d/medibuntu.list, ensuite faire un sudo apt-get update pour voir quelles sont les lignes en erreur
Hors ligne
mako
Re : Perdu OGMRip et impossible de le réinstaller !
@ Cyrille : Pour ce qui est des Médibuntu je sais pas quoi te répondre. Du ppa... je sais pas ce que c'est ni comment on en installe.
Les commandes que tu as citées donnent :
pour
sudo rm /etc/apt/sources.list.d/medibuntu.list
résultat : aucun...
pour
sudo apt-get update
résultat :
Atteint http://ppa.launchpad.net precise Release.gpg
Atteint http://ppa.launchpad.net precise Release.gpg
Atteint http://ppa.launchpad.net precise Release.gpg
Réception de : 1 http://extras.ubuntu.com precise Release.gpg [72 B]
Atteint http://fr.archive.ubuntu.com precise Release.gpg
Réception de : 2 http://fr.archive.ubuntu.com precise-security Release.gpg [198 B]
Réception de : 3 http://fr.archive.ubuntu.com precise-updates Release.gpg [198 B]
Atteint http://fr.archive.ubuntu.com precise Release
Atteint http://extras.ubuntu.com precise Release
Atteint http://ppa.launchpad.net precise Release
Atteint http://ppa.launchpad.net precise Release
Réception de : 4 http://fr.archive.ubuntu.com precise-security Release [49,6 kB]
Atteint http://ppa.launchpad.net precise Release
Atteint http://extras.ubuntu.com precise/main Sources
Atteint http://ppa.launchpad.net precise/main Sources
Atteint http://ppa.launchpad.net precise/main amd64 Packages
Atteint http://ppa.launchpad.net precise/main i386 Packages
Ign http://ppa.launchpad.net precise/main TranslationIndex
Atteint http://ppa.launchpad.net precise/main Sources
Atteint http://ppa.launchpad.net precise/main amd64 Packages
Atteint http://ppa.launchpad.net precise/main i386 Packages
Ign http://ppa.launchpad.net precise/main TranslationIndex
Atteint http://extras.ubuntu.com precise/main amd64 Packages
Atteint http://extras.ubuntu.com precise/main i386 Packages
Ign http://extras.ubuntu.com precise/main TranslationIndex
Réception de : 5 http://fr.archive.ubuntu.com precise-updates Release [49,6 kB]
Atteint http://ppa.launchpad.net precise/main Sources
Atteint http://ppa.launchpad.net precise/main amd64 Packages
Atteint http://ppa.launchpad.net precise/main i386 Packages
Ign http://ppa.launchpad.net precise/main TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/main Sources
Atteint http://fr.archive.ubuntu.com precise/restricted Sources
Atteint http://fr.archive.ubuntu.com precise/universe Sources
Atteint http://fr.archive.ubuntu.com precise/multiverse Sources
Atteint http://fr.archive.ubuntu.com precise/main amd64 Packages
Atteint http://fr.archive.ubuntu.com precise/restricted amd64 Packages
Atteint http://fr.archive.ubuntu.com precise/universe amd64 Packages
Atteint http://fr.archive.ubuntu.com precise/multiverse amd64 Packages
Atteint http://fr.archive.ubuntu.com precise/main i386 Packages
Atteint http://fr.archive.ubuntu.com precise/restricted i386 Packages
Atteint http://fr.archive.ubuntu.com precise/universe i386 Packages
Atteint http://fr.archive.ubuntu.com precise/multiverse i386 Packages
Atteint http://fr.archive.ubuntu.com precise/main TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/multiverse TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/restricted TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/universe TranslationIndex
Réception de : 6 http://fr.archive.ubuntu.com precise-security/main Sources [102 kB]
Réception de : 7 http://fr.archive.ubuntu.com precise-security/restricted Sources [2 494 B]
Réception de : 8 http://fr.archive.ubuntu.com precise-security/universe Sources [30,9 kB]
Réception de : 9 http://fr.archive.ubuntu.com precise-security/multiverse Sources [1 797 B]
Réception de : 10 http://fr.archive.ubuntu.com precise-security/main amd64 Packages [376 kB]
Ign http://ppa.launchpad.net precise/main Translation-fr_FR
Ign http://ppa.launchpad.net precise/main Translation-fr
Ign http://ppa.launchpad.net precise/main Translation-de_DE
Ign http://ppa.launchpad.net precise/main Translation-en
Réception de : 11 http://fr.archive.ubuntu.com precise-security/restricted amd64 Packages [4 627 B]
Réception de : 12 http://fr.archive.ubuntu.com precise-security/universe amd64 Packages [91,8 kB]
Ign http://ppa.launchpad.net precise/main Translation-fr_FR
Ign http://ppa.launchpad.net precise/main Translation-fr
Ign http://ppa.launchpad.net precise/main Translation-de_DE
Réception de : 13 http://fr.archive.ubuntu.com precise-security/multiverse amd64 Packages [2 439 B]
Réception de : 14 http://fr.archive.ubuntu.com precise-security/main i386 Packages [402 kB]
Ign http://ppa.launchpad.net precise/main Translation-en
Ign http://ppa.launchpad.net precise/main Translation-fr_FR
Ign http://ppa.launchpad.net precise/main Translation-fr
Ign http://ppa.launchpad.net precise/main Translation-de_DE
Ign http://ppa.launchpad.net precise/main Translation-en
Ign http://extras.ubuntu.com precise/main Translation-fr_FR
Ign http://extras.ubuntu.com precise/main Translation-fr
Ign http://extras.ubuntu.com precise/main Translation-de_DE
Réception de : 15 http://fr.archive.ubuntu.com precise-security/restricted i386 Packages [4 620 B]
Réception de : 16 http://fr.archive.ubuntu.com precise-security/universe i386 Packages [96,5 kB]
Réception de : 17 http://fr.archive.ubuntu.com precise-security/multiverse i386 Packages [2 649 B]
Réception de : 18 http://fr.archive.ubuntu.com precise-security/main TranslationIndex [74 B]
Ign http://extras.ubuntu.com precise/main Translation-en
Réception de : 19 http://fr.archive.ubuntu.com precise-security/multiverse TranslationIndex [72 B]
Réception de : 20 http://fr.archive.ubuntu.com precise-security/restricted TranslationIndex [72 B]
Réception de : 21 http://fr.archive.ubuntu.com precise-security/universe TranslationIndex [73 B]
Réception de : 22 http://fr.archive.ubuntu.com precise-updates/main Sources [454 kB]
Réception de : 23 http://fr.archive.ubuntu.com precise-updates/restricted Sources [8 028 B]
Réception de : 24 http://fr.archive.ubuntu.com precise-updates/universe Sources [106 kB]
Réception de : 25 http://fr.archive.ubuntu.com precise-updates/multiverse Sources [8 909 B]
Réception de : 26 http://fr.archive.ubuntu.com precise-updates/main amd64 Packages [764 kB]
Réception de : 27 http://fr.archive.ubuntu.com precise-updates/restricted amd64 Packages [12,2 kB]
Réception de : 28 http://fr.archive.ubuntu.com precise-updates/universe amd64 Packages [239 kB]
Réception de : 29 http://fr.archive.ubuntu.com precise-updates/multiverse amd64 Packages [15,3 kB]
Réception de : 30 http://fr.archive.ubuntu.com precise-updates/main i386 Packages [788 kB]
Réception de : 31 http://fr.archive.ubuntu.com precise-updates/restricted i386 Packages [12,2 kB]
Réception de : 32 http://fr.archive.ubuntu.com precise-updates/universe i386 Packages [244 kB]
Réception de : 33 http://fr.archive.ubuntu.com precise-updates/multiverse i386 Packages [15,4 kB]
Réception de : 34 http://fr.archive.ubuntu.com precise-updates/main TranslationIndex [3 564 B]
Réception de : 35 http://fr.archive.ubuntu.com precise-updates/multiverse TranslationIndex [2 605 B]
Réception de : 36 http://fr.archive.ubuntu.com precise-updates/restricted TranslationIndex [2 461 B]
Réception de : 37 http://fr.archive.ubuntu.com precise-updates/universe TranslationIndex [2 850 B]
Atteint http://fr.archive.ubuntu.com precise/main Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/main Translation-fr
Atteint http://fr.archive.ubuntu.com precise/main Translation-en
Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-fr
Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com precise/restricted Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/restricted Translation-fr
Atteint http://fr.archive.ubuntu.com precise/restricted Translation-en
Atteint http://fr.archive.ubuntu.com precise/universe Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/universe Translation-fr
Atteint http://fr.archive.ubuntu.com precise/universe Translation-en
Atteint http://fr.archive.ubuntu.com precise-security/main Translation-en
Atteint http://fr.archive.ubuntu.com precise-security/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com precise-security/restricted Translation-en
Atteint http://fr.archive.ubuntu.com precise-security/universe Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/main Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/main Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/restricted Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/restricted Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/universe Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/universe Translation-en
3 896 ko réceptionnés en 2s (1 506 ko/s)
Lecture des listes de paquets... Fait
"Rien ne se crée, rien ne se perd, tout se digère."
Hors ligne
mako
Re : Perdu OGMRip et impossible de le réinstaller !
J'ai refait
sudo rm /etc/apt/sources.list.d/medibuntu.list
et j'obtiens :
rm: impossible de supprimer «/etc/apt/sources.list.d/medibuntu.list»: Aucun fichier ou dossier de ce type
"Rien ne se crée, rien ne se perd, tout se digère."
Hors ligne
Machtheld
Re : Perdu OGMRip et impossible de le réinstaller !
Explication de texte (voir aussi mon message #7, un peu succinct je l'avoue):
Tu n'arrives pas à installer tes logiciels, parce qu'il y a un problème dans le fichier qui recense les sources de logiciels (les dépôts).
Je te proposais de recréer un nouveau ficher "sources de logiciels", mais Cyril t'a proposé beaucoup plus simple, de virer le dépôt qui pose problème (sudo rm=effacer qc).
Ensuite, il faut dire à la machine que le fichier "sources de logiciels" a été modifié (sudo apt-get update=recharger la liste)
Enfin, tu peux installer tes logiciels.
Les commandes que tu as citées donnent :
pour<metadata lang=Shell prob=0.07 />
sudo rm /etc/apt/sources.list.d/medibuntu.list
résultat : aucun...
Normal. Le fichier a été effacé.
pour
sudo apt-get update
résultat :
Atteint http://ppa.launchpad.net precise Release.gpg
Atteint http://ppa.launchpad.net precise Release.gpg
Atteint http://ppa.launchpad.net precise Release.gpg
Réception de : 1 http://extras.ubuntu.com precise Release.gpg [72 B]
Atteint http://fr.archive.ubuntu.com precise Release.gpg
Réception de : 2 http://fr.archive.ubuntu.com precise-security Release.gpg [198 B]
Réception de : 3 http://fr.archive.ubuntu.com precise-updates Release.gpg [198 B]
Atteint http://fr.archive.ubuntu.com precise Release
Atteint http://extras.ubuntu.com precise Release
Atteint http://ppa.launchpad.net precise Release
Atteint http://ppa.launchpad.net precise Release
Réception de : 4 http://fr.archive.ubuntu.com precise-security Release [49,6 kB]
Atteint http://ppa.launchpad.net precise Release
Atteint http://extras.ubuntu.com precise/main Sources
Atteint http://ppa.launchpad.net precise/main Sources
Atteint http://ppa.launchpad.net precise/main amd64 Packages
Atteint http://ppa.launchpad.net precise/main i386 Packages
Ign http://ppa.launchpad.net precise/main TranslationIndex
Atteint http://ppa.launchpad.net precise/main Sources
Atteint http://ppa.launchpad.net precise/main amd64 Packages
Atteint http://ppa.launchpad.net precise/main i386 Packages
Ign http://ppa.launchpad.net precise/main TranslationIndex
Atteint http://extras.ubuntu.com precise/main amd64 Packages
Atteint http://extras.ubuntu.com precise/main i386 Packages
Ign http://extras.ubuntu.com precise/main TranslationIndex
Réception de : 5 http://fr.archive.ubuntu.com precise-updates Release [49,6 kB]
Atteint http://ppa.launchpad.net precise/main Sources
Atteint http://ppa.launchpad.net precise/main amd64 Packages
Atteint http://ppa.launchpad.net precise/main i386 Packages
Ign http://ppa.launchpad.net precise/main TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/main Sources
Atteint http://fr.archive.ubuntu.com precise/restricted Sources
Atteint http://fr.archive.ubuntu.com precise/universe Sources
Atteint http://fr.archive.ubuntu.com precise/multiverse Sources
Atteint http://fr.archive.ubuntu.com precise/main amd64 Packages
Atteint http://fr.archive.ubuntu.com precise/restricted amd64 Packages
Atteint http://fr.archive.ubuntu.com precise/universe amd64 Packages
Atteint http://fr.archive.ubuntu.com precise/multiverse amd64 Packages
Atteint http://fr.archive.ubuntu.com precise/main i386 Packages
Atteint http://fr.archive.ubuntu.com precise/restricted i386 Packages
Atteint http://fr.archive.ubuntu.com precise/universe i386 Packages
Atteint http://fr.archive.ubuntu.com precise/multiverse i386 Packages
Atteint http://fr.archive.ubuntu.com precise/main TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/multiverse TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/restricted TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/universe TranslationIndex
Réception de : 6 http://fr.archive.ubuntu.com precise-security/main Sources [102 kB]
Réception de : 7 http://fr.archive.ubuntu.com precise-security/restricted Sources [2 494 B]
Réception de : 8 http://fr.archive.ubuntu.com precise-security/universe Sources [30,9 kB]
Réception de : 9 http://fr.archive.ubuntu.com precise-security/multiverse Sources [1 797 B]
Réception de : 10 http://fr.archive.ubuntu.com precise-security/main amd64 Packages [376 kB]
Ign http://ppa.launchpad.net precise/main Translation-fr_FR
Ign http://ppa.launchpad.net precise/main Translation-fr
Ign http://ppa.launchpad.net precise/main Translation-de_DE
Ign http://ppa.launchpad.net precise/main Translation-en
Réception de : 11 http://fr.archive.ubuntu.com precise-security/restricted amd64 Packages [4 627 B]
Réception de : 12 http://fr.archive.ubuntu.com precise-security/universe amd64 Packages [91,8 kB]
Ign http://ppa.launchpad.net precise/main Translation-fr_FR
Ign http://ppa.launchpad.net precise/main Translation-fr
Ign http://ppa.launchpad.net precise/main Translation-de_DE
Réception de : 13 http://fr.archive.ubuntu.com precise-security/multiverse amd64 Packages [2 439 B]
Réception de : 14 http://fr.archive.ubuntu.com precise-security/main i386 Packages [402 kB]
Ign http://ppa.launchpad.net precise/main Translation-en
Ign http://ppa.launchpad.net precise/main Translation-fr_FR
Ign http://ppa.launchpad.net precise/main Translation-fr
Ign http://ppa.launchpad.net precise/main Translation-de_DE
Ign http://ppa.launchpad.net precise/main Translation-en
Ign http://extras.ubuntu.com precise/main Translation-fr_FR
Ign http://extras.ubuntu.com precise/main Translation-fr
Ign http://extras.ubuntu.com precise/main Translation-de_DE
Réception de : 15 http://fr.archive.ubuntu.com precise-security/restricted i386 Packages [4 620 B]
Réception de : 16 http://fr.archive.ubuntu.com precise-security/universe i386 Packages [96,5 kB]
Réception de : 17 http://fr.archive.ubuntu.com precise-security/multiverse i386 Packages [2 649 B]
Réception de : 18 http://fr.archive.ubuntu.com precise-security/main TranslationIndex [74 B]
Ign http://extras.ubuntu.com precise/main Translation-en
Réception de : 19 http://fr.archive.ubuntu.com precise-security/multiverse TranslationIndex [72 B]
Réception de : 20 http://fr.archive.ubuntu.com precise-security/restricted TranslationIndex [72 B]
Réception de : 21 http://fr.archive.ubuntu.com precise-security/universe TranslationIndex [73 B]
Réception de : 22 http://fr.archive.ubuntu.com precise-updates/main Sources [454 kB]
Réception de : 23 http://fr.archive.ubuntu.com precise-updates/restricted Sources [8 028 B]
Réception de : 24 http://fr.archive.ubuntu.com precise-updates/universe Sources [106 kB]
Réception de : 25 http://fr.archive.ubuntu.com precise-updates/multiverse Sources [8 909 B]
Réception de : 26 http://fr.archive.ubuntu.com precise-updates/main amd64 Packages [764 kB]
Réception de : 27 http://fr.archive.ubuntu.com precise-updates/restricted amd64 Packages [12,2 kB]
Réception de : 28 http://fr.archive.ubuntu.com precise-updates/universe amd64 Packages [239 kB]
Réception de : 29 http://fr.archive.ubuntu.com precise-updates/multiverse amd64 Packages [15,3 kB]
Réception de : 30 http://fr.archive.ubuntu.com precise-updates/main i386 Packages [788 kB]
Réception de : 31 http://fr.archive.ubuntu.com precise-updates/restricted i386 Packages [12,2 kB]
Réception de : 32 http://fr.archive.ubuntu.com precise-updates/universe i386 Packages [244 kB]
Réception de : 33 http://fr.archive.ubuntu.com precise-updates/multiverse i386 Packages [15,4 kB]
Réception de : 34 http://fr.archive.ubuntu.com precise-updates/main TranslationIndex [3 564 B]
Réception de : 35 http://fr.archive.ubuntu.com precise-updates/multiverse TranslationIndex [2 605 B]
Réception de : 36 http://fr.archive.ubuntu.com precise-updates/restricted TranslationIndex [2 461 B]
Réception de : 37 http://fr.archive.ubuntu.com precise-updates/universe TranslationIndex [2 850 B]
Atteint http://fr.archive.ubuntu.com precise/main Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/main Translation-fr
Atteint http://fr.archive.ubuntu.com precise/main Translation-en
Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-fr
Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com precise/restricted Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/restricted Translation-fr
Atteint http://fr.archive.ubuntu.com precise/restricted Translation-en
Atteint http://fr.archive.ubuntu.com precise/universe Translation-fr_FR
Atteint http://fr.archive.ubuntu.com precise/universe Translation-fr
Atteint http://fr.archive.ubuntu.com precise/universe Translation-en
Atteint http://fr.archive.ubuntu.com precise-security/main Translation-en
Atteint http://fr.archive.ubuntu.com precise-security/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com precise-security/restricted Translation-en
Atteint http://fr.archive.ubuntu.com precise-security/universe Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/main Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/main Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/restricted Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/restricted Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/universe Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/universe Translation-en
3 896 ko réceptionnés en 2s (1 506 ko/s)
Lecture des listes de paquets... Fait
Pas de message d'erreur. Donc tout va bien.
Tu peux réinstaller OGMRip...et dire merci à Cyril
Hors ligne |
Any idea what I am doing wrong here? There are no error messages and the script runs fine, but no record is inserted into the db. Running the insert query on the database works fine.
Even if i put in a bogus IP or password no error is generated.
This is on windows with python 2.7 and the mysqldb 2.7 windows binaries.
import os, sys, time, glob, shlex, subprocess, MySQLdb
try:
db=MySQLdb.connect(host="my.sql.server.ip.here",user="encoding",passwd="passhere",db="encoding")
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit (1)
c=db.cursor()
c.execute("""INSERT INTO test (jobid, frame) VALUES (%s, %s)""",("asdf", "s[1]" ) )
c.close ()
db.close ()
|
raspouillas
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Je ne faisait aucune allusion au problème de @souen.
Dernière modification par raspouillas (Le 15/06/2012, à 20:37)
ljere
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
alors voici la première partie du script et la j'ai besoin d'aide car je ne suis sure de rien
]#!/usr/bin/python
# encoding: utf-8
from BeautifulSoup import BeautifulSoup
import urllib2
import re
import time
import sys
import mechanize# est ce que je peux mette ces 3 lignes sur 1 seul?
ignoreList = (
'compteur des leve tot',
)# pourquoi on utilise """ au lieu d'un simple "en début et fin et ne peut on simplifié la phrase?
class Day:
"""un jours dure de 5h à 9h du matin exclu ([5h:9h[) il contient la dernière entrée (points) de ce jour pour chaque joueurs"""
def __init__(self):
self.entries={}
def __str__(self):
for entry in self.entries.items():
print entry,'+',entries[entry]# c'est normal que ce def n'est pas aligné aux autres?def utcFrance():
return 1 + time.localtime(time.time())[-1] #1 + 1 si on est a l'heure d'été
# ici je crois qu'on doit modifier en def __init__(self,tuple=(5,9),utc=utcFrance()):class Date:
def __init__(self,tuple=(20,0),utc=utcFrance()):
self.h = (int(tuple[0])-utcFrance()+24+utc)%24
self.m = int(tuple[1])
def __cmp__(self, other):
return cmp(self.points(),other.points())
def points(self):
pts = {5: 10, 6: 6, 7: 3, 8: 1}
return pts.get(self.h, 0)
si vous avez les réponses ou d'autres suggestions je vous écoute
merci
Hors ligne
Pylades
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
# est ce que je peux mette ces 3 lignes sur 1 seul?
Oui, mais c’est mieux sur trois lignes.
# pourquoi on utilise """ au lieu d'un simple "en début et fin et ne peut on simplifié la phrase?
Pour pouvoir écrire cette docstring sur plusieurs lignes si besoin. On peut reformuler sans impacter le fonctionnement du programme.
# c'est normal que ce def n'est pas aligné aux autres?
Oui, faut pas toucher.
# ici je crois qu'on doit modifier en def __init__(self,tuple=(5,9),utc=utcFrance()):
Possible, mais c’est probablement plus compliqué… ce compteur est presque immaintenable.
Mais bon, dans un futur plus ou moins proche, on va refaire un compteur propre pour le TdCT. Du coup, il s’adaptera ici en un clin d’œil.
Dernière modification par Πυλάδης (Le 15/06/2012, à 18:49)
“Any if-statement is a goto. As are all structured loops.
“And sometimes structure is good. When it’s good, you should use it.
“And sometimes structure is _bad_, and gets into the way, and using a goto is just much clearer.”
Linus Torvalds – 12 janvier 2003
En ligne
ljere
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Mais bon, dans un futur plus ou moins proche, on va refaire un compteur propre pour le TdCT. Du coup, il s’adaptera ici en un clin d’œil.
c'est marrant nesthib m'a dit la même chose mais quand personne le sais ....
donc en attendant si on veut bien continuer à m'aider j’apprends le python et j'arriverai peut être à avoir un compteur viable en attendant un compteur plus maintenable et en phase avec python 2.7.3 alors que le script de tshirtman est prévu pour du python 2.6.*
/me est donc décidé à persévérer
Hors ligne
ljere
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
peux t'on me dire que fait (veut dire) cette partie
if (
(str_date.split(' ')[0] in ['Hier']
and int(str_date.split(' ')[2].split('<')[0].split(':')[0]) in range(5,24))
or (str_date.split(' ')[0] in ["Aujourd\'hui"]
and int(str_date.split(' ')[2].split('<')[0].split(':')[0]) in range(5))
):
Hors ligne
Floyd Pepper
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
[
/me est donc décidé à persévérer
/me t'encourage vivement, et j'espère que le truc grec t'a donné de vrais conseils hors forum, cause que vu d'ici, cette intervention est aussi péremptoire qu'inutile.
Perso, je ne peux que te soutenir et te souhaiter de nous faire "the compteur des Lts" qui sera adapté au Cts.
Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys.
Le plus tu t'fais chier, le plus t'es emmerdé.
Hors ligne
ljere
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
répondu golgoth42
Floyd Pepper merci pour les encouragements, par contre continu de poster le tien j'en ai besoin pour mes test
Hors ligne
Floyd Pepper
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
'jour
Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys.
Le plus tu t'fais chier, le plus t'es emmerdé.
Hors ligne
ljere
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
bonjour tout le monde
Hors ligne
souen
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Hello bonjour
Tu es programmé, mais tu es libre.
Ubuntu Studio
"Si il n'y a pas de solution, c'est qu'il n'y a pas problème !"
(sagesse Shadok)
Hors ligne
PPdM
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Salutatous par Toutatis!
Un vrai ennemi ne te laissera jamais tomber.
En ligne
raspouillas
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
bonjour ....
raspouillas
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
PS: Je n'ai de retour de réponse ?
Mindiell
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
... bonjour !
Une seconde, on est samedi
@ljere:
spli permet de séparer une chaine en n morceaux séparés par le caractère donné. En prenant la date affichée : Hier à 21:19 ou Aujourd'hui à 08:56
on obtient alors un tableau du type [0] => "Hier", [1] => "à", [2] => "21:19"
Ensuite le triple split, resplite la chaine et utilise le 3eme élément pour tenter d'en extraire l'heure. le split avec '<' est inutile dans ce cas, il a du être rajouté à une époque lointaine (ancien forum ?). On obtient donc un seul élément égal au 3eme élément déjà pris en compte ("21:19"), puis on split par le ":" pour obtenir l'heure et on s'intéresse aux heures comprises entre 5 et 24.
Le deuxième partie s'intéresse aux heures entre 0 et 5.
Au final, tu obtiens donc les informations pour les dernières 24 heures, et on peut, dès lors, supposer que le compteur se lance tous les jours à 5h00 du matin
PS: j'ai pas répondu en mp : c'était déjà fait, et puis ça peut en intéresser d'autres
Hors ligne
ljere
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
donc comme pour nous on s’intéresse à une période de 6h à 9h
if (
(str_date.split(' ')[0] in ["Aujourd\'hui"]
and int(str_date.split(' ')[2].split(':')[6]) in range(8))
):
comme 9h est exclu je doit bien mettre 8?
Hors ligne
Floyd Pepper
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
1 1787 FloydPepper
2 1543 pierguiard
3 1463 MdMax
4 1247 Azurea
5 1199 souen
6 968 Ras'
7 767 raspouillas
8 552 Arcans
9 428 peterp@n
10 359 golgoth42
11 293 mindiell
12 277 omc
13 219 Πυλάδης
14 176 pololasi
15 117 edge_one
16 101 nathéo
17 99 karameloneboudeplus
18 61 agarwood
19 60 Niltugor
20 52 1101011
20 52 jeyenkil
20 52 ljere
23 43 Crocoii
24 42 nakraïou
24 42 DaveNull
26 40 Biaise
27 39 Clem_ufo
28 38 Atem18
29 22 marinmarais
30 18 Ju
31 13 Le grand rohr sha
32 10 Phoenix
32 10 FLOZz
32 10 sakul
32 10 SopolesRâ
36 6 wiscot
36 6 timsy
36 6 Slystone
36 6 Hibou57
36 6 tshirtman
36 6 marting
36 6 c4nuser
43 4 Morgiver
43 4 :!pakman
45 3 Phoenamandre
45 3 gonzolero
45 3 helly
45 3 Le Rouge
49 1 herewegoagain
49 1 TheUploader
49 1 Kyansaa
49 1 Xiti29
Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys.
Le plus tu t'fais chier, le plus t'es emmerdé.
Hors ligne
Ras'
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
J'me réveille -__________-'
C'est trop tard pour les points ?
Va t'faire shampouiner en GMT-4 !
http://blag.xserver-x.org/
Les types awesome n'ont rien à prouver. À personne.
Hors ligne
PPdM
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
J'me réveille -__________-'
C'est trop tard pour les points ?
nan tu es en avance pour demain!
En ligne
Ras'
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Va détourer ton avatar au lieu de te moquer !
Va t'faire shampouiner en GMT-4 !
http://blag.xserver-x.org/
Les types awesome n'ont rien à prouver. À personne.
Hors ligne
Mindiell
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
donc comme pour nous on s’intéresse à une période de 6h à 9h
if (
(str_date.split(' ')[0] in ["Aujourd\'hui"]
and int(str_date.split(' ')[2].split(':')[6]) in range(8))
):
comme 9h est exclu je doit bien mettre 8?
En fait j'aurai plutôt mis ça :
if (
(str_date.split(' ')[0] in ["Aujourd\'hui"]
and int(str_date.split(' ')[2].split(':')[0]) in range(5,8))
):
Car :
- je ne sais pas pourquoi tu mets 6 au lieu de 0 dans le tableau : quand tu coupes 05:34 en chaines par rapport à ":", tu obtiens un tableau de deux éléments : "0" => "05", "1" => "34"
- Il faut s'occuper uniquement de 5 à 8 heures
Voilà
PS: Ah oui, ça à l'air facile python ou pas ?
Hors ligne
raspouillas
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Bonjour ...
ljere
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
bonjour ...
Hors ligne
ljere
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
@Mindiell ce n'est pas facile mais c'est intéressant encore merci pour tes conseils et explications
Hors ligne
Floyd Pepper
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
'jour
Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys.
Le plus tu t'fais chier, le plus t'es emmerdé.
Hors ligne |
I'm using Python (minidom) to parse an XML file that prints a hierarchical structure that looks something like this (indentation is used here to show the significant hierarchical relationship):
My DocumentOverview Basic Features About This Software Platforms Supported
Instead, the program iterates multiple times over the nodes and produces the following, printing duplicate nodes. (Looking at the node list at each iteration, it's obvious why it does this but I can't seem to find a way to get the node list I'm looking for.)
My DocumentOverviewBasic FeaturesAbout This SoftwarePlatforms SupportedBasic FeaturesAbout This SoftwarePlatforms SupportedPlatforms Supported
Here is the XML source file:
<?xml version="1.0" encoding="UTF-8"?>
<DOCMAP>
<Topic Target="ALL">
<Title>My Document</Title>
</Topic>
<Topic Target="ALL">
<Title>Overview</Title>
<Topic Target="ALL">
<Title>Basic Features</Title>
</Topic>
<Topic Target="ALL">
<Title>About This Software</Title>
<Topic Target="ALL">
<Title>Platforms Supported</Title>
</Topic>
</Topic>
</Topic>
</DOCMAP>
Here is the Python program:
import xml.dom.minidom
from xml.dom.minidom import Node
dom = xml.dom.minidom.parse("test.xml")
Topic=dom.getElementsByTagName('Topic')
i = 0
for node in Topic:
alist=node.getElementsByTagName('Title')
for a in alist:
Title= a.firstChild.data
print Title
I could fix the problem by not nesting 'Topic' elements, by changing the lower level topic names to something like 'SubTopic1' and 'SubTopic2'. But, I want to take advantage of built-in XML hierarchical structuring without needing different element names; it seems that I should be able to nest 'Topic' elements and that there should be some way to know which level 'Topic' I'm currently looking at.
I've tried a number of different XPath functions without much success. |
I have a Python list which holds pairs of key/value:
l=[ [1, 'A'], [1, 'B'], [2, 'C'] ]
I want to convert the list into a dictionary, where multiple values per key would be aggregated into a tuple:
{ 1:('A', 'B'), 2:('C',) }
The iterative solution is trivial:
l=[ [1, 'A'], [1, 'B'], [2, 'C'] ]
d={}
for pair in l:
if d.has_key(pair[0]):
d[pair[0]]=d[pair[0]]+tuple(pair[1])
else:
d[pair[0]]=tuple(pair[1])
print d
{1: ('A', 'B'), 2: ('C',)}
Is there a more elegant, Pythonic solution for this task? |
please this error appears when the user clicks on print button , on my PC the error dosen't appear , only on some pc's ! what is the problem ?
before ,this error did not appear,only now !
my code in vb.net crystal reports for vs2010 report's datasource on local server
edited : This is my code (report load button) :
Dim mov As New leavingReport
Dim rep As New rep
LogOn(mov, DataBasePath, DataBasePath, "Admin", "")
rep.CrystalReportViewer1.ReportSource = mov
mov.Refresh()
rep.ShowDialog()
mov.Dispose()
rep.Dispose()
Thank You |
How do you register a function with all the correct handlers etc to be called when the Python script is exitted (successfully or not)?
I have tried:
@atexit.register
def finalise():
'''
Function handles program close
'''
print("Tidying up...")
...
print("Closing")
...but this does not get called when the user closes the command prompt window for example (because @atexit.register decorated functions do not get called when the exitcode is non zero)
I am looking for a way of guaranteeing finalise() is called on program exit, regardless of errors.
For context, my Python program is a continually looping service program that aims to run all the time.
Thanks in advance |
Running GUI Applications
Tkinter applications are normal Python scripts, but there are a couple of complications worth knowing about when running graphical applications under Windows. These were discussed in Chapter 3, Python on Windows, but are important enough to reiterate here; what we say in this section applies equally to wxPython later in this chapter.
The standard Python.exe that comes with Python is known as a console application (this means it has been built to interact with a Windows console, otherwise known as a DOS box or command prompt). Although you can execute your Tkinter programs using Python.exe, your program will always be associated with a Windows console. It works just fine, but has the following side effects:
If you execute Python.exefrom Windows Explorer, a new empty console window is created; then the Tkinter windows are created.
If you execute a Tkinter application under Python.exefrom a command prompt, the command prompt doesn't return until the Tkinter application has finished. This will be a surprise for many users, who expect that executing a GUI program returns the command prompt immediately.
To get around this problem, Python comes with a special GUI version called Pythonw.exe. This is almost identical to the standard Python.exe, except it's not a console program, so doesn't suffer the problems described previously.
There are two drawbacks to this approach. The first is that .py files are automatically associated with Python.exe. As we saw in Chapter 3, this makes it simple to execute Python programs, but does present a problem when you want to use Pythonw.exe. To solve this problem, Python automatically associates the .pyw extension with Pythonw.exe ; thus, you can give GUI Python applications a .pyw extension, and automatically execute them from Windows Explorer, the command prompt, and so forth.
The second drawback is that because Pythonw.exe has no console, any tracebacks printed by Python aren't typically seen. Although Python prints the traceback normally, the lack of a console means it has nowhere useful to go. To get around this problem, you may like to develop your application using Python.exe (where the console is an advantage for debugging) but run the final version using Pythonw.exe.
"Hello World"
The easiest way to get a feel for Tkinter is with the ever popular "Hello World!" example. The result of this little program is shown in Figure 20-1.
from sys import exit
from Tkinter import *
root = Tk()
Button(root, text='Hello World!', command=exit).pack()
root.mainloop()
As you can see, apart from the import statements, there are only three lines of interest. The root variable is set to the default top-level window automatically created by Tk, although applications with advanced requirements can customize the top-level frames. The code then creates a Tkinter button object, specifying the parent (the root variable), the text for the button, and the command to execute when clicked. We discuss the pack() method later in this section. Finally, turn control over to the main event-processing loop, which creates the Windows on the screen and dispatches user-interface events.
The other end of the World
From the extreme simplicity of the "Hello World" example, the other end of the scale could be considered the tkDemo sample included with this chapter. Although space considerations prevent us from examining this sample in detail, Figure 20-2 should give you an indication of the capabilities offered by Tkinter. |
If you review the sidebar "wxPython Window Layout," you'll see a number of choices available, but we have chosen to use the brute-force mechanism for the Edit Transaction dialog:
# Create some controls
wxStaticText(self, -1, "Date:", wxDLG_PNT(self, 5,5))
self.date = wxTextCtrl(self, ID_DATE, "",
wxDLG_PNT(self, 35,5), wxDLG_SZE(self, 50,-1))
wxStaticText(self, -1, "Comment:", wxDLG_PNT(self, 5,21))
self.comment = wxTextCtrl(self, ID_COMMENT, "",
wxDLG_PNT(self, 35, 21), wxDLG_SZE(self, 195,-1)
The code shows how to create the labels and the text fields at the top of the dialog. Notice the use of wxDLG_PNT and wxDLG_SZE to convert dialog units to a wxPoint and a wxSize, respectively. (The -1's used above mean that the default size should be used for the height.) Using dialog units instead of pixels to define the dialog means you are somewhat insulated from changes in the font used for the dialog, so you use dialog units wherever possible. The wxPoint and wxSize are always defined in terms of pixels, but these conversion functions allow the actual number of pixels used to vary automatically from machine to machine with different fonts. This makes it easy to move programs between platforms that have completely different window managers. Figure 20-13 shows this same program running on RedHat Linux 6.0, and you can see that for the most part, the controls are still spaced appropriately even though a completely different font is used on the form. It looks like the wxTextCtrl is a few dialog units taller on this platform, so perhaps there should be a bit more space between the rows. We leave this as an exercise for you.
The next control to be defined is the wxListCtrl that displays the account and amount lines:
self.lc = wxListCtrl(self, ID_LIST,
wxDLG_PNT(self, 5,34), wxDLG_SZE(self, 225,60),
wxLC_REPORT)
self.lc.InsertColumn(0, "Account")
self.lc.InsertColumn(1, "Amount")
self.lc.SetColumnWidth(0, wxDLG_SZE(self, 180,-1).width)
self.lc.SetColumnWidth(1, wxDLG_SZE(self, 40,-1).width)
It's important to note that the width of this control is 225 dialog units. Since this control spans the entire width of the dialog, you know the space you have to work with. You can use this value when deciding where to place or how to size the other controls.
Instead of auto-sizing the width of the list columns, let's now use explicit sizes. But you can still use dialog units to do it by extracting the width attribute from the wxSize object returned from wxDLG_SZE. We should mention the following points:
The balance field is disabled, as you only want to use it to display a value.
Use a wxStaticLinecontrol for drawing the line across the dialog.
A wxComboBoxis used for selecting existing account names from a list.
Use the standard IDs wxID_OKandwxID_CANCELfor OK and Cancel buttons, respectively, and force the OK button as the default button.
Call the base class Fit()method to determine the initial size of the dialog window. This function calculates the total required size based on the size information specified in each of the children.
Here's the rest of the code for creating the controls:
wxStaticText(self, -1, "Balance:", wxDLG_PNT(self, 165,100))
self.balance = wxTextCtrl(self, ID_BAL, "",
wxDLG_PNT(self, 190,100),
wxDLG_SZE(self, 40, -1))
self.balance.Enable(false)
wxStaticLine(self, -1, wxDLG_PNT(self, 5,115),
wxDLG_SZE(self, 225,-1))
wxStaticText(self, -1, "Account:", wxDLG_PNT(self, 5,122))
self.account = wxComboBox(self, ID_ACCT, "",
wxDLG_PNT(self, 30,122), wxDLG_SZE(self, 130,-1),
accountList, wxCB_DROPDOWN | wxCB_SORT)
wxStaticText(self, -1, "Amount:", wxDLG_PNT(self, 165,122))
self.amount = wxTextCtrl(self, ID_AMT, "",
wxDLG_PNT(self, 190,122),
wxDLG_SZE(self, 40, -1))
btnSz = wxDLG_SZE(self, 40,12)
wxButton(self, ID_ADD, "&Add Line", wxDLG_PNT(self, 52,140), btnSz)
wxButton(self, ID_UPDT, "&Update Line", wxDLG_PNT(self, 97,140),
btnSz)
wxButton(self, ID_DEL, "&Delete Line", wxDLG_PNT(self, 142,140),
btnSz)
self.ok = wxButton(self, wxID_OK, "OK", wxDLG_PNT(self, 145,5),
btnSz)
self.ok.SetDefault()
wxButton(self, wxID_CANCEL, "Cancel", wxDLG_PNT(self, 190,5), btnSz)
# Resize the window to fit the controls
self.Fit()
The last thing to do is set up some event handlers and load the dialog controls with data. The event handling for the controls is almost identical to the menu handling discussed previously, so there shouldn't be any surprises:
# Set some event handlers
EVT_BUTTON(self, ID_ADD, self.OnAddBtn)
EVT_BUTTON(self, ID_UPDT, self.OnUpdtBtn)
EVT_BUTTON(self, ID_DEL, self.OnDelBtn)
EVT_LIST_ITEM_SELECTED(self, ID_LIST, self.OnListSelect)
EVT_LIST_ITEM_DESELECTED(self, ID_LIST, self.OnListDeselect)
EVT_TEXT(self, ID_DATE, self.Validate)
# Initialize the controls with current values
self.date.SetValue(self.trans.getDateString())
self.comment.SetValue(self.trans.comment)
for x in range(len(self.trans.lines)):
account, amount, dict = self.trans.lines[x]
self.lc.InsertStringItem(x, account)
self.lc.SetStringItem(x, 1, str(amount))
self.Validate()
The last thing the code snippet does is call a Validate() method, which as you can probably guess, is responsible for validating the dialog data; in this case, validating the date and that all transaction lines sum to zero. Check the date when the field is updated (via the EVT_TEXT() call shown in the code) and check the balance any time a line is added or updated. If anything doesn't stack up, disable the OK button. Here is Validate:
def Validate(self, *ignore):
bal = self.trans.balance()
self.balance.SetValue(str(bal))
date = self.date.GetValue()
try:
dateOK = (date == dates.testasc(date))
except:
dateOK = 0
if bal == 0 and dateOK:
self.ok.Enable(true)
else:
self.ok.Enable(false)
Notice that the balance field is updated. The next thing we demonstrate is the Add Line functionality. To do this, you need to take whatever is in the account and amount fields, add them to the transaction, and also add them to the list control:
def OnAddBtn(self, event):
account = self.account.GetValue()
amount = string.atof(self.amount.GetValue())
self.trans.addLine(account, amount)
# update the list control
idx = len(self.trans.lines)
self.lc.InsertStringItem(idx-1, account)
self.lc.SetStringItem(idx-1, 1, str(amount))
self.Validate()
self.account.SetValue("")
self.amount.SetValue("")
You call Validate again to check if the transaction's lines are in balance. The event handlers for the Update and Delete buttons are similar and not shown here.
That's about all there is to it! wxPython takes care of the tab-traversal between fields, auto-completion on the Enter key, auto-cancel on Esc, and all the rest.
wxPython Conclusion
This small section has barely touched the surface of what wxPython is capable of. There are many more window and control types than what have been shown here, and the advanced features lend themselves to highly flexible and dynamic GUI applications across many platforms. Combined with the flexibility of Python, you end up with a powerful tool for quickly creating world-class applications.
For more information on wxPython, including extensive documentation and sample code, see the wxPython home page at http://alldunn.com/wxPython/.
For more information on the underlying wxWindows framework, please visit its home page at http://www.wxwindows.org/.
Return to Python DevCenter. |
You can get the string you want (apparently implying a big-endian, 32-bit representation; Python internally uses the native endianity and 64-bits for floats) with the struct module:
>>> import struct
>>> x = 173.125
>>> s = struct.pack('>f', x)
>>> ''.join('%2.2x' % ord(c) for c in s)
'432d2000'
this doesn't yet let you perform bitwise operations, but you can then use struct again to map the string into an int:
>>> i = struct.unpack('>l', s)[0]
>>> print hex(i)
0x432d2000
and now you have an int which you can use in any sort of bitwise operations (follow the same two steps in reverse if after said operations you need to get a float again). |
While there are ways to handle authentication in urllib2, if you're doing Basic Authorization (which means effectively sending the username and password in clear text) then you can do all of what you want with a urllib2.Request and urllib2.urlopen:
import urllib2
def basic_authorization(user, password):
s = user + ":" + password
return "Basic " + s.encode("base64").rstrip()
req = urllib2.Request("http://localhost:8000/36576/speak.json",
headers = {
"Authorization": basic_authorization("7898678", "X"),
"Content-Type": "application/json",
# Some extra headers for fun
"Accept": "*/*", # curl does this
"User-Agent": "my-python-app/1", # otherwise it uses "Python-urllib/..."
},
data = '{"message":{"body":"TEXT"}}')
f = urllib2.urlopen(req)
I tested this with netcat so I could see that the data sent was, excepting sort order, identical in both cases. Here the first one was done with curl and the second with urllib2
% nc -l 8000
POST /36576/speak.json HTTP/1.1
Authorization: Basic Nzg5ODY3ODpY
User-Agent: curl/7.19.4 (universal-apple-darwin10.0) libcurl/7.19.4 OpenSSL/0.9.8k zlib/1.2.3
Host: localhost:8000
Accept: */*
Content-Type: application/json
Content-Length: 27
{"message":{"body":"TEXT"}} ^C
% nc -l 8000
POST /36576/speak.json HTTP/1.1
Accept-Encoding: identity
Content-Length: 27
Connection: close
Accept: */*
User-Agent: my-python-app/1
Host: localhost:8000
Content-Type: application/json
Authorization: Nzg5ODY3ODpY
{"message":{"body":"TEXT"}}^C
(This is slightly tweaked from the output. My test case didn't use the same url path you used.)
There's no need to use the underlying httplib, which doesn't support things that urllib2 gives you like proxy support. On the other hand, I do find urllib2 to be complicated outside of this simple sort of request and if you want better support for which headers are sent and the order they are sent then use httplib. |
1. Úvod
8.2 Git a ostatní systémy - Přechod na systém Git
Přechod na systém Git
Máte-li existující základ kódu v jiném systému VCS, ale rádi byste začali používat Git, můžete do něj svůj projekt převést. Existuje přitom několik způsobů. V této části se seznámíte s několika importéry pro běžné systémy, které jsou součástí systému Git, a poté ukážeme, jak si můžete vytvořit importér vlastní.
Nyní se naučíte, jak importovat data ze dvou větších, profesionálně používaných systémů SCM – Subversion a Perforce. Oba tyto systémy jsem zvolil proto, že podle mých informací přechází na Git nejvíce uživatelů právě z nich, a také proto, že Git obsahuje vysoce kvalitní nástroje právě pro oba tyto systémy.
Pokud jste si přečetli předchozí část o používání nástrojů git svn, můžete získané informace použít. Příkazem git svn clone naklonujte repozitář, odešlete ho na nový server Git a začněte používat ten. Server Subversion můžete úplně přestat používat. Chcete-li získat historii projektu, dostanete ji tak rychle, jak jen dovedete stáhnout data ze serveru Subversion (což ovšem může chvíli trvat).
Takový import však není úplně dokonalý a vzhledem k tomu, jak dlouho může trvat, nabízí se ještě jiná cesta. Prvním problémem jsou informace o autorovi. V Subversion má každá osoba zapisující revize v systému přiděleného uživatele, který je u zaznamenán informací o revizi. V předchozí části se u některých příkladů (výstupy příkazů blame nebo git svn log) objevilo jméno schacon. Jestliže vyžadujete podrobnější informace ve stylu systému Git, budete potřebovat mapování z uživatelů Subversion na autory Git. Vytvořte soubor users.txt, který bude toto mapování obsahovat v následující podobě:
schacon = Scott Chacon <schacon@geemail.com>
selse = Someo Nelse <selse@geemail.com>
Chcete-li získat seznam jmen autorů používaných v SVN, spusťte tento příkaz:
$ svn log ^/ --xml | grep -P "^<author" | sort -u | \ perl -pe 's/<author>(.*?)<\/author>/$1 = /' > users.txt
Vytvoříte tím log ve formátu XML. Můžete v něm vyhledávat autory, vytvořit si vlastní seznam a XML zase vyjmout. (Tento příkaz pochopitelně funguje pouze na počítačích, v nichž je nainstalován grep, sort a perl.) Poté tento výstup přesměrujte do souboru users.txt, abyste mohli vedle každého záznamu přidat stejná data o uživatelích Git.
Tento soubor můžete dát k dispozici nástroji git svn, aby mohl přesněji zmapovat informace o autorech. Nástroji git svn můžete také zadat, aby ignoroval metadata, která systém Subversion normálně importuje: zadejte parametr --no-metadata k příkazu clone nebo init. Váš příkaz import pak bude mít tuto podobu:
$ git svn clone http://my-project.googlecode.com/svn/ \
--authors-file=users.txt --no-metadata -s my_project
Import ze systému Subversion v adresáři my_project by měl nyní vypadat o něco lépe. Revize už nebudou mít tuto podobu:
commit 37efa680e8473b615de980fa935944215428a35a
Author: schacon <schacon@4c93b258-373f-11de-be05-5f7a86268029>
Date: Sun May 3 00:12:22 2009 +0000
fixed install - go to trunk
git-svn-id: https://my-project.googlecode.com/svn/trunk@94 4c93b258-373f-11de-
be05-5f7a86268029
they look like this:
commit 03a8785f44c8ea5cdb0e8834b7c8e6c469be2ff2Author: Scott Chacon <schacon@geemail.com>Date: Sun May 3 00:12:22 2009 +0000 fixed install - go to trunk
Nejenže teď pole Author vypadá podstatně lépe, ale navíc jste se zbavili i záznamu git-svn-id.
Po importu bude nutné data trochu vyčistit. Zaprvé je nutné vyčistit podivné reference, které vytvořil příkaz git svn. Nejprve přesuňte značky tak, aby se z nich staly skutečné značky, a ne podivné vzdálené větve. V dalším kroku přesunete zbytek větví a uděláte z nich větve lokální.
Abyste značky upravili na korektní gitové značky, spusťte
$ git for-each-ref refs/remotes/tags | cut -d / -f 4- | grep -v @ | while read tagname; do git tag "$tagname" "tags/$tagname"; git branch -r -d "tags/$tagname"; done
Tím se reference, které označovaly vzdálené větve a začínaly tag/, převedou na skutečné (prosté) značky.
Ze zbytku referencí vytvořte v repozitáři refs/remotes lokální větve:
$ git for-each-ref refs/remotes | cut -d / -f 3- | grep -v @ | while read branchname; do git branch "$branchname" "refs/remotes/$branchname"; git branch -r -d "$branchname"; done
Všechny staré větve jsou nyní skutečnými větvemi Git a všechny staré značky jsou nyní skutečnými značkami Git. Poslední věcí, která ještě zbývá, je přidat nový server Git jako vzdálený repozitář a odeslat do něj revize. Tady je příklad, jak můžete váš server přidat jako vzdálený:
$ git remote add origin git@my-git-server:myrepository.git
Protože do něj chcete odeslat všechny své větve a značky, můžete použít příkaz:
$ git push origin --all$ git push origin --tags
Na novém serveru Git tak nyní máte v úhledném, čistém importu uloženy všechny větve a značky.
Dalším systémem, z nějž budeme importovat, bude Perforce. Také importér Perforce je distribuován se systémem Git. Pokud máte verzi Git starší než 1.7.11, pak importér naleznete jen v sekci contrib zdrojového kódu. V takovém případě budete muset získat zdrojový text systému Git, který můžete stáhnout ze serveru git.kernel.org:
$ git clone git://git.kernel.org/pub/scm/git/git.git
$ cd git/contrib/fast-import
V adresáři fast-import byste měli najít spustitelný skript napsaný v jazyce Python pojmenovaný git-p4. Aby vám import fungoval, musíte mít v počítači nainstalován Python a nástroj p4. Budete chtít například importovat projekt Jam z veřejného úložiště Perforce Public Depot. K nastavení svého klienta budete muset exportovat proměnnou prostředí P4PORT, která bude ukazovat na depot Perforce:
$ export P4PORT=public.perforce.com:1666
Spusťte příkaz git-p4 clone, jímž importujete projekt Jam ze serveru Perforce. K příkazu zadejte depot a cestu k projektu, kromě toho také cestu, kam chcete projekt importovat:
$ git-p4 clone //public/jam/src@all /opt/p4import
Importing from //public/jam/src@all into /opt/p4import
Reinitialized existing Git repository in /opt/p4import/.git/
Import destination: refs/remotes/p4/master
Importing revision 4409 (100%)
Přejdete-li do adresáře /opt/p4import a spustíte příkaz git log, uvidíte, co jste importovali:
$ git log -2
commit 1fd4ec126171790efd2db83548b85b1bbbc07dc2
Author: Perforce staff <support@perforce.com>
Date: Thu Aug 19 10:18:45 2004 -0800
Drop 'rc3' moniker of jam-2.5. Folded rc2 and rc3 RELNOTES into
the main part of the document. Built new tar/zip balls.
Only 16 months later.
[git-p4: depot-paths = "//public/jam/src/": change = 4409]
commit ca8870db541a23ed867f38847eda65bf4363371d
Author: Richard Geiger <rmg@perforce.com>
Date: Tue Apr 22 20:51:34 2003 -0800
Update derived jamgram.c
[git-p4: depot-paths = "//public/jam/src/": change = 3108]
V každé revizi si můžete všimnout identifikátoru git-p4. Je dobré ponechat tu identifikátor pro případ, že budete někdy v budoucnu potřebovat odkázat na číslo změny Perforce. Pokud ale chcete identifikátor přesto odstranit, teď, dokud jste nezačali pracovat na novém repozitáři, je ta správná chvíle. K odstranění všech řetězců identifikátoru najednou můžete použít příkaz git filter-branch:
$ git filter-branch --msg-filter '
sed -e "/^\[git-p4:/d"
'
Rewrite 1fd4ec126171790efd2db83548b85b1bbbc07dc2 (123/123)
Ref 'refs/heads/master' was rewritten
Spustíte-li příkaz git log, uvidíte, že se změnily všechny kontrolní součty revizí SHA-1, zato všechny řetězce git-p4 ze zpráv k revizím zmizely:
$ git log -2
commit 10a16d60cffca14d454a15c6164378f4082bc5b0
Author: Perforce staff <support@perforce.com>
Date: Thu Aug 19 10:18:45 2004 -0800
Drop 'rc3' moniker of jam-2.5. Folded rc2 and rc3 RELNOTES into
the main part of the document. Built new tar/zip balls.
Only 16 months later.
commit 2b6c6db311dd76c34c66ec1c40a49405e6b527b2
Author: Richard Geiger <rmg@perforce.com>
Date: Tue Apr 22 20:51:34 2003 -0800
Update derived jamgram.c
Váš import je připraven k odeslání na nový server Git.
Není-li vaším současným systémem ani Subversion, ani Perforce, zkuste vyhledat importér online. Kvalitní importéry se dají najít pro CVS, Clear Case, Visual Source Safe, dokonce i adresář s archivy. Pokud vám nefunguje ani jeden z těchto nástrojů, používáte méně častý nástroj nebo potřebujete speciální proces importu ještě z jiného důvodu, použijte git fast-import. Tento příkaz načítá ze vstupů stdin jednoduché instrukce k zapsáni specifických dat systému Git. Je podstatně jednodušší vytvořit objekty Git tímto způsobem než spouštět syrové příkazy Git či se pokoušet zapsat syrové objekty (podrobnější informace v kapitole 9). Tímto způsobem lze vytvořit importovací skript, který bude načítat potřebné informace ze systému, z nějž import provádíte, a vypíše jasné instrukce do výstupu stdout. Tento program můžete spustit a jeho výstup nechat zpracovat příkazem git fast-import.
Jako rychlou ukázku napíšeme jednoduchý importér. Řekněme, že pracujete na projektu, který příležitostně zálohujete zkopírováním pracovního adresáře do zálohového, datem označeného adresáře back_YYYY_MM_DD, a ten chcete nyní importovat do systému Git. Váš adresář má tuto strukturu:
$ ls /opt/import_from
back_2009_01_02
back_2009_01_04
back_2009_01_14
back_2009_02_03
current
Chcete-li importovat adresář Git, budeme se muset podívat na to, jak Git ukládá svá data. Jak si možná vzpomínáte, říkali jsme, že Git je v podstatě seznam odkazů na objekty revizí, které ukazují na určitý snímek obsahu. Jediné, co tedy musíte udělat, je sdělit příkazu fast-import, co je obsahem snímků, jaká data revizí na ně ukazují a pořadí, v němž budou převzaty. Vaše strategie tedy bude spočívat v tom, že postupně projdete jednotlivé snímky a vytvoříte revize s obsahem každého adresáře, přičemž každá revize bude odkazovat na revizi předchozí.
Stejně jako v podkapitole „Příklad vynucení chování systémem Git“ v kapitole 7 použijeme i tentokrát Ruby, s nímž většinou pracuji a který je srozumitelný. Tento příklad můžete ale beze všeho napsat v čemkoli, co vám vyhovuje. Jedinou podmínkou je, aby byly potřebné informace zapsány na standardní výstup (stdout). A to v případě používání Windows znamená, že budete muset věnovat zvláštní pozornost tomu, abyste na koncích řádků nevkládali znaky CR (carriage return). Příkaz git fast-import je v tomto směru velmi vybíravý a chce jen znaky LF (line feed) a nikoliv kombinaci CRLF, kterou používají Windows.
Na začátku přejdete do cílového adresáře a identifikujete všechny podadresáře, z nichž bude každý představovat jeden snímek, který chcete importovat jako revizi. Přejdete do každého podadresáře a zadáte příkazy potřebné k jeho exportu. Základní smyčka bude mít tuto podobu:
last_mark = nil
# loop through the directories
Dir.chdir(ARGV[0]) do
Dir.glob("*").each do |dir|
next if File.file?(dir)
# move into the target directory
Dir.chdir(dir) do
last_mark = print_export(dir, last_mark)
end
end
end
V každém adresáři spustíte soubor print_export, který vezme manifest a známku předchozího snímku a poskytne manifest a označovač tohoto snímku. Tímto způsobem je lze řádně spojit. „Označovač“ (angl. mark) je termín používaný v souvislosti s metodou fast-import. Jedná se o identifikátor, který jednoznačně přiřadíte revizi a lze ho použít k odkazování na tuto revizi z revizí ostatních. Prvním krokem, který tak při metodě se souborem print_export uděláte, bude vygenerování označovače na základě názvu adresáře:
mark = convert_dir_to_mark(dir)
Provedete to tak, že vytvoříte skupinu adresářů a jako označovač použijete hodnotu indexu, neboť označovač musí být celé číslo. Celý postup vypadá takto:
$marks = []
def convert_dir_to_mark(dir)
if !$marks.include?(dir)
$marks << dir
end
($marks.index(dir) + 1).to_s
end
Nyní jste označili revizi celým číslem a zbývá stanovit datum pro metadata revize. Protože je datum obsaženo v názvu adresáře, lze ho vyčíst odtud. Dalším řádkem v souboru print_export bude
date = convert_dir_to_date(dir)
kde convert_dir_to_date je definováno jako:
def convert_dir_to_date(dir)
if dir == 'current'
return Time.now().to_i
else
dir = dir.gsub('back_', '')
(year, month, day) = dir.split('_')
return Time.local(year, month, day).to_i
end
end
Tím dostanete celé číslo pro data každého adresáře. Posledními metadaty, jež budete pro všechny revize potřebovat, jsou informace o autorovi revize, které zadáte v globální proměnné:
$author = 'Scott Chacon <schacon@example.com>'
Nyní je už vše připraveno k vygenerování dat revizí pro váš importér. Úvodní informace sděluje, že definujete objekt revize a na jaké větvi se nachází. Následuje vygenerovaný označovač, informace o autorovi revize a zpráva k revizi, po ní následuje eventuální předchozí revize. Kód má tuto podobu:
# print the import information
puts 'commit refs/heads/master'
puts 'mark :' + mark
puts "committer #{$author} #{date} -0700"
export_data('imported from ' + dir)
puts 'from :' + last_mark if last_mark
Časové pásmo definujete napevno (--0700), protože je to jednoduché. Pokud importujete z jiného systému, musíte zadat časové pásmo jako posun. Zpráva k revizi musí být ve speciálním formátu:
data (size)\n(contents)
Tento formát tedy obsahuje slovo data, velikost načítaných dat (size), nový řádek a konečně data samotná (contents). Protože budete stejný formát potřebovat i později, k určení obsahu souboru vytvoříte pomocnou metodu – export_data:
def export_data(string)
print "data #{string.size}\n#{string}"
end
Teď už zbývá jen určit obsah souborů všech snímků. To bude snadné, protože máte všechny v jednom adresáři. Zadejte příkaz deleteall a k němu přidejte obsah každého souboru v adresáři. Git pak odpovídajícím způsobem nahraje všechny snímky:
puts 'deleteall'
Dir.glob("**/*").each do |file|
next if !File.file?(file)
inline_data(file)
end
Poznámka: Vzhledem k tomu, že mnoho systémů chápe revize jako změny od jednoho zapsání k druhému, přijímá fast-import také příkazy s každým zapsáním a zjišťuje, které soubory byly přidány, odstraněny nebo změněny a co je jejich novým obsahem. Mohli byste také vypočítat rozdíly mezi snímky a poskytnout pouze tato data. To je však o něco složitější. Stejně tak můžete systému Git zadat všechna data a přenechat výpočet na něm. Pokud je pro vaše data tato metoda vhodnější, odkážeme vás na manuálovou stránku fast-import, kde najdete podrobnosti o tom, jak zadat data tímto způsobem.
Formát pro výpis obsahu nového souboru nebo určení změněného souboru s novým obsahem je následující:
M 644 inline path/to/file
data (size)
(file contents)
644 je v tomto případě režim (jde-li o spustitelné soubory, budete je muset vyhledat a zadat režim 755) a výraz inline říká, že obsah uvedete bezprostředně po tomto řádku. Metoda inline_data má tuto podobu:
def inline_data(file, code = 'M', mode = '644')
content = File.read(file)
puts "#{code} #{mode} inline #{file}"
export_data(content)
end
Znovu tu využijete metodu export_data, kterou jste aplikovali před chvílí. Jedná se totiž o stejný způsob, jakým jste specifikovali data zprávy k revizi.
Poslední věcí, kterou musíte udělat, je vrátit aktuální označovač, aby mohl být zadán do příští iterace:
return mark
Poznámka: Pokud používáte Windows, budete muset provést jeden krok navíc. Jak už jsem se zmínil, Windows nahrazují znak konce řádku posloupností CRLF, zatímco git fast-import očekává pouze LF. Abychom tento problém obešli a přitom učinili příkaz git fast-import šťastným, musíte ruby říct, aby místo LF používal CRLF:
$stdout.binmode
A to je celé. Spustíte-li tento skript, získáte obsah v následující podobě:
$ ruby import.rb /opt/import_from
commit refs/heads/master
mark :1
committer Scott Chacon <schacon@geemail.com> 1230883200 -0700
data 29
imported from back_2009_01_02deleteall
M 644 inline file.rb
data 12
version two
commit refs/heads/master
mark :2
committer Scott Chacon <schacon@geemail.com> 1231056000 -0700
data 29
imported from back_2009_01_04from :1
deleteall
M 644 inline file.rb
data 14
version three
M 644 inline new.rb
data 16
new version one
(...)
Pro spuštění importéru přesměrujte tento výstup do příkazu git fast-import. Příkaz spouštějte v adresáři Gitu, do nějž chcete data importovat. Můžete vytvořit nový adresář a spustit v něm příkaz git init, jímž si vytvoříte nový výchozí bod. Poté spusťte svůj skript:
$ git init
Initialized empty Git repository in /opt/import_to/.git/
$ ruby import.rb /opt/import_from | git fast-import
git-fast-import statistics:
---------------------------------------------------------------------
Alloc'd objects: 5000
Total objects: 18 ( 1 duplicates )
blobs : 7 ( 1 duplicates 0 deltas)
trees : 6 ( 0 duplicates 1 deltas)
commits: 5 ( 0 duplicates 0 deltas)
tags : 0 ( 0 duplicates 0 deltas)
Total branches: 1 ( 1 loads )
marks: 1024 ( 5 unique )
atoms: 3
Memory total: 2255 KiB
pools: 2098 KiB
objects: 156 KiB
---------------------------------------------------------------------
pack_report: getpagesize() = 4096
pack_report: core.packedGitWindowSize = 33554432
pack_report: core.packedGitLimit = 268435456
pack_report: pack_used_ctr = 9
pack_report: pack_mmap_calls = 5
pack_report: pack_open_windows = 1 / 1
pack_report: pack_mapped = 1356 / 1356
---------------------------------------------------------------------
Proběhne-li proces úspěšně, podá vám obsáhlou statistiku o tom, co bylo provedeno. V tomto případě jsme importovali celkem 18 objektů 5 revizí do 1 větve. Nyní si můžete nechat příkazem git log zobrazit svoji novou historii:
$ git log -2commit 10bfe7d22ce15ee25b60a824c8982157ca593d41Author: Scott Chacon <schacon@example.com>Date: Sun May 3 12:57:39 2009 -0700 imported from currentcommit 7e519590de754d079dd73b44d695a42c9d2df452Author: Scott Chacon <schacon@example.com>Date: Tue Feb 3 01:00:00 2009 -0700 imported from back_2009_02_03
A máme to tu — krásný, čistý repozitář Git. Měli bychom také dodat, že nejsou načtena žádná data, zatím neproběhl checkout žádných souborů do pracovního adresáře. Chcete-li je získat, musíte vaši větev resetovat do místa, kde se nyní nachází větev master:
$ ls$ git reset --hard masterHEAD is now at 10bfe7d imported from current$ lsfile.rb lib
Nástroj fast-import vám nabízí ještě spoustu dalších možností – nastavení různých režimů, práci s binárními daty, manipulaci s několika větvemi a jejich slučování, značky, ukazatele postupu atd. Několik příkladů složitějších scénářů si můžete prohlédnout v adresáři contrib/fast-import ve zdrojovém kódu Git. Jedním z těch nejlepších je už zmíněný skriptgit-p4. |
Etoma
Re : /* Topic des codeurs [7] */
Écrire du code est très exigeant.
C'est plaisant.
Hors ligne
tshirtman
Re : /* Topic des codeurs [7] */
si les experts d'haskell peuvent l'aider… (j'aime bien ce gars… c'est le mec qui code git-annex et upload des paquets debian depuis un netbook tournant à l'énergie solaire dans une yhourt perdue dans la forêt).
http://kitenet.net/~joey/blog/entry/uni … _homework/
Hors ligne
Elzen
Re : /* Topic des codeurs [7] */
Les thèmes par défaut de xfce4-notifyd ne suffisent pas comme exemples ?
Bah non, justement : aucun de ces thèmes ne fait de différence entre le titre et le contenu normal. C'est par là que j'ai commencé (j'utilisais Smoke avant de voir à quel point la config était simple et de me faire mon thème à moi).
En fait, c'est « widget_class "XfceNotifyWindow.*.<GtkLabel>" » qui référence à la fois le label contenant le titre et le label contenant le message, apparemment. J'n'ai pas (encore ?) trouvé comment différencier les deux… je crains qu'il n'y ait pas moyen, à moins peut-être que le gtkrc-2.0 accepte une syntaxe bizarre pour dire « tel élément, s'il est suivi/précédé de tel autre »…
Edit :
un netbook tournant à l'énergie solaire
Je veux !
Dernière modification par ArkSeth (Le 07/02/2012, à 01:41)
Elzen : polisson, polémiste, polymathe ! (ex-ArkSeth)
Un script pour améliorer quelques trucs du forum.
La joie de t'avoir connu surpasse la peine de t'avoir perdu…
J'ai pour qualité de ne jamais attaquer les gens. J'ai pour défaut de souvent avoir l'air de le faire.
Hors ligne
Pylades
Re : /* Topic des codeurs [7] */
Ça à l’air cool, jusqu’à ce qu’on se demande ce qui se passe la nuit…
Pis faut sortir, toussa ; on ne peut pas rester à l’intérieur.
“Any if-statement is a goto. As are all structured loops.
“And sometimes structure is good. When it’s good, you should use it.
“And sometimes structure is _bad_, and gets into the way, and using a goto is just much clearer.”
Linus Torvalds – 12 janvier 2003
Hors ligne
tshirtman
Re : /* Topic des codeurs [7] */
@Arkseth: oh, le netbook est conventionnel, c'est juste la yourt qui est équippé de panneaux, de batteries et tout ça, et qu'il recharge dessus… ce qui lui donne quelques heures pour bosser le soir, mais pas trop… une vie saine quoi…
/me va dormir…
Hors ligne
Elzen
Re : /* Topic des codeurs [7] */
Majuscule
Et ouais, vachement moins intéressant, de suite. Mais quand même, ça doit être fun.
Elzen : polisson, polémiste, polymathe ! (ex-ArkSeth)
Un script pour améliorer quelques trucs du forum.
La joie de t'avoir connu surpasse la peine de t'avoir perdu…
J'ai pour qualité de ne jamais attaquer les gens. J'ai pour défaut de souvent avoir l'air de le faire.
Hors ligne
Rolinh
Re : /* Topic des codeurs [7] */
Allez, pour le fun:
factorielle récursive (oui, c'est pour la démo ) en Python:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def fact(x):
if x < 2:
return 1
else:
return x * fact(x-1)
print(fact(1234))
La même en Prolog:
fact(0,R):-
R = 1.
fact(N,R):-
N > 0,
fact(N-1, X),
R is N * X.
Les résultats pour la factorielle de 1234 (c'est déjà un sacré grand nombre):
Python (résultat que j'attendais):
RuntimeError: maximum recursion depth exceeded in comparison
Et pour Prolog:
51084981466469576881306176261004598750272741624636207875758364885679783886389114119904367398214909451616865959797190085595957216060201081790863562740711392408402606162284424347926444168293770306459877429620549980121621880068812119922825565603750036793657428476498577316887890689284884464423522469162924654419945496940052746066950867784084753581540148194316888303839694860870357008235525028115281402379270279446743097868896180567901452872031734195056432576568754346528258569883526859826727735838654082246721751819658052692396270611348013013786739320229706009940781025586038809493013992111030432473321532228589636150722621360366978607484692870955691740723349227220367512994355146567475980006373400215826077949494335370591623671142026957923937669224771617167959359650439966392673073180139376563073706562200771241291710828132078928672693377605280698340976512622686207175259108984253979970269330591951400265868944014001740606398220709859461709972092316953639707607509036387468655214963966625322700932867195641466506305265122238332824677892386098873045477946570475614470735681011537762930068333229753461311175690053190276217215938122229254011663319535668562288276814566536254139944327446923749675156838399258655227114181067181300031191298489076680172983118121156086627360397334232174932132686080901569496392129263706595509472541921027039947595787992209537069031379517112985804276412719491334730247762876260753560199012424360211862466047511184797159731714330368251192307852167757615200611669009575630075581632200897019110165738489288234845801413542090086926381756642228872729319587724120647133695447658709466047131787467521648967375146176025775545958018149895570817463048968329692812003996105944812538484291689075721849889797647554854834050132592317503861422078077932841396250772305892378304960421024845815047928229669342818218960243579473180986996883486164613586224677782405363675732940386436560159992961462550218529921214223556288943276860000631422449845365510986932611414112386178573447134236164502410346254516421812825350152383907925299199371093902393126317590337340371199288380603694517035662665827287352023563128756402516081749705325705196477769315311164029733067419282135214232605607889159739038923579732630816548135472123812968829466513428484683760888731900685205308016495533252055718190142644320009683032677163609744614629730631454898167462966265387871725580083514565623719270635683662268663333999029883429331462872848995229714115709023973771126468913873648061531223428749576267079084534656923514931496743842559669386638509884709307166187205161445819828263679270112614012378542273837296427044021252077863706963514486218183806491868791174785424506337810550453063897866281127060200866754011181906809870372032953354528699094096145120997842075109057859226120844176454175393781254004382091350994101959406590175402086698874583611581937347003423449521223245166665792257252160462357733000925232292157683100179557359793926298007588370474068230320921987459976042606283566005158202572800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Je précise que sur mon core i7, le résultat apparaît instantanément à l'écran.
Enfin, vous pouvez toujours faire le test.
Hors ligne
Etoma
Re : /* Topic des codeurs [7] */
Salut.
J'avance dans le bouquin. C'est pas mal.
Je me demandais la relation entre le codage et le processeur/ram.
Puisque je ne pense pas je ne compte pas faire beaucoup de graphisme, tout ça, j'écarte la carte graphique.
Voici la question donc : Est-ce que lorsque l'on code beaucoup, et complexe (plus que ce que je fais, genre print ("Willkommen")) le processeur doit être puissant avec plein de ram, ou alors le plus pauvre des atom /fusion suffit?
Hors ligne
Rolinh
Re : /* Topic des codeurs [7] */
Salut Etoma,
excuse-moi mais... ta question n'a aucun sens. Ça ne veut rien dire "coder beaucoup" (ou alors je ne comprend pas ce que tu veux dire par là car je ne comprend pas le rapport entre "coder beaucoup" et "puissance d'un processeur"). Tu veux dire: faut-il un ordinateur puissant pour coder une application complexe?
Si c'est ça, la réponse est non. En soi, coder revient à écrire du texte. En revanche, si tu dois beaucoup compiler, et notamment des applications lourdes, alors oui: un processeur puissant est appréciable bien que la seule chose qui changera sera le temps de compilation. C'est surtout une question de confort quoi. Je code souvent sur mon netbook de 2-3ans d'âge avec un Atom N280 (ou N270 ou N260 je sais plus) et il répond parfaitement à 100% de mes besoins de ce côté.
Hors ligne
grim7reaper
Re : /* Topic des codeurs [7] */
C’est quoi le but de la comparaison Python/Prolog ?
(il est de notoriété publique que Python n’optimise pas les récursions, plus ou moins du fait de la volonté de Guido il me semble).
Sinon en Haskell
grim7reaper@smile ~]$ghci
GHCi, version 7.0.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Loading package ffi-1.0 ... linking ... done.
Prelude> let factorial n = if n > 0 then n * factorial (n-1) else 1
Prelude> factorial 1234
51084981466469576881306176261004598750272741624636207875758364885679783886389114119904367398214909451616865959797190085595957216060201081790863562740711392408402606162284424347926444168293770306459877429620549980121621880068812119922825565603750036793657428476498577316887890689284884464423522469162924654419945496940052746066950867784084753581540148194316888303839694860870357008235525028115281402379270279446743097868896180567901452872031734195056432576568754346528258569883526859826727735838654082246721751819658052692396270611348013013786739320229706009940781025586038809493013992111030432473321532228589636150722621360366978607484692870955691740723349227220367512994355146567475980006373400215826077949494335370591623671142026957923937669224771617167959359650439966392673073180139376563073706562200771241291710828132078928672693377605280698340976512622686207175259108984253979970269330591951400265868944014001740606398220709859461709972092316953639707607509036387468655214963966625322700932867195641466506305265122238332824677892386098873045477946570475614470735681011537762930068333229753461311175690053190276217215938122229254011663319535668562288276814566536254139944327446923749675156838399258655227114181067181300031191298489076680172983118121156086627360397334232174932132686080901569496392129263706595509472541921027039947595787992209537069031379517112985804276412719491334730247762876260753560199012424360211862466047511184797159731714330368251192307852167757615200611669009575630075581632200897019110165738489288234845801413542090086926381756642228872729319587724120647133695447658709466047131787467521648967375146176025775545958018149895570817463048968329692812003996105944812538484291689075721849889797647554854834050132592317503861422078077932841396250772305892378304960421024845815047928229669342818218960243579473180986996883486164613586224677782405363675732940386436560159992961462550218529921214223556288943276860000631422449845365510986932611414112386178573447134236164502410346254516421812825350152383907925299199371093902393126317590337340371199288380603694517035662665827287352023563128756402516081749705325705196477769315311164029733067419282135214232605607889159739038923579732630816548135472123812968829466513428484683760888731900685205308016495533252055718190142644320009683032677163609744614629730631454898167462966265387871725580083514565623719270635683662268663333999029883429331462872848995229714115709023973771126468913873648061531223428749576267079084534656923514931496743842559669386638509884709307166187205161445819828263679270112614012378542273837296427044021252077863706963514486218183806491868791174785424506337810550453063897866281127060200866754011181906809870372032953354528699094096145120997842075109057859226120844176454175393781254004382091350994101959406590175402086698874583611581937347003423449521223245166665792257252160462357733000925232292157683100179557359793926298007588370474068230320921987459976042606283566005158202572800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
(Chez moi aussi c’est instantané).
Dernière modification par grim7reaper (Le 08/02/2012, à 00:17)
Hors ligne
The Uploader
Re : /* Topic des codeurs [7] */
irb(main):002:0> def fact(x)
irb(main):003:1> if x < 2
irb(main):004:2> return 1
irb(main):005:2> else
irb(main):006:2* return x * (fact(x-1))
irb(main):007:2> end
irb(main):008:1> end
=> nil
irb(main):009:0> fact(5)
=> 120
irb(main):010:0> fact(1234)
=> 51084981466469576881306176261004598750272741624636207875758364885679783886389114119904367398214909451616865959797190085595957216060201081790863562740711392408402606162284424347926444168293770306459877429620549980121621880068812119922825565603750036793657428476498577316887890689284884464423522469162924654419945496940052746066950867784084753581540148194316888303839694860870357008235525028115281402379270279446743097868896180567901452872031734195056432576568754346528258569883526859826727735838654082246721751819658052692396270611348013013786739320229706009940781025586038809493013992111030432473321532228589636150722621360366978607484692870955691740723349227220367512994355146567475980006373400215826077949494335370591623671142026957923937669224771617167959359650439966392673073180139376563073706562200771241291710828132078928672693377605280698340976512622686207175259108984253979970269330591951400265868944014001740606398220709859461709972092316953639707607509036387468655214963966625322700932867195641466506305265122238332824677892386098873045477946570475614470735681011537762930068333229753461311175690053190276217215938122229254011663319535668562288276814566536254139944327446923749675156838399258655227114181067181300031191298489076680172983118121156086627360397334232174932132686080901569496392129263706595509472541921027039947595787992209537069031379517112985804276412719491334730247762876260753560199012424360211862466047511184797159731714330368251192307852167757615200611669009575630075581632200897019110165738489288234845801413542090086926381756642228872729319587724120647133695447658709466047131787467521648967375146176025775545958018149895570817463048968329692812003996105944812538484291689075721849889797647554854834050132592317503861422078077932841396250772305892378304960421024845815047928229669342818218960243579473180986996883486164613586224677782405363675732940386436560159992961462550218529921214223556288943276860000631422449845365510986932611414112386178573447134236164502410346254516421812825350152383907925299199371093902393126317590337340371199288380603694517035662665827287352023563128756402516081749705325705196477769315311164029733067419282135214232605607889159739038923579732630816548135472123812968829466513428484683760888731900685205308016495533252055718190142644320009683032677163609744614629730631454898167462966265387871725580083514565623719270635683662268663333999029883429331462872848995229714115709023973771126468913873648061531223428749576267079084534656923514931496743842559669386638509884709307166187205161445819828263679270112614012378542273837296427044021252077863706963514486218183806491868791174785424506337810550453063897866281127060200866754011181906809870372032953354528699094096145120997842075109057859226120844176454175393781254004382091350994101959406590175402086698874583611581937347003423449521223245166665792257252160462357733000925232292157683100179557359793926298007588370474068230320921987459976042606283566005158202572800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
(instantané sur un C2D T5800)
Passer de Ubuntu 10.04 à Xubuntu 12.04 LTS
Archlinux + KDE sur ASUS N56VV.
ALSA, SysV, DBus, Xorg = Windows 98 !
systemd, kdbus, ALSA + PulseAudio, Wayland = modern OS (10 years after Windows, but still...) ! Deal with it !
Hors ligne
Etoma
Re : /* Topic des codeurs [7] */
Pardon, pour la mauvaise formulation!
Malgré tout, tu as bien décodé le sens de ma question.
Je pensais bien à coder des applications lourdes/complexes et pas simplement deux-trois lignes de codes à compiler.
Par exemple, pour coder avec un netbook! Je pense par exemple à l'atom 435, qui est assez faible, mais pas cher du tout.
Enfin, merci pour la réponse rapide!
Hors ligne
Rolinh
Re : /* Topic des codeurs [7] */
C’est quoi le but de la comparaison Python/Prolog ?
Oh, je sais pas, faire réagir tshirtman?
J'avoue que ça n'a pas grand intérêt. Ça doit être d'avoir passé une journée sur du prolog qui m'a mis dans cet état. ^^
Hors ligne
The Uploader
Re : /* Topic des codeurs [7] */
Oh, je sais pas, faire réagir tshirtman?
Déjà fait : Ruby fonctionne, Python renvoie une exception. Y'a plus qu'à attendre.
Passer de Ubuntu 10.04 à Xubuntu 12.04 LTS
Archlinux + KDE sur ASUS N56VV.
ALSA, SysV, DBus, Xorg = Windows 98 !
systemd, kdbus, ALSA + PulseAudio, Wayland = modern OS (10 years after Windows, but still...) ! Deal with it !
Hors ligne
Rolinh
Re : /* Topic des codeurs [7] */
Déjà fait : Ruby fonctionne, Python renvoie une exception. Y'a plus qu'à attendre.
@Etoma: pas de quoi. Tu as l'intention de déjà te lancer dans un grand projet?
Hors ligne
Etoma
Re : /* Topic des codeurs [7] */
Ben, je sais pas, mais je pense plus que faire des devinettes pour savoir le chiffre que j'ai planqué dans mon code!
Pis bon, je pense reprendre des études, et je pense me diriger vers l'informatique (tout autre chose que le social, dans lequel je travaille en ce moment).
Hors ligne
Pylades
Re : /* Topic des codeurs [7] */
Bah, avec Python la réponse est aussi instantanée, si tu ne fais pas de récursion…
“Any if-statement is a goto. As are all structured loops.
“And sometimes structure is good. When it’s good, you should use it.
“And sometimes structure is _bad_, and gets into the way, and using a goto is just much clearer.”
Linus Torvalds – 12 janvier 2003
Hors ligne
Jules Petibidon
Re : /* Topic des codeurs [7] */
Python fournit une méthode pour les factorielles, ça compte ou pas ?
import math
math.factorial(1234)
Comme l'a dit grim' la récursion est "volontairement" limitée avec Python. Ça peut être considéré comme une faiblesse si ça peut faire plaisir, mais les cas où ça pose problème sont assez rares.
Hors ligne
Rolinh
Re : /* Topic des codeurs [7] */
@Etoma: une solution toujours envisageable est de compiler sur une autre machine. Il m'arrive parfois de programmer directement sur une machine que je prend à distance.
@Pylade: Heu... oui, et?
Hors ligne
The Uploader
Re : /* Topic des codeurs [7] */
Python fournit une méthode pour les factorielles, ça compte ou pas ?
import math
math.factorial(1234)
Comme l'a dit grim' la récursion est "volontairement" limitée avec Python. Ça peut être considéré comme une faiblesse si ça peut faire plaisir, mais les cas où ça pose problème sont assez rares.
Ah tiens, il n'y a pas de Math.factorial (ni Math.fact) dans le module Math de Ruby...
http://stackoverflow.com/questions/2434 … l-function
Dernière modification par The Uploader (Le 08/02/2012, à 00:18)
Passer de Ubuntu 10.04 à Xubuntu 12.04 LTS
Archlinux + KDE sur ASUS N56VV.
ALSA, SysV, DBus, Xorg = Windows 98 !
systemd, kdbus, ALSA + PulseAudio, Wayland = modern OS (10 years after Windows, but still...) ! Deal with it !
Hors ligne
Rolinh
Re : /* Topic des codeurs [7] */
@Etoma: seul 8Go pour le SSD: ça risque de faire un peu peu. Si tu comptes garder Meego, je ne sais pas à quel point on peut en faire un environnement de développement mais je doute un peu du résultat. Sans compter qu'un petit écran, avec une faible définition, peut être un peu gênant. Il est difficile par exemple d'avoir côte à côte une page de documentation et un fenêtre avec un éditeur de texte sur le code, ce qui peut s'avérer gênant pour programmer. Enfin, avec mon netbook, c'est ce qui me dérange. On doit pouvoir trouver des 11" avec du 1366x766 qui devrait être nettement plus confortable sans plus d'encombrement.
Hors ligne
tshirtman
Re : /* Topic des codeurs [7] */
@Etoma: j'ai codé les premières versions d'USF (voir ma signature) sur un eeepc 701… il comptait déjà plusieurs milliers de lignes de code source à l'époque et ça marchait bien, nos machines sont des monstres de puissances, la seule chose qui les mets à genoux c'est de faire des calculs lourd… pas de dérouler des suites d'instructions simples (enfin, je me comprends, les calculs lourds se fond aussi en déroulant des des suites d'instructions simples au final, un ordinateur ne fait que ça de toutes façons).
Pour la limite de récursion, oui… ça pose rarement problème et en effet, une fonction est fournie pour ça… j'ai jamais (ou si peu) prétendus que python était parfais en tout… c'est juste selon moi globalement le meilleur langage de loin…
et pas la peine de faire vos malins par ce que vos langages modèrnes font ça instantanément… la dernière fois que j'ai testé, LISP faisait pareil…
Hors ligne
grim7reaper
Re : /* Topic des codeurs [7] */
Moderne ?
Haskell date de 1985.
Prolog date de 1972.
Common Lisp (parce que je suppose que c’est de lui que tu parles, vu que ça m’étonnerais que tu testes l’implémentation de 1958) date de 1984.
Mouais, pas grande différence hein…
Pas une question de modernité, juste une question de design du langage.
Dernière modification par grim7reaper (Le 08/02/2012, à 00:40)
Hors ligne
The Uploader
Re : /* Topic des codeurs [7] */
Pour la limite de récursion, oui… ça pose rarement problème et en effet, une fonction est fournie pour ça… j'ai jamais (ou si peu) prétendus que python était parfais en tout… c'est juste selon moi globalement le meilleur langage de loin…
Bah Ruby n'est pas parfait non plus :
- pas de Math.factorial (c'est quand même assez surprenant)
- pas de surcharge
- pas d'héritage multiple (oui il y a les modules mais en inclure plus d'un devient vite casse-tête pour 'super' s'ils ont tous un initialize. Heureusement on peut nommer l'initialize d'un module autrement ou l'appeler explicitement)
- pas de commentaires multiligne (Pas très gênant, mas faire un " >>EOF " ou je sais plus quoi pour désactiver tout le code après le commentaire faut le trouver... En plus c'est franchement moche. Bon c'est rare d'avoir à faire ça, heureusement)
Mais c'est pour moi le meilleur langage OO / procédural, et de loin..
Dernière modification par The Uploader (Le 08/02/2012, à 00:41)
Passer de Ubuntu 10.04 à Xubuntu 12.04 LTS
Archlinux + KDE sur ASUS N56VV.
ALSA, SysV, DBus, Xorg = Windows 98 !
systemd, kdbus, ALSA + PulseAudio, Wayland = modern OS (10 years after Windows, but still...) ! Deal with it !
Hors ligne |
I am trying to parse webpages using urllib2, BeautifulSoup and Python 2.7.
The problem lies upstream: each time I try to retrieve a new webpage, I get the one I already retrieved. However, pages are different in my webbrowser: see page 1 and page 2. Is there something wrong with the loop over page numbers?
Here is a code sample:
def main(page_number_max):
import urllib2 as ul
from BeautifulSoup import BeautifulSoup as bs
base_url = 'http://www.senscritique.com/clement/collection/#page='
for page_number in range(1, 1+page_number_max):
url = base_url + str(page_number) + '/'
html = ul.urlopen(url)
bt = bs(html)
for item in bt.findAll('div', 'c_listing-products-content xl'):
item_name = item.findAll('h2', 'c_heading c_heading-5 c_bold')
print str(item_name[0].contents[1]).split('\t')[11]
print('End of page ' + str(page_number) + '\n')
if __name__ == '__main__':
page_number_max = 2
main(page_number_max)
|
D-Bus Interface: Connecting to a Server
NB: This scheme will very likely be changed, details about this are in this mailing list message: [https://tango.0pointer.de/pipermail/pulseaudio-discuss/2009-July/004437.html]. At the time of writing, there are no responses so it's not certain yet what the final server discovery scheme will exactly look like. The following description applies to the current development version.
Procedure
When a client wants to connect to a server, it reads the $PULSE_DBUS_SERVER environment variable, which contains a server address or a list of addresses, as specified in the D-Bus Specification, section Server Addresses. The client should be able to use the string directly as the address parameter of the underlying D-Bus library's connect function.
If $PULSE_DBUS_SERVER is not set, the client reads the Address property (part of the org.PulseAudio.ServerLookup1 interface) of object /org/pulseaudio/server_lookup1. The destination of the call is org.PulseAudio1. The property contains a string similar to the $PULSE_DBUS_SERVER environment variable. The returned string is empty if client.conf doesn't set any address (which is the default) and the daemon is configured to not run local servers. Reading the property may autostart pulseaudio. Due to the fact that pulseaudio may exit automatically after a while, the client shouldn't wait long between reading the address and connecting to the server (the default timeout is 20 seconds).
Authentication
D-Bus handles authentication automatically, so client programmers shouldn't need to care about that otherwise than keeping in mind that authentication may fail. For now the access control is done in the following way (very likely to change):
When a server runs in the system mode, it by default listens only for local unix domain socket connections and accepts all connections.
When a server runs in the user mode and listens only for local unix domain socket connections (the default case), only connections by the same user as the server and connections by root are accepted.
Whenever a server listens for TCP connections all connections are accepted.
Example Python Code
This is an example (could be improved) of how D-Bus clients can establish a connection to PulseAudio:
#!/usr/bin/env python
import dbus
import os
def connect():
if 'PULSE_DBUS_SERVER' in os.environ:
address = os.environ['PULSE_DBUS_SERVER']
else:
bus = dbus.SessionBus()
server_lookup = bus.get_object("org.PulseAudio1", "/org/pulseaudio/server_lookup1")
address = server_lookup.Get("org.PulseAudio.ServerLookup1", "Address", dbus_interface="org.freedesktop.DBus.Properties")
return dbus.connection.Connection(address)
conn = connect()
core = conn.get_object(object_path="/org/pulseaudio/core1")
print "Successfully connected to " + core.Get("org.PulseAudio.Core1", "Name", dbus_interface="org.freedesktop.DBus.Properties") + "!"
Lookup Service Details
To give some background information (and to document this stuff somewhere), this is how server discovery works from PulseAudio's point of view:
Contrary to earlier behavior, running the pulseaudio executable with D-Bus support compiled in doesn't necessary start a proper sound server. In certain circumstances only the server lookup service, as described above, is started. This happens in two cases: the executable is run by a non-root user and the daemon is configured to run in the system mode, or the daemon configuration just says that no local server should be started (which is useful when only remote servers are intended to be used).
There is a new option in daemon.conf: local-server-type. Its value can be either "user", "system" or "none". The default is "user". However, the option conflicts with the old option system-instance. If system-instance is set and local-server-type is not, system-instance value is honored. On the other hand, if local-server-type is set, it overrides whatever is the value of system-instance.
If user's pulseaudio executable isn't running when a client reads the Address property, D-Bus automatically starts pulseaudio. Depending on server configuration, a real sound server may be started, but another possibility is that only the server lookup service is enabled. The server lookup service, i.e. the Address property, works by first reading the user's (or in absence of that, the system version of) client.conf. client.conf too has a new option: default-dbus-server. If it is set, then that value is returned to the client. If default-dbus-server is not set, the address is deduced from the local-server-type option: in case of "user" the returned address is the unix socket of the user's server (~/.pulse/ |
WordNet has a hypernym / hyponym hierarchy but that is not what you want here, as you can see when you look up goalkeeper:
from nltk.corpus import wordnet
s = wordnet.synsets('goalkeeper')[0]
s.hypernym_paths()
One of the results is:
[Synset('entity.n.01'),
Synset('physical_entity.n.01'),
Synset('causal_agent.n.01'),
Synset('person.n.01'),
Synset('contestant.n.01'),
Synset('athlete.n.01'),
Synset('soccer_player.n.01'),
Synset('goalkeeper.n.01')]
There are two methods called usage_domains() and topic_domains() but they return an empty list for most words:
s = wordnet.synsets('football')[0]
s.topic_domains()
>>> []
s.usage_domains()
>>> []
The WordNet Domains project however could be what you are looking for. It offers a text file that contains the mapping between Princeton WordNet 2.0 synsets and their corresponding domains. You have to register your email address to get access to the data. Then you can read in the file that corresponds to your WordNet version (they offer 2.0 and 3.2), for example with the anydbm module:
import anydbm
fh = open('wn-domains-2.0-20050210', 'r')
dbdomains = anydbm.open('dbdomains', 'c')
for line in fh:
offset, domain = line.split('\t')
dbdomains[offset[:-2]] = domain
fh.close()
You can then use the offset attribute of a synset to find out its domain. Maybe you have to add a zero at the beginning:
dbdomains.get('0' + str(wordnet.synsets('travel_guidebook')[0].offset))
>>> 'linguistics\n'
|
michelk
la lecture de flux radio ne fonctionne plus(ubuntu 12.10 - rhythmbox)
Bonjour,
Après une mise à jour, la lecture de flux radio ne fonctionne plus (ubuntu 12.10 - rhythmbox). Lorsque je clique sur les noms des radios, celles-ci s'affichent avec un sens interdit. J'ai essayé de lancer rhythmbox à partir d'un terminal.
Voici ce que j'obtiens:
Fontconfig warning: "/etc/fonts/conf.d/50-user.conf", line 9: reading configurations from ~/.fonts.conf is deprecated.
** (rhythmbox:5591): WARNING **: GObject.get_data() and set_data() are deprecated. Use normal Python attributes instead
(rhythmbox:5591): Rhythmbox-WARNING **: Could not open device /dev/radio0
J'ai aussi tenté un démarrage de rhythmbox avec la commande sudo. Quelques radios fonctionnent, mais la plupart affichent également un sens interdit. De plus les radios que j'ai installées n'apparaissent plus dans le menu
Que puis-je faire?
Merci pour vos réponses,
M.
Hors ligne
michelk
Re : la lecture de flux radio ne fonctionne plus(ubuntu 12.10 - rhythmbox)
Bonjour,
Je suis passé à la version 13.04 d'ubuntu, certaines radios fonctionnent mais la plupart ne s'ouvrent pas.
Celles-ci par exemple ne fonctionnent pas:
http://mp3.streampower.be/klaracontinuo-high
http://www.static.rtbf.be/radio/musiq3/ … 3_128k.m3u
Est-ce en rapport avec le type de fichier(la deuxième fonctionnait avant la mise à jour pourtant)?
Une idée?
Hors ligne
michelk
Re : la lecture de flux radio ne fonctionne plus(ubuntu 12.10 - rhythmbox)
Bon, toujours rien, je tente un p'tit UP?
Hors ligne
philoup44
Re : la lecture de flux radio ne fonctionne plus(ubuntu 12.10 - rhythmbox)
Salut
Regardes dans RHYTHMBOX > éditions > Greffons > Configurer les gréffons
si
- Radio FM
est activée ou non ...
peut etre qu'une option a été décochée ... ??
Dernière modification par philoup44 (Le 06/05/2013, à 19:51)
Hors ligne
cricriber
Re : la lecture de flux radio ne fonctionne plus(ubuntu 12.10 - rhythmbox)
Bonjour tout le monde,
Même problème pour moi, pas de lecture ou si début de lecture plantage de rythmbox.
Hors ligne
sono68200
Re : la lecture de flux radio ne fonctionne plus(ubuntu 12.10 - rhythmbox)
Chez moi pas de lecture non plus de radio sur la 13.04. Cela fonctionnait il y a quelques temps. Quand je double clic sur une radio, rien... Quand je séléctionne une radio puis clique sur play, il l'a met en pause, alors qu'elle ne s'est même pas lancée... Puis en recliquant reste sur pause... J'ai essayé Nostalgie, Rires & Chansons...
Membre attitré de la brigade des S.Un peu zinzin sur les bords, sourire est mon quotidien.
Hors ligne
ismael54
Re : la lecture de flux radio ne fonctionne plus(ubuntu 12.10 - rhythmbox)
Idem sous la 13.04 ! On va dire qu'à part lire de la musique rien ne marche malheureusement...
Pour les radios j'ai le même problème que sono68200 mais pour les podcasts aussi, la plupart du temps ça plante avant que j'ai fini de m'y abonner via l'interface, j'ai pu écouter quelques secondes mais il a planté pour x raison
Hors ligne
guigui85
Re : la lecture de flux radio ne fonctionne plus(ubuntu 12.10 - rhythmbox)
Ok, à mon tour (sur le bon topic) et mêmes problèmes constatés depuis que je suis sur la 13.04, à la fois pour les radios et les podcasts. A mon sens, il y a des problèmes de greffons, voire de sources de logiciel qui ont été désactivés pour le passage à "raring". A voir comment ça évolue dans les jours ou semaines qui viennent ?
Le plus dur, c'est de ne pas penser.
Hors ligne
Bob dit l'Âne
Re : la lecture de flux radio ne fonctionne plus(ubuntu 12.10 - rhythmbox)
Bonsoir
J'ai le même problème avec Rythmbox depuis la mise à niveau vers Raring.
Par contre, ça marche très bien pour les flux radio avec VLC, Banshee ou encore Radio Tray.
Revenons à Rythmbox. J'ai essayé dans un terminal et pour moi ça marche avec la commande "sudo rythmbox"
Akoya MD 97860 P7612 Core 2 Duo T6500 NVIDIA Realtek RTL8191SE Wireless LAN GeForce G210M
Ubuntu 14.04 LTS (« The Trusty Tahr », le tahr sûr)
Les paroles s'envolent, les écrits restent !
Hors ligne
guigui85
Re : la lecture de flux radio ne fonctionne plus(ubuntu 12.10 - rhythmbox)
Bonjour,
il fallait être un âne pour ne pas utiliser VLC et les innombrables radios fournies, idem pour les podcasts.
A suivre pour Rhythmbox, donc. Mais ça devient moins urgent du coup, même si le tout en un, c'est plus pratique, quand ça marche....
Le plus dur, c'est de ne pas penser.
Hors ligne
pcouderc
Re : la lecture de flux radio ne fonctionne plus(ubuntu 12.10 - rhythmbox)
Je trouve irritant et pas professionnel qu'après un passage standard à la 13.04 mon fichier radio m3u ne marche plus. Bon je vais revenir à un bon vieux VLC, mais il me faut aller bidouiller ça tous les 6 mois, c'est pénible, on oublie la procédure en 6 mois.
Hors ligne
zniavre
Re : la lecture de flux radio ne fonctionne plus(ubuntu 12.10 - rhythmbox)
je lance la radio via le fichier .m3u, cela ne fonctionne pas (normal ?), je suis l'action par, alt+f2 'killall gvfsd-http' et hop la radio se lance (re-normal ?)
apparement bug connu depuis 2 ou 3 version d'ubuntu .
Vous pouvez y rajouter tout le fûmier que vous pouvez , pour un chêne centenaire ...faut cent ans.
Hors ligne
ptiprince
Re : la lecture de flux radio ne fonctionne plus(ubuntu 12.10 - rhythmbox)
Bonjour,
Pareil pour moi, plus de radios ... c'est triste quand même ....:(
Hors ligne
ptiprince
Re : la lecture de flux radio ne fonctionne plus(ubuntu 12.10 - rhythmbox)
Moi aussi je n'ai plus accès aux radio ni last FM ... bref, comme si rhythmbox n'était plus relié au web (alors que Internet fonctionne très bien) ...
Hors ligne
guigui85
Re : la lecture de flux radio ne fonctionne plus(ubuntu 12.10 - rhythmbox)
Pour ma part, tout refonctionne normalement depuis la 14.04 sans aucune intervention particulière, hormis les mises à jours.
Il faut peut être voir les mises à jours des paquets synaptics qui sont, pour de bonnes raisons, désactivés ou "nettoyés" lors des changements de version.
Dernière modification par guigui85 (Le 27/07/2014, à 11:07)
Le plus dur, c'est de ne pas penser.
Hors ligne |
wouaren
Impossible lancer application python ImportError: No module named gtk
Impossible de lancer n'importe quel programme en python, ils plantent tous...
J'ai fais une vérification de tous mes paquets python, j'ai les mêmes qu'une machine qui arrive a faire marcher les programmes pythons :
Voilà l'erreur fatale :
vincent@ubuntu:~/Desktop/fricorder$ ./fricorder.py Traceback (most recent call last):
File "./fricorder.py", line 28, in ?
import gtk
ImportError: No module named gtk
Ce programme fonctionne : http://forum.ubuntu-fr.org/viewtopic.php?id=22614
Voilà la liste de mes paquets pythons :
diveintopython,gimp-python,python ,python-adns,python-apt,python-cddb,python-clientcookie,python-crypto,python-egenix-mxproxy,
python-egenix-mxstack,python-egenix-mxtexttools,python-egenix-mxtools,python-epydoc,python-eunuchs,
python-examples,python-gadfly,python-gd,python-gdbm,python-gdchart,python-genetic,python-geoip,
python-glade2,python-gmenu,python-gnome2,python-gnome2-extras,python-gnupginterface,
python-gst,python-gtk2,python-htmlgen,python-htmltmpl,python-id3lib,python-imaging,
python-imaging-sane,python-jabber,python-kjbuckets,python-launchpad-integration,
python-ldap,python-minimal,python-musicbrainz,python-mysqldb,python-netcdf,
python-newt,python-numeric,python-osd,python-pam,python-parted,python-pexpect,python-pgsql,
python-pisock,python-pqueue,python-pyao,python-pylibacl,python-pyogg,python-pyopenssl,
python-pyorbit,python-pyvorbis,python-pyxattr,python-reportlab,python-simpletal,python-soappy,
python-sqlite,python-stats,python-syck,python-tk,python-unit,python-uno,python-xdg,python-xml,
python-xmpp,python2.4,python2.4-adns,python2.4-apt,python2.4-cairo,python2.4-clientcookie,
python2.4-crypto,python2.4-dbus,python2.4-dictclient,python2.4-egenix-mxdatetime,
python2.4-egenix-mxproxy,python2.4-egenix-mxstack,python2.4-egenix-mxtexttools,
python2.4-egenix-mxtools,python2.4-epydoc,python2.4-eunuchs,python2.4-examples,python2.4-gadfly,
python2.4-gd,python2.4-gdbm,python2.4-geoip,python2.4-glade2,python2.4-gnome2,
python2.4-gnome2-extras,python2.4-gtk2,python2.4-htmlgen,python2.4-htmltmpl,python2.4-id3lib,
python2.4-imaging,python2.4-imaging-sane,python2.4-jabber,python2.4-kjbuckets,python2.4-ldap,
python2.4-librdf,python2.4-libxml2,python2.4-libxslt1,python2.4-minimal,python2.4-musicbrainz,
python2.4-mysqldb,python2.4-numeric,python2.4-osd,python2.4-pam,python2.4-pexpect,
python2.4-pgsql,python2.4-pycurl,python2.4-pylibacl,python2.4-pyopenssl,python2.4-pyorbit,
python2.4-pyxattr,python2.4-reportlab,python2.4-simpletal,python2.4-sqlite,python2.4-syck,
python2.4-tk,python2.4-unit,python2.4-xml,python2.4-xmpp
love ubuntu
Hors ligne
alain_72
Re : Impossible lancer application python ImportError: No module named gtk
tu n'as pas le paquet python2.4-gtk2 qui est dispo sous synaptic...
ubuntu Breezy Badger 5.10 - kernel linux-K7
AMD Athlon XP 2600 - 512 Mo DDR - HD 80 Go (/) HD 160 Go (/home)
Nvidia Geforce FX 5200 128 Mo
adresse jabber : linux.ubuntu@jabber.org
Hors ligne
wouaren
Re : Impossible lancer application python ImportError: No module named gtk
Bon je veux bien être sympa alain_72 mais il faudrait ouvrir tes yeux et me croire sur parole car en plus je l'ai marqué dans mon post, j'ai ce paquet... !
Une seconde preuve allez...
vincent@ubuntu:~$ sudo apt-get install python2.4-gtk2
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances... Fait
python2.4-gtk2 est déjà la plus récente version disponible.
0 mis à jour, 0 nouvellement installés, 0 à enlever et 0 non mis à jour
Si tu as ou quelqu'un à une autre solution, Merci
Dernière modification par wouaren (Le 06/01/2006, à 22:14)
love ubuntu
Hors ligne
Nim
Re : Impossible lancer application python ImportError: No module named gtk
Il est possible que la commande python de base pointe vers la mauvaise version de python.
etienne@anna ~ $ python -V
T'indique quelle version de python ?
Si ce n'est pas la 2.4, une solution simple est de remettre en place le lien symbolique pour qu'il pointe sur la bonne version.
etienne@anna bin $ cd /usr/bin/
etienne@anna bin $ sudo rm python
etienne@anna bin $ sudo ln -s python2.4 python
Hors ligne |
I've been reading through On the Road this week (which is great, by the way, even if you're worried about being seen as the kind of person who reads On The Road), and was impressed by Kerouac's characteristic stream-of-consciousness writing style. Curious about how it compared mechanically to other beloved authors of mine, I decided to fire up Python and do some basic analysis. Below is the numbers of syllables per sentence in the first hundred sentences of writing samples from a bunch of likable dudes:
(Note: as Reddit user /u/cincodenada points out, these should really be bar graphs since they aren't reflecting time-series or continuous data. Unfortunately, I was having some issues getting the data to render as bar graphs at an acceptable speed.)
Without becoming a full-blown armchair literary critic, there are a bunch of fun observations you can make here:
Dickens and Hemingway fulfill their stereotype of economical prose, with a few elongated digressions. In particular, Hemingway's massive spike -- from The Snows of Kilimanjaro-- is worth quoting:
The cot the man lay on was in the wide shade of a mimosa tree and as he looked out past the shade onto the glare of the plain there were three of the big birds squatted obscenely, while in the sky a dozen more sailed, making quick-moving shadows as they passed.
Kerouac's overwhelming prose comes less from long sentences and more from long thoughts (though there are ample of both).
Retroactive vindication for thinking Milton was absurdly dense when I had to read it in
British Literature. Averaging one hundred syllables a sentence is absurd.
I also put this into a table for a significantly more compact (yet significantly less pretty!) view of the data. Be sure to try clicking the headers:
author words sentences words per sentence flesch-kincaid syllables per word
kerouac 21829 1281 17 81.2110779239 1.28095652572
joyce 7609 686 11 94.1033026679 1.20055197792
hemingway 8930 601 14 89.8165789474 1.21522956327
milton 5381 83 64 49.7284473146 1.08920275042
dickens 5542 288 19 85.2575784915 1.20913027788
fitzgerald 5651 323 17 80.5177101398 1.28915236241
nabokov 9942 407 24 66.8328756789 1.36692818346
vonnegut 2417 237 10 83.9083347125 1.33305750931
More proof that Milton is ridiculous and that Flesch-Kincaid is not exactly the most airtight of measurements -- Vonnegut harder to read than Joyce? Really? (And Ulysseys was the writing sample, mind you.)
From a programming perspective, nothing of note -- feel free to check out the script yourself (though you'll have to grab the writing samples on your own, as I'm too lazy to upload them.) I am, however, rather proud of my method of finding the number of syllables in a word:
from curses.ascii import isdigit
from nltk.corpus import cmudict as d
is_word = lambda word: isdigit(word[-1])
num_syllables = lambda word: len(filter(is_word, word))
return max(map(num_syllables, d[lowercase]))
|
I am trying to import a module in python that contains the following lines:
#setup.py
def isnumber(pause):
try:
float(pause)
return True
except ValueError:
return False
I am trying to call it like this:
#program.py
import setup
but I get the following error:
Traceback (most recent call last):
File "C:\Users\rthompson@iingen.unam.mx\ralph\programas\python\scraper\release\program.py", line 4, in <module>
import setup
File "C:\Users\rthompson@iingen.unam.mx\ralph\programas\python\lib\setup.py", line 55, in <module>
download_url="http://www.crummy.com/software/BeautifulSoup/download/"
File "C:\Users\rthompson@iingen.unam.mx\ralph\programas\python\lib\distutils\core.py", line 140, in setup
raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg
SystemExit: usage: program.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: program.py --help [cmd1 cmd2 ...]
or: program.py --help-commands
or: program.py cmd --help
error: no commands supplied
Line 55 in setup.py corresponds to return True in the code above.
Without the isnumber function the import works as expected.
Can anyone see what I'm doing wrong? |
I import into a panda DataFrame a directory of |-delimited.dat files. The following code works, but I eventually run out of RAM with a MemoryError:.
import pandas as pd
import glob
temp = []
dataDir = 'C:/users/richard/research/data/edgar/masterfiles'
for dataFile in glob.glob(dataDir + '/master_*.dat'):
print dataFile
temp.append(pd.read_table(dataFile, delimiter='|', header=0))
masterAll = pd.concat(temp)
Is there a more memory efficient approach? Or should I go whole hog to a database? (I will move to a database eventually, but I am baby stepping my move to pandas.) Thanks!
FWIW, here is the head of an example .dat file:
cik|cname|ftype|date|fileloc
1000032|BINCH JAMES G|4|2011-03-08|edgar/data/1000032/0001181431-11-016512.txt
1000045|NICHOLAS FINANCIAL INC|10-Q|2011-02-11|edgar/data/1000045/0001193125-11-031933.txt
1000045|NICHOLAS FINANCIAL INC|8-K|2011-01-11|edgar/data/1000045/0001193125-11-005531.txt
1000045|NICHOLAS FINANCIAL INC|8-K|2011-01-27|edgar/data/1000045/0001193125-11-015631.txt
1000045|NICHOLAS FINANCIAL INC|SC 13G/A|2011-02-14|edgar/data/1000045/0000929638-11-00151.txt
|
I am writing a Python C extension on a very old Red Hat system. The system has zlib 1.2.3, which does not correctly support large files. Unfortunately, I can't just upgrade the system zlib to a newer version, since some of the packages poke into internal zlib structures and that breaks on newer zlib versions.
I would like to build my extension so that all the zlib calls (gzopen(), gzseek() etc.) are resolved to a custom zlib that I install in my user directory, without affecting the rest of the Python executable and other extensions.
I have tried statically linking in libz.a by adding libz.a to the gcc command line during linking, but it did not work (still cannot create large files using gzopen() for example). I also tried passing -z origin -Wl,-rpath=/path/to/zlib -lz to gcc, but that also did not work.
Since newer versions of zlib are still named zlib 1.x, the soname is the same, so I think symbol versioning would not work. Is there a way to do what I want to do?
I am on a 32-bit Linux system. Python version is 2.6, which is custom-built.
Edit:
I created a minimal example. I am using Cython (version 0.19.1).
File gztest.pyx:
from libc.stdio cimport printf, fprintf, stderr
from libc.string cimport strerror
from libc.errno cimport errno
from libc.stdint cimport int64_t
cdef extern from "zlib.h":
ctypedef void *gzFile
ctypedef int64_t z_off_t
int gzclose(gzFile fp)
gzFile gzopen(char *path, char *mode)
int gzread(gzFile fp, void *buf, unsigned int n)
char *gzerror(gzFile fp, int *errnum)
cdef void print_error(void *gzfp):
cdef int errnum = 0
cdef const char *s = gzerror(gzfp, &errnum)
fprintf(stderr, "error (%d): %s (%d: %s)\n", errno, strerror(errno), errnum, s)
cdef class GzFile:
cdef gzFile fp
cdef char *path
def __init__(self, path, mode='rb'):
self.path = path
self.fp = gzopen(path, mode)
if self.fp == NULL:
raise IOError('%s: %s' % (path, strerror(errno)))
cdef int read(self, void *buf, unsigned int n):
cdef int r = gzread(self.fp, buf, n)
if r <= 0:
print_error(self.fp)
return r
cdef int close(self):
cdef int r = gzclose(self.fp)
return 0
def read_test():
cdef GzFile ifp = GzFile('foo.gz')
cdef char buf[8192]
cdef int i, j
cdef int n
errno = 0
for 0 <= i < 0x200:
for 0 <= j < 0x210:
n = ifp.read(buf, sizeof(buf))
if n <= 0:
break
if n <= 0:
break
printf('%lld\n', <long long>ifp.tell())
printf('%lld\n', <long long>ifp.tell())
ifp.close()
File setup.py:
import sys
import os
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
if __name__ == '__main__':
if 'CUSTOM_GZ' in os.environ:
d = {
'include_dirs': ['/home/alok/zlib_lfs/include'],
'extra_objects': ['/home/alok/zlib_lfs/lib/libz.a'],
'extra_compile_args': ['-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -g3 -ggdb']
}
else:
d = {'libraries': ['z']}
ext = Extension('gztest', sources=['gztest.pyx'], **d)
setup(name='gztest', cmdclass={'build_ext': build_ext}, ext_modules=[ext])
My custom zlib is in /home/alok/zlib_lfs (zlib version 1.2.8):
$ ls ~/zlib_lfs/lib/
libz.a libz.so libz.so.1 libz.so.1.2.8 pkgconfig
To compile the module using this libz.a:
$ CUSTOM_GZ=1 python setup.py build_ext --inplace
running build_ext
cythoning gztest.pyx to gztest.c
building 'gztest' extension
gcc -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/alok/zlib_lfs/include -I/opt/include/python2.6 -c gztest.c -o build/temp.linux-x86_64-2.6/gztest.o -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -g3 -ggdb
gcc -shared build/temp.linux-x86_64-2.6/gztest.o /home/alok/zlib_lfs/lib/libz.a -L/opt/lib -lpython2.6 -o /home/alok/gztest.so
gcc is being passed all the flags I want (adding full path to libz.a, large file flags, etc.).
To build the extension without my custom zlib, I can compile without CUSTOM_GZ defined:
$ python setup.py build_ext --inplace
running build_ext
cythoning gztest.pyx to gztest.c
building 'gztest' extension
gcc -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/opt/include/python2.6 -c gztest.c -o build/temp.linux-x86_64-2.6/gztest.o
gcc -shared build/temp.linux-x86_64-2.6/gztest.o -L/opt/lib -lz -lpython2.6 -o /home/alok/gztest.so
We can check the size of the gztest.so files:
$ stat --format='%s %n' original/gztest.so custom/gztest.so
62398 original/gztest.so
627744 custom/gztest.so
So, the statically linked file is much larger, as expected.
I can now do:
>>> import gztest
>>> gztest.read_test()
and it will try to read foo.gz in the current directory.
When I do that using non-statically linked gztest.so, it works as expected until it tries to read more than 2 GB.
When I do that using statically linked gztest.so, it dumps core:
$ python -c 'import gztest; gztest.read_test()'
error (2): No such file or directory (0: )
0
Segmentation fault (core dumped)
The error about No such file or directory is misleading -- the file exists and is gzopen() actually returns successfully. gzread() fails though.
Here is the gdb backtrace:
(gdb) bt
#0 0xf730eae4 in free () from /lib/libc.so.6
#1 0xf70725e2 in ?? () from /lib/libz.so.1
#2 0xf6ce9c70 in __pyx_f_6gztest_6GzFile_close (__pyx_v_self=0xf6f75278) at gztest.c:1140
#3 0xf6cea289 in __pyx_pf_6gztest_2read_test (__pyx_self=<optimized out>) at gztest.c:1526
#4 __pyx_pw_6gztest_3read_test (__pyx_self=0x0, unused=0x0) at gztest.c:1379
#5 0xf769910d in call_function (oparg=<optimized out>, pp_stack=<optimized out>) at Python/ceval.c:3690
#6 PyEval_EvalFrameEx (f=0x8115c64, throwflag=0) at Python/ceval.c:2389
#7 0xf769a3b4 in PyEval_EvalCodeEx (co=0xf6faada0, globals=0xf6ff81c4, locals=0xf6ff81c4, args=0x0, argcount=0, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2968
#8 0xf769a433 in PyEval_EvalCode (co=0xf6faada0, globals=0xf6ff81c4, locals=0xf6ff81c4) at Python/ceval.c:522
#9 0xf76bbe1a in run_mod (arena=<optimized out>, flags=<optimized out>, locals=<optimized out>, globals=<optimized out>, filename=<optimized out>, mod=<optimized out>) at Python/pythonrun.c:1335
#10 PyRun_StringFlags (str=0x80a24c0 "import gztest; gztest.read_test()\n", start=257, globals=0xf6ff81c4, locals=0xf6ff81c4, flags=0xffbf2888) at Python/pythonrun.c:1298
#11 0xf76bd003 in PyRun_SimpleStringFlags (command=0x80a24c0 "import gztest; gztest.read_test()\n", flags=0xffbf2888) at Python/pythonrun.c:957
#12 0xf76ca1b9 in Py_Main (argc=1, argv=0xffbf2954) at Modules/main.c:548
#13 0x080485b2 in main ()
One of the problems seems to be that the second line in the backtrace refers to libz.so.1! If I do ldd gztest.so, I get, among other lines:
libz.so.1 => /lib/libz.so.1 (0xf6f87000)
I am not sure why that is happening though.
Edit 2:
I ended up doing the following:
compiled my custom zlib with all the symbols exported with a z_prefix.zlib'sconfigurescript makes this very easy: just run./configure --zprefix ....
called gzopen64()instead ofgzopen()in my Cython code. This is because I wanted to make sure I am using the correct "underlying" symbol.
used z_off64_texplicitly.
statically link my custom zlib.ainto the shared library generated by Cython. I used'-Wl,--whole-archive /home/alok/zlib_lfs_z/lib/libz.a -Wl,--no-whole-archive'while linking with gcc to achieve that. There might be other ways or this might not be needed but it seemed the simplest way to make sure the correct library gets used.
With the above changes, large files work while the rest of the Python extension modules/processes work as before. |
I wouldn't suggest using such templates in production code, because
Explicit is better than implicit.
For throw-away prototypes it might be acceptable. Here is an example from the python recipes:
It defines a decorator with can be attached to __init__:
def injectArguments(inFunction):
"""
This function allows to reduce code for initialization
of parameters of a method through the @-notation
You need to call this function before the method in this way:
@injectArguments
"""
def outFunction(*args, **kwargs):
_self = args[0]
_self.__dict__.update(kwargs)
# Get all of argument's names of the inFunction
_total_names = \
inFunction.func_code.co_varnames[1:inFunction.func_code.co_argcount]
# Get all of the values
_values = args[1:]
# Get only the names that don't belong to kwargs
_names = [n for n in _total_names if not kwargs.has_key(n)]
# Match names with values and update __dict__
d={}
for n, v in zip(_names,_values):
d[n] = v
_self.__dict__.update(d)
inFunction(*args,**kwargs)
return outFunction
A test:
class Test:
@injectArguments
def __init__(self, name, surname):
pass
if __name__=='__main__':
t = Test('mickey', surname='mouse')
print t.name, t.surname
|
I am trying to connect directly to the video stream of an IP video server (the "Nuuo" IP Server).
Their instruction manual gives the URL of the 'home' - a page which installs a cute little activeX control that handles all interaction with the actual video server.
I need the URL of that internal server. [I don't need the added controls offered by the activeX control, and am in an environment where Internet Explorer is not available. I just want the stream]
I tried Wireshark, which captured all the packets, but does not show me the complete URL of the different pages. [ie: if the physical device is at 212.234.56.456, it shows the same URL whether I connect to the home page (212.234.56.456/home.html), to the video server (probably something like 212.234.56.456/video.amp), or to anything else within the device.]
Despite much head-scratching and searching their site and the manual, I cannot understand how to get the whole URL of the server.
Can someone please direct me to a tutorial or page of instructions - or just spell out how to do this?
Wireshark does not have to be the solution - I will happily use something else (tried Fiddler, but don't know to configure it - by default it catches none of this traffic)
Thanks
Edit: The protocol is TCP
Video port: 8000 [There is an option in the server to change the port. The default is 8000]
I am trying to connect to the video stream using something like VLC or RealPlayer [for the purpose of re-streaming] instead of the activeX control it comes with. I do NOT KNOW anything about TCP, other than that it shows up in the packet attached. The server is encoding to MPEG 4 [h.264], and should be streaming RTSP://
I have read of many many people doing this successfully with an Axis server (They connect to rtsp://[server-ip-address]:554/axis-media/media.amp with VLC), and with an Arecont Server (rtsp://[server-ip-address]/h264.sdp). Obviously, this page does not exist on the Nuuo server I am using, which is designed to compete with the Axis device.
I loaded the page, started Wireshark, then pressed the play button on the ActiveXControl (starting the video). Below is the first packet Wireshark caught [of many, it is the request for the video]:
No. Time Source Destination Protocol Info
53 7.198090 192.168.1.4 212.143.234.227 TCP 4734 > irdmi [SYN] Seq=0 Win=65535 Len=0 MSS=1460
Frame 53 (62 bytes on wire, 62 bytes captured)
Arrival Time: Jul 8, 2009 13:24:35.008644000
[Time delta from previous captured frame: 0.048542000 seconds]
[Time delta from previous displayed frame: 7.198090000 seconds]
[Time since reference or first frame: 7.198090000 seconds]
Frame Number: 53
Frame Length: 62 bytes
Capture Length: 62 bytes
[Frame is marked: False]
[Protocols in frame: eth:ip:tcp]
[Coloring Rule Name: TCP SYN/FIN]
[Coloring Rule String: tcp.flags & 0x02 || tcp.flags.fin == 1]
Ethernet II, Src: Intel_66:1e:41 (00:19:d1:66:1e:41), Dst: GigasetC_49:05:10 (00:21:04:49:05:10)
Destination: GigasetC_49:05:10 (00:21:04:49:05:10)
Address: GigasetC_49:05:10 (00:21:04:49:05:10)
.... ...0 .... .... .... .... = IG bit: Individual address (unicast)
.... ..0. .... .... .... .... = LG bit: Globally unique address (factory default)
Source: Intel_66:1e:41 (00:19:d1:66:1e:41)
Address: Intel_66:1e:41 (00:19:d1:66:1e:41)
.... ...0 .... .... .... .... = IG bit: Individual address (unicast)
.... ..0. .... .... .... .... = LG bit: Globally unique address (factory default)
Type: IP (0x0800)
Internet Protocol, Src: 192.168.1.4 (192.168.1.4), Dst: 212.143.234.227 (212.143.234.227)
Version: 4
Header length: 20 bytes
Differentiated Services Field: 0x00 (DSCP 0x00: Default; ECN: 0x00)
0000 00.. = Differentiated Services Codepoint: Default (0x00)
.... ..0. = ECN-Capable Transport (ECT): 0
.... ...0 = ECN-CE: 0
Total Length: 48
Identification: 0x816c (33132)
Flags: 0x04 (Don't Fragment)
0... = Reserved bit: Not set
.1.. = Don't fragment: Set
..0. = More fragments: Not set
Fragment offset: 0
Time to live: 128
Protocol: TCP (0x06)
Header checksum: 0xf83b [correct]
[Good: True]
[Bad : False]
Source: 192.168.1.4 (192.168.1.4)
Destination: 212.143.234.227 (212.143.234.227)
Transmission Control Protocol, Src Port: 4734 (4734), Dst Port: irdmi (8000), Seq: 0, Len: 0
Source port: 4734 (4734)
Destination port: irdmi (8000)
[Stream index: 3]
Sequence number: 0 (relative sequence number)
Header length: 28 bytes
Flags: 0x02 (SYN)
0... .... = Congestion Window Reduced (CWR): Not set
.0.. .... = ECN-Echo: Not set
..0. .... = Urgent: Not set
...0 .... = Acknowledgement: Not set
.... 0... = Push: Not set
.... .0.. = Reset: Not set
.... ..1. = Syn: Set
[Expert Info (Chat/Sequence): Connection establish request (SYN): server port irdmi]
[Message: Connection establish request (SYN): server port irdmi]
[Severity level: Chat]
[Group: Sequence]
.... ...0 = Fin: Not set
Window size: 65535
Checksum: 0x378c [validation disabled]
[Good Checksum: False]
[Bad Checksum: False]
Options: (8 bytes)
Maximum segment size: 1460 bytes
NOP
NOP
SACK permitted
|
Apache Libcloud is a Python library that aims to provide a single interface for various cloud services, such as computing and storage. It has a pretty extensive list of providers, and can mitigate vendor lock-in for common tasks such as creating, rebooting, and destroying computing instances.
Perhaps one of the lesser known superpowers of libcloud is the inclusion of instance costs for many of the providers. While these numbers are not provided by the APIs themselves, but rather built into the code, the committers do their best to keep these numbers up to date.
With this in mind, we can render some neat 10,000-foot views.
“You can’t do much without measuring.” - Coda Hale
Single-click provisioning and auto-scaling (for varying definitions) are becoming easy if not prominent with today’s tools. In this fast-paced world, getting a grip on exact usage can be a powerful and important metric to have, and better yet, to have automated.
Imagine a homegrown Google PowerMeter for your EC2 farm or Linode Hadoop cluster. Graphite immediately comes to mind for receiving, storing and displaying data. If not, replace Graphite with your favorite datastore, and couple it with an in-browser visualization framework such as d3.js or Crossfilter and the possibilities are plentiful.
What we can glean from libcloud is a base number and a minimum cost. Additional considerations such as bandwidth, special-type utilities such as load balancers services, and special types of pricing such as EC2’s Spot Instances will fall outside the scope of our basic calculations.
We can generate a table of monthly costs, broken down by both instance sizes and by individual servers. The provider in this example will be Rackspace Cloud Servers. Costs will be extrapolated out to per-month costs, or if you prefer more granularity, you can tweak the multiplier and calculate a per-day cost, for example.
First, the code (gist here):
#!/usr/bin/env python import locale from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver RACKSPACE_USER = 'YOUR_USERNAME_HERE' RACKSPACE_KEY = 'YOUR_API_KEY_HERE' HOURS_PER_MONTH = 730.484 # according to magical google calculator DELIMITER = '\t' # helper to convert items in list to str, and join with DELIMITER def assemble_line(words): return DELIMITER.join([str(word) for word in words]) def format_price(price): # for US-style dollar amounts locale.setlocale(locale.LC_ALL, 'en_US') return '${}'.format(locale.format('%0.2f', price, grouping=True)) def main(): Driver = get_driver(Provider.RACKSPACE) conn = Driver(RACKSPACE_USER, RACKSPACE_KEY) nodes = conn.list_nodes() sizes = conn.list_sizes() nodes_by_size = {} summary = [] output = [] # sort nodes by name nodes.sort(lambda x, y: cmp(x.name, y.name)) for node in nodes: size = [s for s in sizes if s.id == node.extra['flavorId']][0] size_name = str(size.ram) if size in nodes_by_size: nodes_by_size[size].append(node) else: nodes_by_size[size] = [node] month_price = size.price * HOURS_PER_MONTH output.append((node.name, size_name, format_price(month_price))) # calculate total monthly price, broken down by size for size, nodes in nodes_by_size.iteritems(): num_nodes = len(nodes) month_price = size.price * HOURS_PER_MONTH nodes_total_price = month_price * num_nodes summary.append((size.ram, # size num_nodes, # number of nodes format_price(month_price), # price per node per month format_price(nodes_total_price))) # total price per month total_num_nodes = sum(len(nodes) for nodes in nodes_by_size.values()) total_price = sum(size.price * HOURS_PER_MONTH * len(nodes) for size, nodes in nodes_by_size.iteritems()) summary.append(('', total_num_nodes, '', format_price(total_price))) # output print('Summary') print(assemble_line(('Size', 'Nodes', '$/Nodes/Month', '$/Month'))) print('\n'.join([assemble_line(line) for line in summary])) print print('Inventory') print('\n'.join([assemble_line(line) for line in output])) if __name__ == '__main__': main()
We begin by getting the Provider.RACKSPACE driver, then making a connection with our username and API key, and finally, listing our existing nodes and the available sizes.
From there we loop through all the existing nodes and populate the dict nodes_by_size where the key is the instance size, and the values are lists of the instances. Note that the size of the instance is determined by a semi-cryptic list comprehension:
size = [s for s in sizes if s.id == node.extra['flavorId']][0]
This searches through the list of sizes for one that matches the node’s size, which is buried away in the flavorId value in the node.extra. This is specific to Rackspace; for example, EC2 would use instanceId instead of flavorId.
We also populate a list called output which will have the node’s name, its instance size (by way of RAM), and the extrapolated monthly cost.
Next, we loop through the nodes_by_size dict and do a simple rollup, saving a breakdown of the different instance sizes, how many per category, and the cost breakdown.
At the very end, we print out summary and output.
The tabulated result is pretty simple, and by changing DELIMITER to a comma, you can have a poor man’s CSV.
Summary Size Nodes $/Nodes/Month $/Month 256 2 $10.96 $21.91 512 5 $21.91 $109.57 7 $131.48 Inventory alkazar0 512 $21.91 flexo0 512 $21.91 kif1 256 $10.96 kif2 256 $10.96 leela6 512 $21.91 nibbler3 512 $21.91 nibbler4 512 $21.91
Thus, after the initial OAuth setup for GoogleCL, one can simply do:
$ ./bookkeeping.py > inventory.tsv && \ google docs upload inventory.tsv
Infrastructures come in many shapes and sizes with varying levels of flux. Measuring costs is hardly a glamorous or fun task, but can reap long-term benefits and lead to smarter decision making if done properly. ∪ |
Como fazer um cabo GPIO
Vamos fazer um cabo de interface com conectador GPIO. Este é o conector P1 do Raspberry Pi. Isto irá permitir-nos a ligar os motores, LEDs, botões e outros componentes físicos:
É um cabo de fita com 26 fios. Isto é semelhante a cabo IDE (ou ATA) de 40 vias para disco rígido (não ATA66/133 de 80 vias):
Cabo IDE/ATA original de 40 vias
Queremos 2 conectores, não 3. Com um cabo que tem três conectores, cortamos uma seção.
Corte com uma tesoura.
Com uma faca X-acto, vamos dividir o cabo em duas partes: uma de 26 vias e uma de 14 vias.
Marcar com uma caneta
dividir em duas partes
Fizemos um corte com uma serra (ou roda de corte de tipo Dremel).
conector serrada
A remoção da porção da direita
Nós terminamos o corte. Agora você pode conectar o cabo ao computador:
Conexão
A conexão é simples:
LED vermelho e LED verde, perna curta -> terceiro buraco no lado esquerdo.
LED vermelho, perna comprida -> segundo buraco no lado direito.
LED verde, perna comprida -> terceiro buraco no lado direito.
#!/usr/bin/env python
""" Setting up two pins for output """
import RPi.GPIO as gpio
import time
PINR = 0 # this should be 2 on a V2 RPi
PING = 1 # this should be 3 on a V2 RPi
gpio.setmode(gpio.BCM) # broadcom mode
gpio.setup(PINR, gpio.OUT) # set up red LED pin to OUTput
gpio.setup(PING, gpio.OUT) # set up green LED pin to OUTput
#Make the two LED flash on and off forever
try:
while True:
gpio.output(PINR, gpio.HIGH)
gpio.output(PING, gpio.LOW)
time.sleep(1)
gpio.output(PINR, gpio.LOW)
gpio.output(PING, gpio.HIGH)
time.sleep(1)
except KeyboardInterrupt:
gpio.cleanup()
Coloque este código em um arquivo chamado flashled.py.
Em operação
Normalmente, é necessário proteger um LED com um resistor para limitar a amperagem, mas como se fez este de forma
intermitente, para testar a cabo, não há nenhum risco.
Para uso
prolongado,
deve haver um resistor em sériede 220 Ohm a 360 Ohm.
$ chmod +x flashled.py $ sudo ./flashled.py
Control-Cpara interromper.
LED vermelho
LED verde |
I have a directory structure:
example.pytemplates/ __init__.py a.py b.py
a.py and b.py have only one class, named the same as the file (because they are cheetah templates). For purely style reasons, I want to be able to import and use these classes in example.py like so:
import templates
t = templates.a()
Right now I do that by having this in the template folder's __init__.py:
__all__ = ["a", "b"]
from . import *
However, this seems pretty poor (and maybe superfluous), and doesn't even do what I want, as I have to use the classes like this:
t = templates.a.a()
Thoughts? |
I'm trying to improve the speed of a function that calculates the normalized cross-correlation between a search image and a template image by using the anfft module, which provides Python bindings for the FFTW C library and seems to be ~2-3x quicker than scipy.fftpack for my purposes.
When I take the FFT of my template, I need the result to be padded to the same size as my search image so that I can convolve them. Using scipy.fftpack.fftn I would just use the shape parameter to do padding/truncation, but anfft.fftn is more minimalistic and doesn't do any zero-padding itself.
When I try and do the zero padding myself, I get a very different result to what I get using shape. This example uses just scipy.fftpack, but I have the same problem with anfft:
import numpy as np
from scipy.fftpack import fftn
from scipy.misc import lena
img = lena()
temp = img[240:281,240:281]
def procrustes(a,target,padval=0):
# Forces an array to a target size by either padding it with a constant or
# truncating it
b = np.ones(target,a.dtype)*padval
aind = [slice(None,None)]*a.ndim
bind = [slice(None,None)]*a.ndim
for dd in xrange(a.ndim):
if a.shape[dd] > target[dd]:
diff = (a.shape[dd]-b.shape[dd])/2.
aind[dd] = slice(np.floor(diff),a.shape[dd]-np.ceil(diff))
elif a.shape[dd] < target[dd]:
diff = (b.shape[dd]-a.shape[dd])/2.
bind[dd] = slice(np.floor(diff),b.shape[dd]-np.ceil(diff))
b[bind] = a[aind]
return b
# using scipy.fftpack.fftn's shape parameter
F1 = fftn(temp,shape=img.shape)
# doing my own zero-padding
temp_padded = procrustes(temp,img.shape)
F2 = fftn(temp_padded)
# these results are quite different
np.allclose(F1,F2)
I suspect I'm probably making a very basic mistake, since I'm not overly familiar with the discrete Fourier transform. |
def _table_(request,id,has_permissions):
dict = {}
dict.update(get_newdata(request,rid))
return render_to_response('home/_display.html',context_instance=RequestContext(request,{'dict': dict, 'rid' : rid, 'has_permissions' : str(has_permissions)}))
In templates the code is as,
{% if has_permissions == "1" %}
<input type="button" value="Edit" id="edit" onclick="javascript:edit('{{id}}')" style="display:inline;"/>
{% endif %}
There is a template error in has_permissions line. Can any 1 tell me what is wrong here.has_permissions has the value 1 or 0. |
I have 3d mesh and I would like to draw each face a 2d shape.
What I have in mind is this: for each face 1. access the face normal 2. get a rotation matrix from the normal vector 3. multiply each vertex to the rotation matrix to get the vertices in a '2d like ' plane 4. get 2 coordinates from the transformed vertices
I don't know if this is the best way to do this, so any suggestion is welcome.
At the moment I'm trying to get a rotation matrix from the normal vector, how would I do this ?
UPDATE:
Here is a visual explanation of what I need:
At the moment I have quads, but there's no problem converting them into triangles.
I want to rotate the vertices of a face, so that one of the dimensions gets flattened.
I also need to store the original 3d rotation of the face. I imagine that would be inverse rotation of the face normal.
I think I'm a bit lost in space :)
Here's a basic prototype I did using Processing:
void setup(){
size(400,400,P3D);
background(255);
stroke(0,0,120);
smooth();
fill(0,120,0);
PVector x = new PVector(1,0,0);
PVector y = new PVector(0,1,0);
PVector z = new PVector(0,0,1);
PVector n = new PVector(0.378521084785,0.925412774086,0.0180059205741);//normal
PVector p0 = new PVector(0.372828125954,-0.178844243288,1.35241031647);
PVector p1 = new PVector(-1.25476706028,0.505195975304,0.412718296051);
PVector p2 = new PVector(-0.372828245163,0.178844287992,-1.35241031647);
PVector p3 = new PVector(1.2547672987,-0.505196034908,-0.412717700005);
PVector[] face = {p0,p1,p2,p3};
PVector[] face2d = new PVector[4];
PVector nr = PVector.add(n,new PVector());//clone normal
float rx = degrees(acos(n.dot(x)));//angle between normal and x axis
float ry = degrees(acos(n.dot(y)));//angle between normal and y axis
float rz = degrees(acos(n.dot(z)));//angle between normal and z axis
PMatrix3D r = new PMatrix3D();
//is this ok, or should I drop the builtin function, and add
//the rotations manually
r.rotateX(rx);
r.rotateY(ry);
r.rotateZ(rz);
print("original: ");println(face);
for(int i = 0 ; i < 4; i++){
PVector rv = new PVector();
PVector rn = new PVector();
r.mult(face[i],rv);
r.mult(nr,rn);
face2d[i] = PVector.add(face[i],rv);
}
print("rotated: ");println(face2d);
//draw
float scale = 100.0;
translate(width * .5,height * .5);//move to centre, Processing has 0,0 = Top,Lef
beginShape(QUADS);
for(int i = 0 ; i < 4; i++){
vertex(face2d[i].x * scale,face2d[i].y * scale,face2d[i].z * scale);
}
endShape();
line(0,0,0,nr.x*scale,nr.y*scale,nr.z*scale);
//what do I do with this ?
float c = cos(0), s = sin(0);
float x2 = n.x*n.x,y2 = n.y*n.y,z2 = n.z*n.z;
PMatrix3D m = new PMatrix3D(x2+(1-x2)*c, n.x*n.y*(1-c)-n.z*s, n.x*n.z*(1-c)+n.y*s, 0,
n.x*n.y*(1-c)+n.z*s,y2+(1-y2)*c,n.y*n.z*(1-c)-n.x*s,0,
n.x*n.y*(1-c)-n.y*s,n.x*n.z*(1-c)+n.x*s,z2-(1-z2)*c,0,
0,0,0,1);
}
Update
Sorry if I'm getting annoying, but I don't seem to get it.
Here's a bit of python using Blender's API:
import Blender
from Blender import *
import math
from math import sin,cos,radians,degrees
def getRotMatrix(n):
c = cos(0)
s = sin(0)
x2 = n.x*n.x
y2 = n.y*n.y
z2 = n.z*n.z
l1 = x2+(1-x2)*c, n.x*n.y*(1-c)+n.z*s, n.x*n.y*(1-c)-n.y*s
l2 = n.x*n.y*(1-c)-n.z*s,y2+(1-y2)*c,n.x*n.z*(1-c)+n.x*s
l3 = n.x*n.z*(1-c)+n.y*s,n.y*n.z*(1-c)-n.x*s,z2-(1-z2)*c
m = Mathutils.Matrix(l1,l2,l3)
return m
scn = Scene.GetCurrent()
ob = scn.objects.active.getData(mesh=True)#access mesh
out = ob.name+'\n'
#face0
f = ob.faces[0]
n = f.v[0].no
out += 'face: ' + str(f)+'\n'
out += 'normal: ' + str(n)+'\n'
m = getRotMatrix(n)
m.invert()
rvs = []
for v in range(0,len(f.v)):
out += 'original vertex'+str(v)+': ' + str(f.v[v].co) + '\n'
rvs.append(m*f.v[v].co)
out += '\n'
for v in range(0,len(rvs)):
out += 'original vertex'+str(v)+': ' + str(rvs[v]) + '\n'
f = open('out.txt','w')
f.write(out)
f.close
All I do is get the current object, access the first face, get the normal, get the vertices, calculate the rotation matrix, invert it, then multiply it by each vertex. Finally I write a simple output.
Here's the output for a default plane for which I rotated all the vertices manually by 30 degrees:
Plane.008
face: [MFace (0 3 2 1) 0]
normal: [0.000000, -0.499985, 0.866024](vector)
original vertex0: [1.000000, 0.866025, 0.500000](vector)
original vertex1: [-1.000000, 0.866026, 0.500000](vector)
original vertex2: [-1.000000, -0.866025, -0.500000](vector)
original vertex3: [1.000000, -0.866025, -0.500000](vector)
rotated vertex0: [1.000000, 0.866025, 1.000011](vector)
rotated vertex1: [-1.000000, 0.866026, 1.000012](vector)
rotated vertex2: [-1.000000, -0.866025, -1.000012](vector)
rotated vertex3: [1.000000, -0.866025, -1.000012](vector)
Here's the first face of the famous Suzanne mesh:
Suzanne.001
face: [MFace (46 0 2 44) 0]
normal: [0.987976, -0.010102, 0.154088](vector)
original vertex0: [0.468750, 0.242188, 0.757813](vector)
original vertex1: [0.437500, 0.164063, 0.765625](vector)
original vertex2: [0.500000, 0.093750, 0.687500](vector)
original vertex3: [0.562500, 0.242188, 0.671875](vector)
rotated vertex0: [0.468750, 0.242188, -0.795592](vector)
rotated vertex1: [0.437500, 0.164063, -0.803794](vector)
rotated vertex2: [0.500000, 0.093750, -0.721774](vector)
rotated vertex3: [0.562500, 0.242188, -0.705370](vector)
The vertices from the Plane.008 mesh are altered, the ones from Suzanne.001's mesh aren't. Shouldn't they ? Should I expect to get zeroes on one axis ? Once I got the rotation matrix from the normal vector, what is the rotation on x,y,z ?
Note: 1. Blender's Matrix supports the * operator 2.In Blender's coordinate system Z point's up. It looks like a right handed system, rotated 90 degrees on X.
Thanks |
Okay so what I'm doing is a somewhat simple contour plot yet I am running into trouble with the data I have. I've searched everywhere for an answer and mostly what I get are links to simple contour plotting examples using matplotlib which have not been very helpful.
What I need is a contour plot of the variables a, b, rms. both a and b run from -3 to 3 in 0.1 intervals and rms is calculated using the code below. I've attempted to calculate the rms values using the X and Y derived from the meshgrid() of the a and b ranges but this will not work with the calculations I have.
from numpy import *
from pylab import *
import matplotlib.pyplot as plt
p, pdot, s400, dist=loadtxt("cc45list.txt", usecols=(1,2,3,4), unpack=True)
n=45
for a in arange(-3, 3.1, 0.1):
for b in arange(-3, 3.1, 0.1):
c=(p**a)*(pdot**b)
d=(s400)*(dist**2)
s_c=sum(c)
s_d=sum(d)
s_cd=sum(c*d)
s_csqr=sum(c**2)
k=(n*(s_cd)-(s_c*s_d))/(n*(s_csqr)-((s_c)**2))
L_p=(k)*(p**a)*(pdot**b)
rms=sqrt((sum((L_p-d)**2))/n)
My advisor has suggested using two for loops to fill the arrays needed for the contour plots for a, b, and rms but (as I am new to python if you cannot tell) I have really no idea how to accomplish this. Apologies if this question is somewhat basic but I'm honestly lost. Any help or suggestions, even if they are minor, would be of great help. Thanks |
Does anybody know a Python module to easily extract temporal expressions such as 12/01/2011 and Monday, 12/3/1987 or others (in English format)?
Would like to avoid to build a huge set of regex.
In the standard library you won't find something comprehensive, but if you install dateutils, you can do this:
>>> from dateutils import parser
>>> parser.parse('January 12, 2012').strftime('%s')
'1326315600'
>>> parser.parse('01/12/2012').strftime('%s')
'1326315600'
>>> parser.parse('Sunday, 16/09/2012').strftime('%s')
'1347742800'
Martijn had a point, so here is the normal representation - which is
>>> parser.parse('Sunday, 16/09/2012')
datetime.datetime(2012, 9, 16, 0, 0)
>>> parser.parse('01/12/2012')
datetime.datetime(2012, 1, 12, 0, 0)
>>> parser.parse('January 12, 2012')
datetime.datetime(2012, 1, 12, 0, 0)
Use the standard
Example:
In : datetime.datetime.strptime("12/01/2012", "%m/%d/%Y")
Out: datetime.datetime(2012, 12, 1, 0, 0)
|
bertrand47
[Résolu] Duplicate sources list
J'ai depuis quelques jours une erreur "duplicate sources list", visiblement du à un doublon i386 et amd64. J'ai une installation amd64.
W: Duplicate sources.list entry http://security.ubuntu.com/ubuntu/ precise-security/main amd64 Packages (/var/lib/apt/lists/security.ubuntu.com_ubuntu_dists_precise-security_main_binary-amd64_Packages)
W: Duplicate sources.list entry http://security.ubuntu.com/ubuntu/ precise-security/restricted amd64 Packages (/var/lib/apt/lists/security.ubuntu.com_ubuntu_dists_precise-security_restricted_binary-amd64_Packages)
W: Duplicate sources.list entry http://security.ubuntu.com/ubuntu/ precise-security/universe amd64 Packages (/var/lib/apt/lists/security.ubuntu.com_ubuntu_dists_precise-security_universe_binary-amd64_Packages)
W: Duplicate sources.list entry http://security.ubuntu.com/ubuntu/ precise-security/multiverse amd64 Packages (/var/lib/apt/lists/security.ubuntu.com_ubuntu_dists_precise-security_multiverse_binary-amd64_Packages)
W: Duplicate sources.list entry http://security.ubuntu.com/ubuntu/ precise-security/main i386 Packages (/var/lib/apt/lists/security.ubuntu.com_ubuntu_dists_precise-security_main_binary-i386_Packages)
W: Duplicate sources.list entry http://security.ubuntu.com/ubuntu/ precise-security/restricted i386 Packages (/var/lib/apt/lists/security.ubuntu.com_ubuntu_dists_precise-security_restricted_binary-i386_Packages)
W: Duplicate sources.list entry http://security.ubuntu.com/ubuntu/ precise-security/universe i386 Packages (/var/lib/apt/lists/security.ubuntu.com_ubuntu_dists_precise-security_universe_binary-i386_Packages)
W: Duplicate sources.list entry http://security.ubuntu.com/ubuntu/ precise-security/multiverse i386 Packages (/var/lib/apt/lists/security.ubuntu.com_ubuntu_dists_precise-security_multiverse_binary-i386_Packages)
W: Duplicate sources.list entry http://extras.ubuntu.com/ubuntu/ precise/main amd64 Packages (/var/lib/apt/lists/extras.ubuntu.com_ubuntu_dists_precise_main_binary-amd64_Packages)
W: Duplicate sources.list entry http://extras.ubuntu.com/ubuntu/ precise/main i386 Packages (/var/lib/apt/lists/extras.ubuntu.com_ubuntu_dists_precise_main_binary-i386_Packages)
Avec:
cat /etc/apt/sources.list
J'obtiens:
bertrand@bertrand-HP-Compaq-dc5750:~$ cat /etc/apt/sources.list
# deb cdrom:[LuninuX OS 12.00 _Purple Possum_ - amd64 Beta 2]/ dists/precise/main/binary-i386/
# deb cdrom:[LuninuX OS 12.00 _Purple Possum_ - amd64 Beta 2]/ dists/precise/restricted/binary-i386/
# deb cdrom:[LuninuX OS 12.00 _Purple Possum_ - amd64 Beta 2]/ precise 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
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://fr.archive.ubuntu.com/ubuntu/ precise-backports main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-backports main restricted universe multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ precise-security main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-security main restricted
deb http://fr.archive.ubuntu.com/ubuntu/ precise-security universe
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-security universe
deb http://fr.archive.ubuntu.com/ubuntu/ precise-security multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-security multiverse
## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu precise partner
# deb-src http://archive.canonical.com/ubuntu precise partner
## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
deb http://extras.ubuntu.com/ubuntu precise main
deb-src http://extras.ubuntu.com/ubuntu precise main
Quelqu'un peut'il m'aider ?
Dernière modification par bertrand47 (Le 24/05/2012, à 14:59)
Hors ligne
xabilon
Re : [Résolu] Duplicate sources list
Salut
As-tu des fichiers *.list dans le dossier /etc/apt/sources.list.d/ ?
Que donne :
cat /etc/apt/sources.list.d/*.list
Pour passer un sujet en résolu : modifiez le premier message et ajoutez [Résolu] au titre.
Hors ligne
bertrand47
Re : [Résolu] Duplicate sources list
Ca donne ça:
bertrand@bertrand-HP-Compaq-dc5750:~$ cat /etc/apt/sources.list.d/*.list
deb http://ppa.launchpad.net/atareao/atareao/ubuntu precise main
deb-src http://ppa.launchpad.net/atareao/atareao/ubuntu precise main
deb http://ppa.launchpad.net/otto-kesselgulasch/gimp/ubuntu precise main
deb-src http://ppa.launchpad.net/otto-kesselgulasch/gimp/ubuntu precise main
# deb http://ppa.launchpad.net/jan-hoffmann/gnome-shell/ubuntu precise main
# deb-src http://ppa.launchpad.net/jan-hoffmann/gnome-shell/ubuntu precise main
# deb http://ppa.launchpad.net/docky-core/stable/ubuntu precise main
# deb-src http://ppa.launchpad.net/docky-core/stable/ubuntu precise main
deb http://ppa.launchpad.net/yannubuntu/boot-repair/ubuntu precise main
deb-src http://ppa.launchpad.net/yannubuntu/boot-repair/ubuntu precise main
deb http://ppa.launchpad.net/gwendal-lebihan-dev/cinnamon-stable/ubuntu precise main
deb-src http://ppa.launchpad.net/gwendal-lebihan-dev/cinnamon-stable/ubuntu precise main
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ precise-backports multiverse
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ precise-backports multiverse
# deb http://archive.canonical.com/ubuntu precise partner
# deb-src http://archive.canonical.com/ubuntu precise partner
# deb http://extras.ubuntu.com/ubuntu precise main
# deb-src http://extras.ubuntu.com/ubuntu precise main
deb http://ppa.launchpad.net/satyajit-happy/themes/ubuntu precise main
deb-src http://ppa.launchpad.net/satyajit-happy/themes/ubuntu precise main
deb http://ppa.launchpad.net/tiheum/equinox/ubuntu precise main
deb-src http://ppa.launchpad.net/tiheum/equinox/ubuntu precise main
deb http://ppa.launchpad.net/tualatrix/ppa/ubuntu precise main
deb-src http://ppa.launchpad.net/tualatrix/ppa/ubuntu precise main
deb http://ppa.launchpad.net/ubuntu-mozilla-security/ppa/ubuntu precise main
deb-src http://ppa.launchpad.net/ubuntu-mozilla-security/ppa/ubuntu precise main
deb http://ppa.launchpad.net/webupd8team/gnome3/ubuntu precise main
deb-src http://ppa.launchpad.net/webupd8team/gnome3/ubuntu precise main
Hors ligne
crasyo
Re : [Résolu] Duplicate sources list
Bonjour !
j'ai exactement le même problème après upgrade de oneiric à precise !
et voici le list et le *list :
deb http://ppa.launchpad.net/osmoma/audio-recorder/ubuntu precise main
deb-src http://ppa.launchpad.net/osmoma/audio-recorder/ubuntu precise main
deb-src http://archive.ubuntu.com/ubuntu precise main restricted #Added by software-properties
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://fr.archive.ubuntu.com/ubuntu/ precise main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise restricted main multiverse universe #Added by software-properties
## Major bug fix updates produced after the final release of the
## distribution.
deb http://fr.archive.ubuntu.com/ubuntu/ precise-updates main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-updates restricted main multiverse universe #Added by software-properties
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://fr.archive.ubuntu.com/ubuntu/ precise universe
deb http://fr.archive.ubuntu.com/ubuntu/ precise-updates universe
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://fr.archive.ubuntu.com/ubuntu/ precise multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ precise-updates multiverse
## 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/ natty-backports main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu precise-security main restricted
deb-src http://security.ubuntu.com/ubuntu precise-security restricted main multiverse universe #Added by software-properties
deb http://security.ubuntu.com/ubuntu precise-security universe
deb http://security.ubuntu.com/ubuntu precise-security multiverse
## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
deb http://archive.canonical.com/ubuntu precise partner
deb-src http://archive.canonical.com/ubuntu precise partner
## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
deb http://extras.ubuntu.com/ubuntu precise main
deb-src http://extras.ubuntu.com/ubuntu precise main
deb http://fr.archive.ubuntu.com/ubuntu/ precise restricted main multiverse universe
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
## Major bug fix updates produced after the final release of the
## distribution.
## 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.
## 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.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://fr.archive.ubuntu.com/ubuntu/ precise-backports main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-backports main restricted universe multiverse #Added by software-properties
## 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.
## This software is not part of Ubuntu, but is offered by third-party
deb http://fr.archive.ubuntu.com/ubuntu/ precise-proposed restricted main multiverse universe
## developers who want to ship their latest software.
Me voilà bien perplexe, ça ne m'est jamais arrivé ! J'ajoute que du coup, je ne peux pas faire les mises à jour en mode console, cela me dit en boucle de corriger le problème en effectuant apt-get update...
Merci de m'aider si c'est possible
Hors ligne
xabilon
Re : [Résolu] Duplicate sources list
Déjà, commencer par remplacer tout le contenu du fichier /etc/apt/sources.list par ça :
## DEPOTS OFFICIELS ##
deb http://fr.archive.ubuntu.com/ubuntu/ precise main restricted universe multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ precise-updates main restricted universe multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ precise-security main restricted universe multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ precise-backports main restricted universe multiverse
## DEPOTS SUPPLEMENTAIRES ##
# deb http://archive.canonical.com/ubuntu precise partner
deb http://extras.ubuntu.com/ubuntu precise main
Ça sera beaucoup plus clair.
Ce fichier est un fichier système, donc il faudra les droits d'administration (root) pour le modifier. Une petite recherche vous apprendra comment faire.
Pour passer un sujet en résolu : modifiez le premier message et ajoutez [Résolu] au titre.
Hors ligne
bertrand47
Re : [Résolu] Duplicate sources list
Merci.
Hors ligne
xabilon
Re : [Résolu] Duplicate sources list
C'est bon ?
Pour passer un sujet en résolu : modifiez le premier message et ajoutez [Résolu] au titre.
Hors ligne
bertrand47
Re : [Résolu] Duplicate sources list
parfait, merci.
Hors ligne
crasyo
Re : [Résolu] Duplicate sources list
Merci,
je viens à l'instant de procéder à cette modification et à un update, ça marche !
Il est agréable de lire des gens compétents. Et si rapides pour dépanner.
Une idée de ce qui a pu se passer ??? que je ne recommence pas...
Hors ligne
analogfaz
Re : [Résolu] Duplicate sources list
Bonjour,
en plus des dépôts ubuntu, j'ai un tas de canonical :
deb http://archive.canonical.com/ubuntu precise partner
deb-src http://archive.canonical.com/ubuntu precise partner
deb http://archive.canonical.com/ubuntu precise-updates partner
deb-src http://archive.canonical.com/ubuntu precise-updates partner
deb http://archive.canonical.com/ubuntu precise-backports partner
deb-src http://archive.canonical.com/ubuntu precise-backports partner
deb http://archive.canonical.com/ubuntu precise-security partner
deb-src http://archive.canonical.com/ubuntu precise-security partner
# deb http://archive.canonical.com/ubuntu precise-proposed partner
# deb-src http://archive.canonical.com/ubuntu precise-proposed partner
Cela fait-il double usage avec les dépôts ubuntu eux-mêmes ?
Ais-je interêt à les supprimer de mon sources.list ?
Hors ligne
bowmore
Re : [Résolu] Duplicate sources list
Même problème, résolu par la méthode xabilon.
"Bon bah, je vais essayer de ne pas claquer la porte en sortant"
Buzz Aldrin, le 21 juillet 1969 sur la Mer de la Tranquillité
Hors ligne
xabilon
Re : [Résolu] Duplicate sources list
@analogfaz : ces dépôts-là sont des dépôts "partner" (paquets proposés par des entreprises partenaires de Canonical), donc non, il ne font pas double usage.
Pour passer un sujet en résolu : modifiez le premier message et ajoutez [Résolu] au titre.
Hors ligne
analogfaz
Re : [Résolu] Duplicate sources list
Merci xabilon !
Hors ligne
emraude90
Re : [Résolu] Duplicate sources list
j' ai eu le même problème que bertrand47 et j'ai essayé la méthode de xabilon, j'ai eu les résultats suivants:
W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/fr.archive.ubuntu.com_ubuntu_dists_precise_main_binary-i386_Packages Somme de contrôle de hachage incohérente
E: Le téléchargement de quelques fichiers d'index a échoué, ils ont été ignorés, ou les anciens ont été utilisés à la place.
pourriez vous me dire comment régler ce problème. je tiens à vous préciser que je suis débutante sur ubuntu,
Merci,
Hors ligne
xabilon
Re : [Résolu] Duplicate sources list
Essaye ceci en terminal :
sudo rm /var/lib/apt/lists/partial/* -vf
sudo apt-get update
ça consiste à supprimer les listes des paquets, et à les retélécharger.
Ceci dit, il n'est pas exclu que ce soit une erreur du dépôt lui-même, donc le problème ne viendrait pas de chez toi.
Pour passer un sujet en résolu : modifiez le premier message et ajoutez [Résolu] au titre.
Hors ligne
Troumad
Hors ligne
cdjklm
Re : [Résolu] Duplicate sources list
si je fais ta technique es ce que je perd toute mes sources,car j ai pas mal de source qui tiennes a jours mes logiciels installe et je n aimerai pas perdre ca
asus N55SF,Dual Boot Win7 Ubuntu (14.04) 64 bits,Intel® Core™ i7-2670QM CPU @ 2.20GHz × 8,GEFORCE GT555M 2GO DDR3ual,6GO Ram,HDD 750GO
Benq joybook lite Xubuntu 12.04 32bits , intel N270 1.66GHz x 2 , 945 GMA intégré 256 MO , 2GO Ram , HDD 250 GO , WIFI ,BLUETOOTH,modem 3G MC8775 intégré.
Hors ligne
xabilon
Re : [Résolu] Duplicate sources list
Salut cdjklm (tu t'es pas trop pris la tête pour trouver ton pseudo ?)
Non, cela supprime de ton disque dur les listes des paquets contenus dans les dépôts, pas les dépôts ni les paquets eux-mêmes, et un sudo apt-get update les re-télécharge.
Ta liste de sources est dans le fichier /etc/apt/sources.list (et éventuellement dans les fichiers du dossier /etc/apt/sources.list.d), ces commandes n'y touchent pas.
Si tu n'as pas confiance, tu peux faire une sauvegarde de ta (tes) liste(s) de sources.
Pour passer un sujet en résolu : modifiez le premier message et ajoutez [Résolu] au titre.
Hors ligne
cdjklm
Re : [Résolu] Duplicate sources list
ha oui merci c est vrai que je ne pense jamais a une sauvegarde pourtant m aurrai bien evider beaucoup de formatage j esseille ca.
(pour le pseudo ca viens des bornes d arcade ou il fallait 3 lettres et venant d amerique du nord cela faisait cidje mais sur internet y a un minimun donc pourquoi se prendre la tete autant suivre le clavier;)
asus N55SF,Dual Boot Win7 Ubuntu (14.04) 64 bits,Intel® Core™ i7-2670QM CPU @ 2.20GHz × 8,GEFORCE GT555M 2GO DDR3ual,6GO Ram,HDD 750GO
Benq joybook lite Xubuntu 12.04 32bits , intel N270 1.66GHz x 2 , 945 GMA intégré 256 MO , 2GO Ram , HDD 250 GO , WIFI ,BLUETOOTH,modem 3G MC8775 intégré.
Hors ligne
cdjklm
Re : [Résolu] Duplicate sources list
finalement je vais te montrer mon fichier dabord pour voir ce que tu en pense car il y en a dessus par rapport a ce qu il es conseille de mettre dans ce forum.
# deb cdrom:[Ubuntu 12.04 LTS _Precise Pangolin_ - Release amd64 (20120425)]/ dists/precise/main/binary-i386/
# deb cdrom:[Ubuntu 12.04 LTS _Precise Pangolin_ - Release amd64 (20120425)]/ dists/precise/restricted/binary-i386/
# deb cdrom:[Ubuntu 12.04 LTS _Precise Pangolin_ - Release amd64 (20120425)]/ precise main restricted
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb cdrom:[Ubuntu 10.10 _Maverick Meerkat_ - Release i386 (20101007)]/ dists/maverick/main/binary-i386/
deb cdrom:[Ubuntu 10.10 _Maverick Meerkat_ - Release i386 (20101007)]/ dists/maverick/restricted/binary-i386/
deb http://ftp.crihan.fr/ubuntu/ precise main restricted
deb-src http://ftp.crihan.fr/ubuntu/ precise main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://ftp.crihan.fr/ubuntu/ precise-updates main restricted
deb-src http://ftp.crihan.fr/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://ftp.crihan.fr/ubuntu/ precise universe
deb-src http://ftp.crihan.fr/ubuntu/ precise universe
deb http://ftp.crihan.fr/ubuntu/ precise-updates universe
deb-src http://ftp.crihan.fr/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://ftp.crihan.fr/ubuntu/ precise multiverse
deb-src http://ftp.crihan.fr/ubuntu/ precise multiverse
deb http://ftp.crihan.fr/ubuntu/ precise-updates multiverse
deb-src http://ftp.crihan.fr/ubuntu/ precise-updates multiverse
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://ftp.crihan.fr/ubuntu/ precise-backports main restricted universe multiverse
deb-src http://ftp.crihan.fr/ubuntu/ precise-backports main restricted universe multiverse
deb http://ftp.crihan.fr/ubuntu/ precise-security main restricted
deb-src http://ftp.crihan.fr/ubuntu/ precise-security main restricted
deb http://ftp.crihan.fr/ubuntu/ precise-security universe
deb-src http://ftp.crihan.fr/ubuntu/ precise-security universe
deb http://ftp.crihan.fr/ubuntu/ precise-security multiverse
deb-src http://ftp.crihan.fr/ubuntu/ precise-security multiverse
## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
deb http://archive.canonical.com/ubuntu precise partner
deb-src http://archive.canonical.com/ubuntu precise partner
## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
deb http://extras.ubuntu.com/ubuntu precise main
deb-src http://extras.ubuntu.com/ubuntu precise main
deb http://archive.ubuntugames.org ubuntugames main
deb-src http://archive.ubuntugames.org ubuntugames main
## Depôt MultiSystem
deb http://liveusb.info/multisystem/depot all main
deb http://dswd.github.com/Swine/repository/deb stable main
deb-src http://dswd.github.com/Swine/repository/deb stable main
deb http://ftp.crihan.fr/ubuntu/ precise-proposed restricted main multiverse universe
deb http://repository.mein-neues-blog.de:9000/ /
asus N55SF,Dual Boot Win7 Ubuntu (14.04) 64 bits,Intel® Core™ i7-2670QM CPU @ 2.20GHz × 8,GEFORCE GT555M 2GO DDR3ual,6GO Ram,HDD 750GO
Benq joybook lite Xubuntu 12.04 32bits , intel N270 1.66GHz x 2 , 945 GMA intégré 256 MO , 2GO Ram , HDD 250 GO , WIFI ,BLUETOOTH,modem 3G MC8775 intégré.
Hors ligne
xabilon
Re : [Résolu] Duplicate sources list
Les dépôts ftp.crihan.fr m'ont l'air d'être des miroirs tout à fait normaux.
Les autres dépôts, je ne les connais pas, mais c'est à toi de savoir pourquoi tu les as rajouté
Pour passer un sujet en résolu : modifiez le premier message et ajoutez [Résolu] au titre.
Hors ligne |
Forms are just a tool to simplify and speed-up (the development of) the process of fetching POST data from request. A manual way would be to do request.POST.get('somefield') for all the fields there could be in a html form. Django can do better that that.
In its essence, a Form class holds a number of Fields and performs these tasks:
display html inputs,
collect and validate data when user submits,
if fields don't validate, return the values along with error messages to html,
if all fields validate, provide form.cleaned_data dictionary as a convenient way to access these values in view.
With these values, I could then manually crate a new instance of a MyModel and save it. Of course, I would have to define a Field in the Form for every Field in MyModel model.
This means that, basically, I could do something like this:
(forgive me for not testing this code, so I can't vouch that is's 100% correct)
models.py:
class MyModel(models.Model):
field1 = models.CharField(max_length=40, blank=False, null=False)
field2 = models.CharField(max_length=60, blank=True, null=True)
forms.py:
class MyModelForm(forms.Form):
form_field1 = forms.CharField(max_length=40, required=True)
form_field2 = forms.CharField(max_length=60, required=False)
views.py:
def create_a_my_model(request):
if request.method == 'POST':
form = MyModelForm(request.POST)
if form.is_valid():
my_model = MyModel()
my_model.field1 = form.cleaned_data.get('form_field1', 'default1')
my_model.field2 = form.cleaned_data.get('form_field2', 'default2')
my_model.save()
else:
form = MyModelForm()
c = { 'form' : form }
return HttpResponse('templtate.html', c)
(this could be written with a few lines of code less, but it's meant to be as clear as possible)
Notice there are no relation between model Fields and form Fields! We have to manually assign values to MyModel instance when creating it.
The above example outlines generic form workflow. It is often needed in complex situations, but not in such a simple one as is this example.
For this example (and a LOT of real-world examples), Django can do better that that!
You can notice two annoying issues in the above example:
I have to define model Fields and Form fields each, and they are very similar, so that's kinda duplicate work (the similarity grows when adding labels, validators etc.),
creating of MyModel instance is a bit silly, having to assign all those values manually.
This is where ModelForms come in.
These act basically just like a regular form (actually, they are extended from regular forms), but they can save me some of the work (the two issues I just outlined, of course :) ).
So back to the two issues:
Instead of defining a form Field for each model Field, I simply define model = MyModel in the the Meta class. This instructs the Form to automatically generate form Fields from model Fields.
Model forms have save method available. This can be used to create instance of model in one line in the view, instead of manually assigning field-by-field.
So, lets make the example above with a ModelForm:
models.py:
class MyModel(models.Model):
field1 = models.CharField(max_length=40, blank=False, null=False)
field2 = models.CharField(max_length=60, blank=True, null=True)
forms.py:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
views.py:
def create_a_my_model(request):
if request.method == 'POST':
form = MyModelForm(request.POST)
if form.is_valid():
# save the model to database, directly from the form:
my_model = form.save() # reference to my_model is often not needed at all, a simple form.save() is ok
# alternatively:
# my_model = form.save(commit=False) # create model, but don't save to database
# my.model.something = whatever # if I need to do something before saving it
# my.model.save()
else:
form = MyModelForm()
c = { 'form' : form }
return HttpResponse('templtate.html', c)
Hope this clears up the usage of Django forms a bit.
Just one more note - it is perfectly ok to define form Fields on a ModelForm. These will not be used in form.save() but can still be access with form.cleaned_data just as in a regular Form. |
How do you create a random string in Python?
I needed it to be number then character repeat till you're done this is what I created
def random_id(length):
number = '0123456789'
alpha = 'abcdefghijklmnopqrstuvwxyz'
id = ''
for i in range(0,length,2):
id += random.choice(number)
id += random.choice(alpha)
return id
|
I want to create a Python context manager to act as a controlled sort of "library" that lends out objects, and then takes them back when the scope of the with statement exits.
In psuedo-code I was thinking something like this:
class Library:
def __init__(self):
self.lib = [1,2,3,4]
self.lock = Condition(Lock())
def __enter__(self):
with self.lock:
# Somehow keep track of this object-thread association
if len(self.lib) > 0:
return self.lib.pop()
else:
self.lock.wait()
return self.lib.pop()
def __exit__(self):
with self.lock:
# Push the object that the calling thread obtained with
# __enter__() back into the array
self.lock.notify()
|
To sort by a key in Python 2.3 or lower, you could use the cmp parameter. But sometimes key style sorting is easier to read; and in any case, it does less work, since cmp will be called O(n log n) times, while the key function will be called only O(n) times.
With that in mind, here's a way to reproduce the behavior of the key parameter in later versions of Python. It uses the decorate-sort-undecorate idiom, a.k.a. the Schwartzian Transform. This won't be quite as space efficient because it makes copies, but for large lists, it is likely to be more time efficient. I've named this sorted because it roughly reproduces the sorted function added in 2.4; check the python version and conditionally import this so that you don't smash the built-in sorted in newer versions -- or just rename it.
def sorted(seq, key=lambda x: None, reverse=False):
seq = [(key(x), i, x) for i, x in enumerate(seq)]
seq.sort()
if reverse:
seq.reverse()
return [x for k, i, x in seq]
Note that enumerate is only necessary if you care about having a stable sort on unequal values with equal keys; it slows down the function by a hair. Tested on your data:
>>> key=lambda x: (x.count('YES'), x.count('MAYBE'), x.count('NO'))
>>> my_sorted(mylist, key=key, reverse=True)
[['ITEM C', 'YES', 'YES', 'YES', 'YES', 'NO', 'NO', 'MAYBE', 'NO', 'MAYBE'],
['ITEM B', 'YES', 'NO', 'YES', 'YES', 'NO', 'NO', 'NO', 'NO', 'MAYBE'],
['ITEM A', 'YES', 'NO', 'YES', 'YES', 'NO', 'NO', 'NO', 'NO', 'NO']]
You might also consider using a dictionary to do your counting; that way, only one pass is required. However, count is sufficiently optimized that three passes are still faster than one Python for loop, at least on my machine. So only use this if you need to count lots of values. I'll leave this here for posterity:
def my_key(inner_list):
counts = {'YES':0, 'MAYBE':0, 'NO':0}
for i in inner_list:
if i in counts:
counts[i] += 1
return (counts['YES'], counts['MAYBE'], counts['NO'])
I did some testing; apologies for the long post. The below is only for the curious and inquisitive.
My tests indicate that on the smaller list, decorate, sort, undecorate is already faster than using the built-in sort + cmp. On a bigger list, the difference becomes more dramatic. Definitions:
def key_count(x):
return (x.count('YES'), x.count('MAYBE'), x.count('NO'))
def key_dict(inner_list):
counts = {'YES':0, 'MAYBE':0, 'NO':0}
for i in inner_list:
if i in counts:
counts[i] += 1
return (counts['YES'], counts['MAYBE'], counts['NO'])
def decorate_sort(seq, key=lambda x: None, reverse=False):
seq = [(key(x), i, x) for i, x in enumerate(seq)]
seq.sort()
if reverse:
seq.reverse()
return [x for k, i, x in seq]
def builtin_sort(seq, key, reverse=False):
seq.sort(lambda p, q: cmp(key(p), key(q)))
if reverse:
seq.reverse()
Tests:
>>> mylist = [
... ['ITEM A', 'YES', 'NO', 'YES', 'YES', 'NO', 'NO', 'NO', 'NO', 'NO'],
... ['ITEM B', 'YES', 'NO', 'YES', 'YES', 'NO', 'NO', 'NO', 'NO', 'MAYBE'],
... ['ITEM C', 'YES', 'YES', 'YES', 'YES', 'NO', 'NO', 'MAYBE', 'NO', 'MAYBE']
... ]
>>> %timeit decorate_sort(mylist, key=key_count, reverse=True)
100000 loops, best of 3: 5.03 us per loop
>>> %timeit builtin_sort(mylist, key=key_count, reverse=True)
100000 loops, best of 3: 5.28 us per loop
The built-in version is already slower! The less-generalized version mylist.sort(lambda p, q: -cmp(key(p), key(q))) is a better by a hair for a short list, because of the addition of enumerate to decorate_sort; without it, decorate_sort is faster (4.28 us per loop in my previous test):
>>> %timeit mylist.sort(lambda p, q: -cmp(key_count(p), key_count(q)))
100000 loops, best of 3: 4.74 us per loop
Using key_dict is a mistake in this case, though:
>>> %timeit decorate_sort(mylist, key=key_dict, reverse=True)
100000 loops, best of 3: 8.97 us per loop
>>> %timeit builtin_sort(mylist, key=key_dict, reverse=True)
100000 loops, best of 3: 11.4 us per loop
Testing it on a larger list, basically the same results hold:
>>> import random
>>> mylist = [[random.choice(('YES', 'MAYBE', 'NO')) for _ in range(1000)]
for _ in range(100)]
>>> %timeit decorate_sort(mylist, key=key_count, reverse=True)
100 loops, best of 3: 6.93 ms per loop
>>> %timeit builtin_sort(mylist, key=key_count, reverse=True)
10 loops, best of 3: 34.5 ms per loop
The less generalized version is now slower than decorate_sort.
>>> %timeit mylist.sort(lambda p, q: -cmp(key_count(p), key_count(q)))
100 loops, best of 3: 13.5 ms per loop
And key_dict is still slower. (But faster than builtin_sort!)
>>> %timeit decorate_sort(mylist, key=key_dict, reverse=True)
10 loops, best of 3: 20.4 ms per loop
>>> %timeit builtin_sort(mylist, key=key_dict, reverse=True)
10 loops, best of 3: 103 ms per loop
So the upshot is that the Schwartzian Transform provides a solution that is both faster and more generalized -- a rare and wonderful combination. |
given the next console:
import os
import tty
import termios
from sys import stdin
class Console(object):
def __enter__(self):
self.old_settings = termios.tcgetattr(stdin)
self.buffer = []
return self
def __exit__(self, type, value, traceback):
termios.tcsetattr(stdin, termios.TCSADRAIN, self.old_settings)
...
def dimensions(self):
dim = os.popen('stty size', 'r').read().split()
return int(dim[1]), int(dim[0])
def write(self, inp):
if isinstance(inp, basestring):
inp = inp.splitlines(False)
if len(inp) == 0:
self.buffer.append("")
else:
self.buffer.extend(inp)
def printBuffer(self):
self.clear()
print "\n".join(self.buffer)
self.buffer = []
Now I have to get some letters in that buffer, but letters aren't given in the right order and some places are going to be empty. For instance: I want to have a "w" on the screen in the 12th column and the 14th row and then some other "w"'s on other places and a "b" over there etc...(the console is big enough to handle this). How could I implement this? I really don't have a clue how to solve this problem.
Another question that bothers me is how to call this exit-constructor, what kinda parameters should be given?
sincerely, a really inexperienced programmer. |
function [A , c] = MinVolEllipse(P, tolerance)
[d N] = size(P);
Q = zeros(d+1,N);
Q(1:d,:) = P(1:d,1:N);
Q(d+1,:) = ones(1,N);
count = 1;
err = 1;
u = (1/N) * ones(N,1);
while err > tolerance,
X = Q * diag(u) * Q';
M = diag(Q' * inv(X) * Q);
[maximum j] = max(M);
step_size = (maximum - d -1)/((d+1)*(maximum-1));
new_u = (1 - step_size)*u ;
new_u(j) = new_u(j) + step_size;
count = count + 1;
err = norm(new_u - u);
u = new_u;
end
U = diag(u);
A = (1/d) * inv(P * U * P' - (P * u)*(P*u)' );
c = P * u;
Here is some MATLAB test code:
points = [[ 0.53135758, -0.25818091, -0.32382715],
[ 0.58368177, -0.3286576, -0.23854156,],
[ 0.18741533, 0.03066228, -0.94294771],
[ 0.65685862, -0.09220681, -0.60347573],
[ 0.63137604, -0.22978685, -0.27479238],
[ 0.59683195, -0.15111101, -0.40536606],
[ 0.68646128, 0.0046802, -0.68407367],
[ 0.62311759, 0.0101013, -0.75863324]];
[A centroid] = minVolEllipse(points',0.001);
A
[~, D, V] = svd(A);
rx = 1/sqrt(D(1,1));
ry = 1/sqrt(D(2,2));
rz = 1/sqrt(D(3,3));
[u v] = meshgrid(linspace(0,2*pi,20),linspace(-pi/2,pi/2,10));
x = rx*cos(u').*cos(v');
y = ry*sin(u').*cos(v');
z = rz*sin(v');
for idx = 1:20,
for idy = 1:10,
point = [x(idx,idy) y(idx,idy) z(idx,idy)]';
P = V * point;
x(idx,idy) = P(1)+centroid(1);
y(idx,idy) = P(2)+centroid(2);
z(idx,idy) = P(3)+centroid(3);
end
end
figure
plot3(points(:,1),points(:,2),points(:,3),'.');
hold on;
mesh(x,y,z);
axis square;
alpha 0;
which will produce the the covariance matrix:
A =
47.3693 -116.0758 -79.1861
-116.0758 458.0874 280.0656
-79.1861 280.0656 179.3886
Now, here is my attempt at port this code to Python (2.7):
from __future__ import division
import numpy as np
import numpy.linalg as la
def mvee(points,tol=0.001):
N, d = points.shape
Q = np.zeros([N,d+1])
Q[:,0:d] = points[0:N,0:d]
Q[:,d] = np.ones([1,N])
Q = np.transpose(Q)
points = np.transpose(points)
count = 1
err = 1
u = (1/N) * np.ones(shape = (N,))
while err > tol:
X = np.dot(np.dot(Q, np.diag(u)), np.transpose(Q))
M = np.diag( np.dot(np.dot(np.transpose(Q), la.inv(X)),Q))
jdx = np.argmax(M)
step_size = (M[jdx] - d - 1)/((d+1)*(M[jdx] - 1))
new_u = (1 - step_size)*u
new_u[jdx] = new_u[jdx] + step_size
count = count + 1
err = la.norm(new_u - u)
u = new_u
U = np.diag(u)
c = np.dot(points,u)
A = (1/d) * la.inv(np.dot(np.dot(points,U), np.transpose(points)) - np.dot(c,np.transpose(c)) )
return A, np.transpose(c)
The corresponding test code:
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt
from scipy.spatial import Delaunay
#some random points
points = np.array([[ 0.53135758, -0.25818091, -0.32382715],
[ 0.58368177, -0.3286576, -0.23854156,],
[ 0.18741533, 0.03066228, -0.94294771],
[ 0.65685862, -0.09220681, -0.60347573],
[ 0.63137604, -0.22978685, -0.27479238],
[ 0.59683195, -0.15111101, -0.40536606],
[ 0.68646128, 0.0046802, -0.68407367],
[ 0.62311759, 0.0101013, -0.75863324]])
# compute mvee
A, centroid = mvee(points)
print A
# point it and some other stuff
U, D, V = la.svd(A)
rx, ry, rz = [1/np.sqrt(d) for d in D]
u, v = np.mgrid[0:2*np.pi:20j,-np.pi/2:np.pi/2:10j]
x=rx*np.cos(u)*np.cos(v)
y=ry*np.sin(u)*np.cos(v)
z=rz*np.sin(v)
for idx in xrange(x.shape[0]):
for idy in xrange(y.shape[1]):
x[idx,idy],y[idx,idy],z[idx,idy] = np.dot(np.transpose(V),np.array([x[idx,idy],y[idx,idy],z[idx,idy]])) + centroid
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(points[:,0],points[:,1],points[:,2])
ax.plot_surface(x, y, z, cstride = 1, rstride = 1, alpha = 0.1)
plt.show()
produces this:
[[ 0.84650504 -1.40006147 0.39857055][-1.40006147 2.60678264 -1.52583781][ 0.39857055 -1.52583781 1.04581752]]
Clearly different. What gives? |
vhorax
Bug Installation de KVM Ubuntu 12.10
Bonsoir,
Je débute sur Ubuntu et je vient d'installer le Gestionnaire de Machine Virtuelle via la logithèque Ubuntu et quand je le démarre il me met se message:
Impossible de se connecter à libvirt.
Verify that:
- The 'libvirt-bin' package is installed
- The 'libvirtd' daemon has been started
- You are member of the 'libvirtd' group
Libvirt URI is: qemu:///system
Traceback (most recent call last):
File "/usr/share/virt-manager/virtManager/connection.py", line 1027, in _open_thread
self.vmm = self._try_open()
File "/usr/share/virt-manager/virtManager/connection.py", line 1009, in _try_open
flags)
File "/usr/lib/python2.7/dist-packages/libvirt.py", line 102, in openAuth
if ret is None:raise libvirtError('virConnectOpenAuth() failed')
libvirtError: Failed to connect socket to '/var/run/libvirt/libvirt-sock': Permission non accordée
J'ai installer le Package en faisant :
sudo apt-get install libvirt-bin
Sa a fonctionné mais pas corrigé le problème et je comprend pas trop les autres choses à vérifier.
Voilà merci d'avance .
Dernière modification par vhorax (Le 09/01/2013, à 21:35)
Hors ligne
Haleth
Re : Bug Installation de KVM Ubuntu 12.10
C'est quoi le rapport avec kvm ?
Pour utiliser kvm:
#Créer une image
qemu-img create -f qcow2 machin.img 50G
#1st boot: cdrom
kvm machin.img -cdrom truc.iso
#Boot classique
kvm machin.img
Ubuntu is an ancien African word which means "I can't configure Debian"
Because accessor & mutator are against encapsulation (one of OOP principles), good OOP-programmers do not use them. Obviously, procedural-devs do not. In fact, only ugly-devs are still using them.
Hors ligne
vhorax
Re : Bug Installation de KVM Ubuntu 12.10
J'utilise en interface graphique et je ne peut pas créer mes machines virtuelles.
Je suis obliger de passer par le terminal ?
Dernière modification par vhorax (Le 09/01/2013, à 21:50)
Hors ligne
src
Re : Bug Installation de KVM Ubuntu 12.10
En gros tu dois installer :
-virt-manager
-libvirt
-kvm
Les 3 composants sont indépendants, donc installer l'un n'amène pas les autres.
Je donne les noms génériques, les paquets ne s'appellent pas forcément comme ça.
Ensuite tu vas lancer virt-manager et là tu n'auras qu'à créer une connexion localhost de type QEMU, tu pourras ainsi créer des VM.
Par contre virt-manager est assez austère, c'est très pro un peu comme Hyper-V. Si tu veux quelque chose de plus convivial je te recommande Virtualbox.
Dernière modification par src (Le 11/01/2013, à 00:34)
Actuellement sur Manjaro Xfce (amd64)
Serveur sur FreeBSD 10 (i386) + Debian GNU/kFreeBSD.
http://maniatux.fr
Hors ligne |
From PEP 8:
- Imports should usually be on separate lines, e.g.:
Yes: import os
import sys
No: import sys, os
it's okay to say this though:
from subprocess import Popen, PIPE
I thought comma separated style is simpler, shorter, easier to read and write, until I read PEP8. Does it have any disadvantage? PEP 8 didn't give any explaination about that.
So my question is, why is that bad? |
#1626 Le 13/05/2012, à 15:13
Hizoka
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
echo "TERM@@SEND@@$cmd\n"
sleep 3 # permet de laisser le temps au process d'etre créer
pid=$(pidof cdrdao)
while kill -0 $pid >/dev/null; do
sleep 0.2
## barre de progression ####### en pulsation ####
echo 'SET@_progressbar1.pulse()'
done &
pidwhile=${!}
ca devrait le faire ça
File le lien de ton logiciel que je puisse jeter un oeil à ton glade...
Hors ligne
#1627 Le 13/05/2012, à 15:51
yakusa77
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
je test sa tout de suite je te si ca fonctionne hizoka, merci du tuyau
voila le lien du prog : cdpsx2bin normalement après c'est petite mise au point je pense pouvoir remettre en dl le prog
edit: sa fonctionne partiellement, l'action du bouton refonctionne en revanche la suite du code est exécuter dans la foulée ce qui fait que j'ai la fenêtre "terminé" qui s'affiche alors le rip comment tout juste mais la boucle fonctionne quand même.
Dernière modification par yakusa77 (Le 13/05/2012, à 16:04)
Hors ligne
#1628 Le 13/05/2012, à 16:06
AnsuzPeorth
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
@yakusa77
Tu es entre de bonnes mains, je le laisse faire :d
@Hizoka
Vu que tu t'occupes de yakusa, je pourrait m'occuper de ton cas ....
Pour ton soucis de edit, oui, ton pc trop rapide, et j'ai peur de pas pouvoir faire grand chose, mais j'y jetterai un oeil. Par conte, vraiment etrange que ca ne le fait que sur la premiere colonne !!!!
pour WRAP_WORD des sourceview, je peux ajouter une verif au load, et ajouter cette option , ce sera le default, si ca conviens pas, il suffira de modifier apres via bash, mais au moins, pas de soucis d'affichage.
Pour les combo, pas possible de charger avant, ou alors, tu indique l'option --load-config, et ensuite tu reload la config (la commande que je t'ai donné).
Ou alors, il faudrait que je modifie la save et le load des combo depuis cfg, mais il faudra un ficheir de conf different, genre
[COMBO:_combo1]
selected = 0
content = row1@@row2@@row3
Donc une option par combo ...
Maintenant, dis moi tes priorité, que veux tu en premier, en sachant que demain je pars une semaine, donc je serait pas dispo !
A savoir que je dois aussi tout modiifer pour mes soucis de freeze avec idle_add depuis maj (la version gtk3, ben ca attendra un peu ...)
PS: suis sur chan , cf signature
Dernière modification par AnsuzPeorth (Le 13/05/2012, à 16:06)
Hors ligne
#1629 Le 13/05/2012, à 17:09
Hizoka
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
yakusa77
J'ai trouvé pour ton soucis de bourrage :
1) un viewport qui devait se remplir et se développer était présent dans _vboxTerm
=> je l'ai viré
2) _vboxTerm n'avait pas de taille definit
=> j'ai donné la taille que tu indiques dans le go
Confirme moi que ça marche chez toi.
Je look pour l'arret.
Sinon, il faut que tu revois ton arborescence pour ton deb...
tu mets tout dans /bin, il ne faut surtout pas.
http://www.debian.org/doc/debian-policy/ch-archive.html
EDIT : si tu peux rejoinds nous sur le chat d'ansuzpeorth (look sa signature)
Ca regle pas le soucis si tu fais comme je t'ai dis plus haut et que tu ajoute des kill dans tes actions d'arrets ?
oui() {
kill ${pid_while} ${pid}
echo 'EXIT@@'
rm /tmp/{lecteur,dev.txt}
}
# quitte le programme ...
_QUIT() {
# verifie si un rip est en cours ...
process=`ps -e | grep cdrdao | wc -l`
if [[ $process == "1" ]]; then
echo 'SET@_avertissement.show()'
else
kill ${pid_while} ${pid}
echo 'EXIT@@'
rm /tmp/{lecteur,dev.txt}
fi
}
Dernière modification par Hizoka (Le 13/05/2012, à 17:19)
Hors ligne
#1630 Le 13/05/2012, à 19:38
AnsuzPeorth
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
@hizo
Bon, up git dev
J'ai ajouté wrap_mode, et logiquement, plus de risque de freeze pour les vieilles version de gtk, par sécurité, si tout fonctionne, mets à jour tes softs.
Tiens moi au jus que j'up une maj, car là ca craint ce freeze .... !
Dernière modification par AnsuzPeorth (Le 13/05/2012, à 19:38)
Hors ligne
#1631 Le 16/05/2012, à 02:57
Hizoka
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
Voila de quoi travailler pour ton retour
1) Est-il possible d'envoyer plusieurs lignes directement dans un tree avec @@ pour separer les lignes comme le fait lz chargement de variable.
2) Le chargement de fichier de config via echo "EXEC@@ParseConfig('fichier').load_config(self.gui)" execute chaque commande avec la nouvelle variable chargée ?
Ce n'est pas sensé bloquer le coté graphique ?
Ex :
=> [[ PY ]] => EXEC@@ParseConfig('/home/hizoka/.config/screencastor/ezez.cfg').load_config(self.gui)
[[ INIT CONFIG ]]
[[ CONFIG LOAD ]] ENTRY
=> [[ PY ]] => :: FIFO write :: _pref_name ezez
....
=> [[ PY ]] => DEBUG=> in bash NOT GET _pref_name ezez
=> [[ PY ]] => ====>>> fonction pref_name : ezez
3) Peut on rendre insensible une box ?
si de base je met la box en insensible et que j'execute :
echo 'SET@_bigbox.props.sensitive = "True"'
ca passe bien
mais l'inverse ne marche pas, une idée ?
4) Alors là, par contre c'est tres chiant, en utilisant un fichier de config (même vide ou ne contenant que des coches) , il fait planter mkv-extractor-gui...
Tout le coté graphique fonctionne, mais plus aucun lien avec le script...
Il faudra qu'on voit ça en live car j'ai grave galéré pour trouver que ca venait du config...
5) Peut on définir la taille de la mémoire du terminal ?
6) Une possibilité qu'on a deja evoqué mais qui je trouve serait surpuissante, c'est de pouvoir utiliser une combobox avec des coches, niveau ergonomie, ca serait le top
7) Je pige pas la commande CONFIG@@SET, c'est pour modifier une variable ?
sauvegarder une variable dans le fichier de conf ?
Car aucune de mes 2 suppositions ne fonctionnent...
8) Je ne retrouve plus comment on envoie une commande depuis un autre terminal dans g2s, j'ai essayé :
echo 'SET@_statusbar.push(0, "oui vive moi")' > /tmp/FIFO27625
=> [[ PY ]] => DEBUG=> in bash NOT GET SET@_statusbar.push(0, "oui vive moi")
mais pas de write...
9) J'ai un retour au demarrage d'un logiciel :
./lpsm.py:1835: RuntimeWarning: missing handler 'on_activate'
self.widgets.connect_signals(self)
je vois pas ce qu'il veut dire.... mes on_activate me semble ok et font bien appel à un bouton...
10) Ton manpage creator ne fonctionne pas chez moi.
Il y avait un soucis dans la commande g2s (g2s appellé au lieu de ./glade2script.py) mais maintenant j'ai :
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
self.run()
File "/home/hizoka/Scripts_et_logiciels/scripts/lpsm/usr/share/lpsm/manpagecreator/manpagecreator.py", line 385, in run
for f in os.listdir('mans'):
OSError: [Errno 2] Aucun fichier ou dossier de ce type: 'mans'
^CTraceback (most recent call last):
File "./glade2script.py", line 4596, in <module>
m.main()
File "./glade2script.py", line 2187, in main
gtk.main()
KeyboardInterrupt
au lancement
Dernière modification par Hizoka (Le 19/05/2012, à 02:40)
Hors ligne
#1632 Le 19/05/2012, à 23:26
yakusa77
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
J'ai un petit problème, depuis cet semaine je me suis remis sur un projet que j'avais commencer en 2010 en laissé inachevé, grâce à Hizo j'ai pu achevé le projet précédent qui était une réécriture d'un prog en gtkdialog...
bon sur le projet en question c'est front end pour un super émulateur, MESS. bref j'arrive au résulta que je voulais , mais voila une fois que je lance l’émulateur quelque soit la manière donc j'en sort, j'ai toujours un problème de relais brisé entre l'interface et le script... ce qui a pour incidence que plus rien ne fonctionne d'un point interface, il faut que je coupe par la croix.
si quelqu'un a une idée du pourquoi de la chose...
Dernière modification par yakusa77 (Le 19/05/2012, à 23:28)
Hors ligne
#1633 Le 20/05/2012, à 00:09
Hizoka
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
il faudrait plus d'infos... du genre comment tu le lance, une fois lancé, que se passe-t-il sur l'interface ? comment sait il que c'est terminé ?
mets un lien vers ton logiciel...
Hors ligne
#1634 Le 20/05/2012, à 00:26
yakusa77
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
je veut bien te fournir un lien, mais te faudra l'emulateur qui es tres lourd avec...
sinon je le lance de la maniere la plus logique a mon gout à savoir soit par ./chemin/exec soit comme avec exec /chemin/exec
edit: apres compression sous 7zip ~ 50 mo : emustation
Dernière modification par yakusa77 (Le 20/05/2012, à 00:49)
Hors ligne
#1635 Le 20/05/2012, à 02:12
Hizoka
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
ne serais tu pas mieux de l'executer en fond de tache ?
EDIT : ca m'a l'air ok en le foutant en fond...
Dernière modification par Hizoka (Le 20/05/2012, à 02:26)
Hors ligne
#1636 Le 20/05/2012, à 08:56
yakusa77
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
comme quoi effectivement parfois, un truc tout bête peut vraiment tout changer ! effectivement sa fonctionne sans soucis
merci
Hors ligne
#1637 Le 20/05/2012, à 09:48
yakusa77
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
parfois aussi j'ai ce message lorsque je selectionne une console mais pas sur toute
./glade2script.py:2238: GtkWarning: Failed to set text from markup due to error parsing markup: Erreur à la ligne 1 : L'entité ne se termine pas par un point-virgule ; vous avez probablement utilisé une esperluette sans intention d'écrire une entité - échappez l'esperluette avec &
je comprend pas pourquoi ... mais sa ne gene pas le bon fonctionnement
Hors ligne
#1638 Le 20/05/2012, à 17:31
#1639 Le 20/05/2012, à 19:25
Hizoka
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
Voila de quoi travailler pour ton retour
1) Est-il possible d'envoyer plusieurs lignes directement dans un tree avec @@ pour separer les lignes comme le fait lz chargement de variable.
2) Le chargement de fichier de config via echo "EXEC@@ParseConfig('fichier').load_config(self.gui)" execute chaque commande avec la nouvelle variable chargée ?
Ce n'est pas sensé bloquer le coté graphique ?
Ex :
=> [[ PY ]] => EXEC@@ParseConfig('/home/hizoka/.config/screencastor/ezez.cfg').load_config(self.gui)
[[ INIT CONFIG ]]
[[ CONFIG LOAD ]] ENTRY
=> [[ PY ]] => :: FIFO write :: _pref_name ezez
....
=> [[ PY ]] => DEBUG=> in bash NOT GET _pref_name ezez
=> [[ PY ]] => ====>>> fonction pref_name : ezez
3) Peut on rendre insensible une box ?
si de base je met la box en insensible et que j'execute :<metadata lang=Batchfile prob=0.08 />
echo 'SET@_bigbox.props.sensitive = "True"'
ca passe bien
mais l'inverse ne marche pas, une idée ?
4) Alors là, par contre c'est tres chiant, en utilisant un fichier de config (même vide ou ne contenant que des coches) , il fait planter mkv-extractor-gui...
Tout le coté graphique fonctionne, mais plus aucun lien avec le script...
Il faudra qu'on voit ça en live car j'ai grave galéré pour trouver que ca venait du config...
5) Peut on définir la taille de la mémoire du terminal ?
6) Une possibilité qu'on a deja evoqué mais qui je trouve serait surpuissante, c'est de pouvoir utiliser une combobox avec des coches, niveau ergonomie, ca serait le top
7) Je pige pas la commande CONFIG@@SET, c'est pour modifier une variable ?
sauvegarder une variable dans le fichier de conf ?
Car aucune de mes 2 suppositions ne fonctionnent...
8) Je ne retrouve plus comment on envoie une commande depuis un autre terminal dans g2s, j'ai essayé :
echo 'SET@_statusbar.push(0, "oui vive moi")' > /tmp/FIFO27625
=> [[ PY ]] => DEBUG=> in bash NOT GET SET@_statusbar.push(0, "oui vive moi")
mais pas de write...
9) J'ai un retour au demarrage d'un logiciel :
./lpsm.py:1835: RuntimeWarning: missing handler 'on_activate'
self.widgets.connect_signals(self)
je vois pas ce qu'il veut dire.... mes on_activate me semble ok et font bien appel à un bouton...
10) Ton manpage creator ne fonctionne pas chez moi.
Il y avait un soucis dans la commande g2s (g2s appellé au lieu de ./glade2script.py) mais maintenant j'ai :<metadata lang=Python prob=0.41 />
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
self.run()
File "/home/hizoka/Scripts_et_logiciels/scripts/lpsm/usr/share/lpsm/manpagecreator/manpagecreator.py", line 385, in run
for f in os.listdir('mans'):
OSError: [Errno 2] Aucun fichier ou dossier de ce type: 'mans'
^CTraceback (most recent call last):
File "./glade2script.py", line 4596, in <module>
m.main()
File "./glade2script.py", line 2187, in main
gtk.main()
KeyboardInterrupt
au lancement
Je continue ma liste
11) Y aurait-il moyen de sauvegarder la valeur des combobo dans le fichier de config ?
car dans le cas d'une combobox qui n'a pas toujours le même contenu, le numero de ligne ne sert à rien...
12) Je pige pas pourquoi, il me dit :
Traceback (most recent call last):
File "./lpsm.py", line 729, in on_clicked
getattr(self.th.IMPORT, widget.get_name()) ('clicked')
AttributeError: 'MyThread' object has no attribute 'IMPORT'
Traceback (most recent call last):
File "./lpsm.py", line 565, in on_combo
getattr(self.th.IMPORT, nom) (valeur)
AttributeError: 'MyThread' object has no attribute 'IMPORT'
à chaque interaction sur mon glade apres avoir fait un
echo 'CONFIG@@SAVE@@'
La sauvegarde se fait bien par contre...
Dernière modification par Hizoka (Le 20/05/2012, à 19:39)
Hors ligne
#1640 Le 24/05/2012, à 12:41
AnsuzPeorth
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
Oulahhhh, j'aurais jamais du ajouter le fichier de config, j'avais oublié hizoka et ses demandes exotiques
1) non
2) le coté graphique est bloqué uniquement au démarrage, mais je peux modifier pour que ce soit tjrs bloqué. Tu peux aussi le bloquer depuis ton bash !
3) Tu as essayé avec set_active ?
4) ...
5) je pense pas (tu parle de memoire, pas de l'historique ?)
6) No comment ....
7) Cette commande modifie le dictionnaire où sont stocker les variables, c'est lors de l'enregistrement que tu verras les modifs, dans le fichier de config.
8) Tu peux appeler une fonction de ton bash, mais pas directement une commande G2S (ou faut modifier la boucle de fin, a voir ce que tu veux !)
9) Erreur etrange en effet !!! Cette erreur signale qu'il n'y a pas de fonction on_activate, alors qu'elle y est !
10) Depuis le temps, tu devrais apprendre à lire les erreurs python, elle signifie qu'il n'y a pas de dossier mans, nécessaire pour ce soft.
11) nop, trop galere, j'avais essayé, mais faut tout modifier, car sauver juste qqles valeurs, tu vas ensuite vouloir sauver le combo entier, et trop pénible a mettre en place ...
12) Doit avoir une petite erreur dans le code, je look.
@yakusa77
L'erreur est pourtant clair, tu utilise un & dans une commande set_markup, il faut la remplacer par & (voir doc également !)
Hors ligne
#1641 Le 24/05/2012, à 23:36
Hizoka
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
1) Est-il possible d'envoyer plusieurs lignes directement dans un tree avec @@ pour separer les lignes comme le fait lz chargement de variable.
=> non
Serait-il possible d'ajouter cette possibilité ?
J'explique pourquoi :
1 - Je charge un fichier de config, du coup la var G2S_tree vaut ligne1@@ligne2@ligne3
2 - Je change le tree à la main (ajout de ligne ou autre...)
3 - Je voudrais recharger le tree comme au chargement, je n'aurais qu'a faire un END avec la var G2S_tree
2) le coté graphique est bloqué uniquement au démarrage, mais je peux modifier pour que ce soit tjrs bloqué. Tu peux aussi le bloquer depuis ton bash !
Merde, me rappelle plus comment on bloque via le bash (ce qui serait suffisant...).
Désolé.
3) Peut on rendre insensible une box ?
si de base je met la box en insensible et que j'execute :<metadata lang=Batchfile prob=0.08 />
echo 'SET@_bigbox.props.sensitive = "True"'
ca passe bien
mais l'inverse ne marche pas, une idée ?
=> Tu as essayé avec set_active ?
J'avais commencé par ça mais il me dit qu'une box n'a pas cette option.
5) Peut on définir la taille de la mémoire du terminal ?
=> je pense pas (tu parle de memoire, pas de l'historique ?)
Je parle juste du nombre de lignes que tu peux remonter pour voir le retour des commandes (certaines commandes qui sont bavardes sont coupées et du coup le début n'est plus affichable)
7) Je pige pas la commande CONFIG@@SET, c'est pour modifier une variable ? sauvegarder une variable dans le fichier de conf ?
=> Cette commande modifie le dictionnaire où sont stocker les variables, c'est lors de l'enregistrement que tu verras les modifs, dans le fichier de config.
Donc je fais un SET pour modifier une variable et c'est ma valeur qui sera prise en compte lors de la sauvagarde des configs, c'est ça ?
Dans ce cas là, je peux utiliser ça pour sauvegarder une valeur d'un combobox non ?
Dans le fichier de config dans MISC : val_combo1 =
Dans le script :
function combo1
{
combo1=${@}
echo "CONFIG@@SET@@MISC@@val_combo1@@${@}"
# Sauvegarde maintenant ou plus tard en fonction de ce qu'on veut
}
Il resterait plus qu'a faire un FIND avec la variable val_combo1 au demarrage du logiciel.
Ca le ferait ça ?
8) Je ne retrouve plus comment on envoie une commande depuis un autre terminal dans g2s,
=> Tu peux appeler une fonction de ton bash, mais pas directement une commande G2S (ou faut modifier la boucle de fin, a voir ce que tu veux !)
En fait, ca permettrait de tester des commandes ou des trucs comme ça sans avoir à creer des boutons bidons contenant une commande pygtk par ex. Ca serait sympa et pratique. (ça faisait suite en fait à mes tests pour la sensibilité de la box ci-dessus)
9) Erreur etrange en effet !!! Cette erreur signale qu'il n'y a pas de fonction on_activate, alors qu'elle y est !
Et cette erreur n’apparrait qu'une seule fois alors que j'utilise pas mal de fois ce signal...
Ca bloque rien à priori mais bon...
Dans la doc :
-s/--sh
à utiliser pour donner un nom différent ou pour donner des arguments à ce script
sinon, le script associé devra porter le même nom que le glade et ce trouver dans le même dossier que ce dernier
Nom du script associé
Il faudrait juste trad ça
--load-config
@exemple --load-config="configfile.cfg"
Load config from file
Il faudrait preciser que contraitrement à auto-config, les widgets ne sont pas modifiés
Voilou
Encore des demandes, des questions, des avis, Du grand hizo
Dernière modification par Hizoka (Le 24/05/2012, à 23:37)
Hors ligne
#1642 Le 25/05/2012, à 11:43
AnsuzPeorth
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
Serait-il possible d'ajouter cette possibilité ?
... Garde le sous le coude, je le ferais peut etre plus tard, en attendant:
echo -e "${G2S_tree//@@/\n}" | xargs -I% echo "TREE@@END@@%"
Merde, me rappelle plus comment on bloque via le bash (ce qui serait suffisant...).
echo "SET@window_realized = False"
essai sans les "
echo 'SET@_bigbox.props.sensitive = "True"'
echo 'SET@_bigbox.props.sensitive = True'
Je parle juste du nombre de lignes que tu peux remonter pour voir le retour des commandes
-1 pour garder l'integralité de l'historique, sinon, indiquer nombre de lignes.
http://developer.gnome.org/vte/unstable … minal.html
echo "SET@_terminal.set_scrollback_lines(-1)"
Donc je fais un SET pour modifier une variable et c'est ma valeur qui sera prise en compte lors de la sauvagarde des configs, c'est ça ?
oui
Ca le ferait ça ?
je pense ... A essayer !
Pour envoyer direct dans FIFO, pour pouvoir envoyer une commande GET, il faudra modifier la boucle de fin,un truc du genre
if [[ "$ligne" =~ ^GET@ ]]
Sinon, pour les autres commandes, ca devrait faire:
echo 'echo SET@.....' > /tmp/FIFO27625
Pour on_activate, je comprends pas cette erreur, a voir ....
Pour la doc, je verrais plus tard, prochaine MAj ...
Hors ligne
#1643 Le 25/05/2012, à 19:17
Hizoka
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
echo -e "${G2S_tree//@@/\n}" | xargs -I% echo "TREE@@END@@_tree@@%"
nickel ça !
Vis à vis du blocage, J'ai quelques soucis :
# Blocage graphique
echo "SET@window_realized = False"
# Chargement du fichier de config
echo "EXEC@@ParseConfig('${G2S_pref_liste}').load_config(self.gui)"
# Debloquage graphique
sleep 1; echo "SET@window_realized = True"
de façon aléatoire soit ça fonctionne bien soit il execute quand meme des commandes malgres un sleep de 1 seconde...
=> [[ PY ]] => SET@window_realized = False
=> [[ PY ]] => EXEC@@ParseConfig('/home/hizoka/.config/screencastor/teste.cfg').load_config(self.gui)
[[ INIT CONFIG ]]
[[ CONFIG LOAD ]] ENTRY
[[ CONFIG LOAD ]] TOGGLE
[[ CONFIG LOAD ]] WINDOW:screencastor
[[ CONFIG LOAD ]] LABEL
[[ CONFIG LOAD ]] COMBO
[[ CONFIG LOAD ]] SPIN
[[ CONFIG LOAD ]] FILECHOOSER
[[ CONFIG LOAD ]] PANED
[[ CONFIG LOAD ]] NOTEBOOK
[[ CONFIG LOAD ]] COLORBUTTON
[[ CONFIG LOAD ]] COLORDIALOG
[[ CONFIG LOAD ]] FONT
[[ CONFIG LOAD ]] CALENDAR
[[ CONFIG LOAD ]] TREEVIEW
[[ CONFIG LOAD ]] TEXTVIEW
[[ CONFIG LOAD ]] MISC
[[ CONFIG LOADED ]]
=> [[ PY ]] => SET@window_realized = True
là c'est passé mais la :
=> [[ PY ]] => SET@window_realized = False
=> [[ PY ]] => EXEC@@ParseConfig('/home/hizoka/.config/screencastor/0Defaut.cfg').load_config(self.gui)
=> [[ PY ]] => :: FIFO write :: _pref_liste Defaut.cfg
[[ INIT CONFIG ]]
[[ CONFIG LOAD ]] ENTRY
=> [[ PY ]] => :: FIFO write :: _pref_name Nom du code à sauvegarder
[[ CONFIG LOAD ]] TOGGLE
=> [[ PY ]] => :: FIFO write :: _debit_variable False
=> [[ PY ]] => :: FIFO write :: _debit_fixe True
=> [[ PY ]] => :: FIFO write :: _webm False
=> [[ PY ]] => :: FIFO write :: _x264 True
[[ CONFIG LOAD ]] WINDOW:screencastor
[[ CONFIG LOAD ]] LABEL
[[ CONFIG LOAD ]] COMBO
=> [[ PY ]] => :: FIFO write :: _video_vpre none
=> [[ PY ]] => :: FIFO write :: _sortie_extension_video mkv
[[ CONFIG LOAD ]] SPIN
=> [[ PY ]] => :: FIFO write :: _video_bitrate 700.0
=> [[ PY ]] => :: FIFO write :: _video_qmin 10.0
=> [[ PY ]] => :: FIFO write :: _video_qmax 50.0
=> [[ PY ]] => :: FIFO write :: _video_framekey 250.0
[[ CONFIG LOAD ]] FILECHOOSER
=> [[ PY ]] => :: FIFO write :: _sortie_dossier /home
=> [[ PY ]] => :: FIFO write :: _sortie_dossier /home/hizoka
[[ CONFIG LOAD ]] PANED
[[ CONFIG LOAD ]] NOTEBOOK
[[ CONFIG LOAD ]] COLORBUTTON
[[ CONFIG LOAD ]] COLORDIALOG
[[ CONFIG LOAD ]] FONT
[[ CONFIG LOAD ]] CALENDAR
[[ CONFIG LOAD ]] TREEVIEW
[[ CONFIG LOAD ]] TEXTVIEW
[[ CONFIG LOAD ]] MISC
[[ CONFIG LOADED ]]
=> [[ PY ]] => SET@window_realized = True
=> [[ PY ]] => DEBUG=> in bash NOT GET
=> [[ PY ]] => DEBUG=> in bash NOT GET _pref_name Nom du code à sauvegarder
=> [[ PY ]] => DEBUG=> in bash NOT GET _debit_variable False
=> [[ PY ]] => DEBUG=> in bash NOT GET _debit_fixe True
=> [[ PY ]] => code final execute par : _debit_fixe
=> [[ PY ]] => TEXT@@CLEAR@@_code_ffmpeg
=> [[ PY ]] => TEXT@@END@@_code_ffmpeg@@ffmpeg -f "alsa" -i "0" -f "x11grab" -r:v "30" -s:v "2880x1200" -i ":0+0,0" -codec:a "libvorbis" -ar:a "44100" -b:a "128k" -codec:v "libx264" -crf "20" -me_method "epzs" -g "250" -subq "6" -keyint_min "25" -trellis "1" -bf "16" -threads "0" -b:v "700k" -bt "4000k" -r:v "25" "/home/hizoka/Screencastor_1337964646.mkv"
=> [[ PY ]] => DEBUG=> in bash NOT GET _webm False
=> [[ PY ]] => DEBUG=> in bash NOT GET _x264 True
=> [[ PY ]] => MULTI@@SET@@hide()@@_webm_frame1,_webm_frame2
=> [[ PY ]] => MULTI@@SET@@show()@@_x264_frame1,_x264_frame2,_x264_frame3,_separator_2,_pasflv_frame2
=> [[ PY ]] => SET@audio_codec.set_sensitive(True)
=> [[ PY ]] => COMBO@@FINDSELECT@@_sortie_extension_video@@mkv
=> [[ PY ]] => DEBUG=> in bash NOT GET
=> [[ PY ]] => DEBUG=> in bash NOT GET _video_vpre none
=> [[ PY ]] => code final execute par : _video_vpre
=> [[ PY ]] => TEXT@@CLEAR@@_code_ffmpeg
=> [[ PY ]] => :: FIFO write :: _sortie_extension_video mkv
=> [[ PY ]] => TEXT@@END@@_code_ffmpeg@@ffmpeg -f "alsa" -i "0" -f "x11grab" -r:v "30" -s:v "2880x1200" -i ":0+0,0" -codec:a "libvorbis" -ar:a "44100" -b:a "128k" -codec:v "libx264" -crf "20" -me_method "epzs" -g "250" -subq "6" -keyint_min "25" -trellis "1" -bf "16" -threads "0" -b:v "700k" -bt "4000k" -r:v "25" "/home/hizoka/Screencastor_1337964646.mkv"
=> [[ PY ]] => DEBUG=> in bash NOT GET
=> [[ PY ]] => DEBUG=> in bash NOT GET _sortie_extension_video mkv
=> [[ PY ]] => code final execute par : _sortie_extension_video
=> [[ PY ]] => TEXT@@CLEAR@@_code_ffmpeg
=> [[ PY ]] => TEXT@@END@@_code_ffmpeg@@ffmpeg -f "alsa" -i "0" -f "x11grab" -r:v "30" -s:v "2880x1200" -i ":0+0,0" -codec:a "libvorbis" -ar:a "44100" -b:a "128k" -codec:v "libx264" -crf "20" -me_method "epzs" -g "250" -subq "6" -keyint_min "25" -trellis "1" -bf "16" -threads "0" -b:v "700k" -bt "4000k" -r:v "25" "/home/hizoka/Screencastor_1337964646.mkv"
=> [[ PY ]] => DEBUG=> in bash NOT GET
=> [[ PY ]] => DEBUG=> in bash NOT GET _video_bitrate 700.0
=> [[ PY ]] => code final execute par : _video_bitrate
=> [[ PY ]] => TEXT@@CLEAR@@_code_ffmpeg
=> [[ PY ]] => TEXT@@END@@_code_ffmpeg@@ffmpeg -f "alsa" -i "0" -f "x11grab" -r:v "30" -s:v "2880x1200" -i ":0+0,0" -codec:a "libvorbis" -ar:a "44100" -b:a "128k" -codec:v "libx264" -crf "20" -me_method "epzs" -g "250" -subq "6" -keyint_min "25" -trellis "1" -bf "16" -threads "0" -b:v "700k" -bt "4000k" -r:v "25" "/home/hizoka/Screencastor_1337964646.mkv"
=> [[ PY ]] => DEBUG=> in bash NOT GET
=> [[ PY ]] => DEBUG=> in bash NOT GET _video_qmin 10.0
=> [[ PY ]] => code final execute par : _video_qmin
=> [[ PY ]] => TEXT@@CLEAR@@_code_ffmpeg
=> [[ PY ]] => TEXT@@END@@_code_ffmpeg@@ffmpeg -f "alsa" -i "0" -f "x11grab" -r:v "30" -s:v "2880x1200" -i ":0+0,0" -codec:a "libvorbis" -ar:a "44100" -b:a "128k" -codec:v "libx264" -crf "20" -me_method "epzs" -g "250" -subq "6" -keyint_min "25" -trellis "1" -bf "16" -threads "0" -b:v "700k" -bt "4000k" -r:v "25" "/home/hizoka/Screencastor_1337964646.mkv"
=> [[ PY ]] => DEBUG=> in bash NOT GET
=> [[ PY ]] => DEBUG=> in bash NOT GET _video_qmax 50.0
=> [[ PY ]] => code final execute par : _video_qmax
=> [[ PY ]] => TEXT@@CLEAR@@_code_ffmpeg
=> [[ PY ]] => TEXT@@END@@_code_ffmpeg@@ffmpeg -f "alsa" -i "0" -f "x11grab" -r:v "30" -s:v "2880x1200" -i ":0+0,0" -codec:a "libvorbis" -ar:a "44100" -b:a "128k" -codec:v "libx264" -crf "20" -me_method "epzs" -g "250" -subq "6" -keyint_min "25" -trellis "1" -bf "16" -threads "0" -b:v "700k" -bt "4000k" -r:v "25" "/home/hizoka/Screencastor_1337964646.mkv"
=> [[ PY ]] => DEBUG=> in bash NOT GET
=> [[ PY ]] => DEBUG=> in bash NOT GET _video_framekey 250.0
=> [[ PY ]] => code final execute par : _video_framekey
=> [[ PY ]] => TEXT@@CLEAR@@_code_ffmpeg
=> [[ PY ]] => TEXT@@END@@_code_ffmpeg@@ffmpeg -f "alsa" -i "0" -f "x11grab" -r:v "30" -s:v "2880x1200" -i ":0+0,0" -codec:a "libvorbis" -ar:a "44100" -b:a "128k" -codec:v "libx264" -crf "20" -me_method "epzs" -g "250" -subq "6" -keyint_min "25" -trellis "1" -bf "16" -threads "0" -b:v "700k" -bt "4000k" -r:v "25" "/home/hizoka/Screencastor_1337964646.mkv"
=> [[ PY ]] => DEBUG=> in bash NOT GET _sortie_dossier /home
=> [[ PY ]] => DEBUG=> in bash NOT GET _sortie_dossier /home/hizoka
=> [[ PY ]] => DEBUG=> in bash NOT GET _sortie_extension_video mkv
=> [[ PY ]] => code final execute par : _sortie_extension_video
=> [[ PY ]] => TEXT@@CLEAR@@_code_ffmpeg
=> [[ PY ]] => TEXT@@END@@_code_ffmpeg@@ffmpeg -f "alsa" -i "0" -f "x11grab" -r:v "30" -s:v "2880x1200" -i ":0+0,0" -codec:a "libvorbis" -ar:a "44100" -b:a "128k" -codec:v "libx264" -crf "20" -me_method "epzs" -g "250" -subq "6" -keyint_min "25" -trellis "1" -bf "16" -threads "0" -b:v "700k" -bt "4000k" -r:v "25" "/home/hizoka/Screencastor_1337964647.mkv"
il en a execute une bonne partie...
en passant via une commande g2s, ca ne reglerait pas le probleme ?
et de temps en temps j'ai le droit à :
screencastor.py: Fatal IO error 11 (Ressource temporairement non disponible) on X server :0.
etrange car mon pc n'est pas à fond....
echo 'SET@_bigbox.props.sensitive = True'
Nickel aussi ça ! etrange que ça marche avec les " et le true...
echo "SET@_terminal.set_scrollback_lines(-1)"
Youpie
J'avais pas pensé à -1...
echo 'echo SET@.....' > /tmp/FIFO27625
Ouais pas besoin de get juste de set, mais j'entourais la commande de " alors qu'il ne fallait rien
Pour mon idée de save de valeur de combobox, pas le temps de teste avant le taf donc je verrai plus tard.
EDIT : Je pense qu'il faudrait modifier la fonction de save des config.
Faire comme tu le proposé à la base, indiquer les widgets à save, et si on les veut tous, soit ne pas mettre de widget ou mettre ALL.
Car la je veux save 1-2 widgets mais pas tout, du coup il faudrait que je tape une commande contenant tous mes widgets a ne pas save... ce qui reste d'être assez lourd...
Voilou
merci beaucoup à toi !
Dernière modification par Hizoka (Le 27/05/2012, à 19:24)
Hors ligne
#1644 Le 28/05/2012, à 20:42
Hizoka
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
un petit soucis avec la commande CONFIG@@SET :
CONFIG@@SET@@ppa_save@@True|ppa:hizo/logiciels|3FD9D589@@False|ppa:hizo/tests|3FD9D589
puis save :
Traceback (most recent call last):
File "./lpsm.py", line 3728, in CONFIGSET
section, var, value = sortie.split('@@')[2:]
ValueError: too many values to unpack
Le fait de de foutre des @@ pose soucis non ?
la mon but est de faire une copie de sauvegarde de la valeur d'un tree.
Hors ligne
#1645 Le 29/05/2012, à 20:10
yakusa77
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
Dans un combo, comment faire pour récupéré une valeur qui n'es pas affiché:
j'ai créer un tableau à 3 colonne via glade (donc en dur) la seconde (indice 1) est celle qui s'affiche. Dans la troisième colonne je stock une info que je veux exploité
mais je ne sait pas comment récupéré sa valeur. je précise que c'est un tableau gchararray dans un gtkliststore. Je sais pas si j'ai me fait bien comprendre ?
Hors ligne
#1646 Le 30/05/2012, à 03:09
Hizoka
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
yakusa77 => Jamais fait ça, mais je ne pense pas que g2s le permette pour le moment.
Enfin attends le retour de ansuz.
Sinon, c'est une bonne idée
Perso j'ai fait un truc du genre moi :
116 - Lent/Qualité
216 - Moyen
214 - Rapide/Qualité médiocre
Et je récupérais ${1} afin de n'avoir que la 1ere valeur.
Hors ligne
#1647 Le 30/05/2012, à 07:46
yakusa77
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
Alors je vais développé un peu:
glade permet de faire ceci, pour une combobox ... faire un tableau avec le nombre de colonne que l'on souhaite
pour ma part , étant donnée que je travail sur un frontend d’émulateur de jeux en ce moment, j'ai besoin de d'indiqué dans l'une des colonnes quel pilote à besoin que l'on lui fournisse un bios pour fonctionné...
Mais je ne veut pas (plus) que cela apparaisse a l'ecran ...
avec le widget "GtkCellRendererText" lier au combobox on peut désigné quel colonne est affiché dans le combo.
Donc, j'ai créer un tableau comme ceci
'pilote [0]' 'console [1]' 'bios [2]'
avec le on_combo je récupère la première valeur, ce qui permet à une partie de fonctionner, mais le autres sont ignoré visiblement ce qui empêche mon test sur le troisième champs.
Sinon j'ai essayer avec ${2} au lieu de ${@}, mais bien entendu cela n'es fonctionne pas.
Quand je faisait du zenity je cachait des colonnes dans les listes, le principe es le même je pense...
Hors ligne
#1648 Le 30/05/2012, à 12:58
AnsuzPeorth
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
dsl, j'étais pas la ces jours ci ...
Le fait de de foutre des @@ pose soucis non ?
Logiquement non, essai déjà en indiquant la section ...
EDIT : Je pense qu'il faudrait modifier la fonction de save des config.
ouais ... euh, ben ca dépends de l'utilisation, car soit on indique une blackliste, soit une whiteliste, l'une ou l'autre, ca posera le même soucis !
@yakusa77
Ce n'est pas possible avec les combo en l'état, pour faire comme ça, je devrait tout modifier (la modification qu'hizoka veut depuis pas mal de temps d'ailleurs ... vous vous êtes concerté ou koi )
Bref, soi tu utilise un tree, soit tu te crée un tableau, avec les key/value que tu as besoin, et le $1 recu dans ta fonction correspondra à la key !
Sinon, tu peux essayer un TREE@@GET@@_combo, tu aura la ligne selectionné (j'ai pas essayé, mais ca devrait faire ...)
Je n'ai pas laisser le choix à l'user de faire son treestore (pour les combo ou treeviexw), car c'est assez complexe (ce que tu as fait, le créer dans dans glade), je voulais un truc facile, et aller gratter dans glade et s'emmerder avec les treestore, alors que c'est bien plus simple via les commandes g2s ou via option de lancement !
Hors ligne
#1649 Le 30/05/2012, à 18:33
Hizoka
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
Logiquement non, essai déjà en indiquant la section ...
Putain de buse...
ouais ... euh, ben ca dépends de l'utilisation, car soit on indique une blackliste, soit une whiteliste, l'une ou l'autre, ca posera le même soucis !
Au pire tu peux pas faire 2 versions ?
CONFIG@@WHITE et CONFIG@@BLACK
Si tu modifies tout le systeme des combobox, il faudra passer par glade pour les gerer ?
si oui alors ça vaut pas le coup... il plante énormément quand je joue avec...
Ansuz, as tu vu mon message numero 1643 ?
Hors ligne
#1650 Le 30/05/2012, à 21:42
AnsuzPeorth
Re : [glade2script-GTK2] Interface graphique pour script bash ou autre.
Au pire tu peux pas faire 2 versions ?
Un jours peut être ....
Si tu modifies tout le systeme des combobox, il faudra passer par glade pour les gerer ?
Non, mais de toute façon, c'est pas au programme ...
Ansuz, as tu vu mon message numero 1643 ?
Pour le blocage de l'interface ? Essai de mettre le sleep également avant la commande EXEC (ton ordi trop puissant ...)
Hors ligne |
JavaScript
stevemtno — 2012-01-10T12:51:47-05:00 — #1
I'm guessing this is a pretty easy problem to fix, but I can't find any code that will do what I need.
I have a group of images (all different sizes). Each image will have a corresponding text link. I need to be able to click on one of the text links and display the corresponding image in a separate div.
I found this example on Dynamic Drive, and it works, but the text links in this case are in a select box. If there is an easy way to just convert the select box links to plain text links, that would be ideal.
<form name="dynamicselector">
<table border="0" width="100%" cellspacing="0" cellpadding="0" height="178">
<tr>
<td width="35%" valign="top" align="left">
<select name="dynamicselector2" size="4" onChange="generateimage(this.options[this.selectedIndex].value)">
<option value="images/menus/mandarin-house-chef-special-01-sm.jpg" selected>DHTML Guide</option>
<option value="images/menus/mandarin-house-chef-special-02-sm.jpg">DHTML QuickStart</option>
<option value="images/menus/mandarin-house-chef-special-03-sm.jpg">HTML4</option>
<option value="http://images.amazon.com/images/P/1861001746.01.TZZZZZZZ.jpg">IE5 DHTML</option>
</select>
</td>
<td width="65%" valign="top" align="left">
<ilayer id="dynamic1" width=100% height=178>
<layer id="dynamic2" width=100% height=178>
<div id="dynamic3"></div>
</layer>
</ilayer>
</td>
</tr>
</table>
</form>
<script>
//Dynamic Image selector Script- © Dynamic Drive (www.dynamicdrive.com)
//For full source code, installation instructions,
//100's more DHTML scripts, visit dynamicdrive.com
//enter image descriptions ("" for blank) this text appears under the image
var description=new Array()
description[0]="DHTML: The Definitive Guide"
description[1]="DHTML Visual QuickStart Guide"
description[2]="HTML 4 and DHTML"
description[3]="IE5 DHTML Reference"
var ie4=document.all
var ns6=document.getElementById
var tempobj=document.dynamicselector.dynamicselector2
if (ie4||ns6)
var contentobj=document.getElementById? document.getElementById("dynamic3"): document.all.dynamic3
function generateimage(which){
if (ie4||ns6){
contentobj.innerHTML='<center>Loading image...</center>'
contentobj.innerHTML='<center><img src="'+which+'"><br><br>'+description[tempobj.options.selectedIndex]+'</center>'
}
else if (document.layers){
document.dynamic1.document.dynamic2.document.write('<center><img src="'+which+'"><br><br>'+description[tempobj.options.selectedIndex]+'</center>')
document.dynamic1.document.dynamic2.document.close()
}
else
alert('You need NS 4+ or IE 4+ to view the images!')
}
function generatedefault(){
generateimage(tempobj.options[tempobj.options.selectedIndex].value)
}
if (ie4||ns6||document.layers){
if (tempobj.options.selectedIndex!=-1){
if (ns6)
generatedefault()
else
window.onload=generatedefault
}
}
</script>
Or if anyone has a better suggestion (I know the above code is really old), I'd be open to that as well.
Thanks in advance,
Steve
aussiejohn — 2012-01-10T15:56:39-05:00 — #2
It references IE 4 and Netscape 4, that's indeed a fair indication of old scripts
It wouldn't be too hard to write something like this from scratch.
In terms of markup you could have something like:
<ul class="gallery">
<li><a href="/path/to/image.jpg" title="The longer description">Some link text </a></li>
<li><a href="/path/to/image.jpg" title="The longer description">Some link text </a></li>
<li><a href="/path/to/image.jpg" title="The longer description">Some link text </a></li>
</ul>
Then basic pseudocode for the JS would look like:
Find all gallery lists
Iterate through all gallery lists to find links
apply (click) event handler to links
prevent the default event from firing
get the image path from the href and use it to generate a new image in the location you wish
get the title attribute and add it below the image
stevemtno — 2012-01-10T15:59:54-05:00 — #3
I don't have a clue what to do here. Can you be a little more specific? The HTML part of it is no problem. The JS is another story...
system — 2012-01-10T16:48:59-05:00 — #4
Something like this should help you get started.
The links for the images and link text are created dynamically according to the data in the picData array.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title></title>
<style type="text/css">
#linksCont {
list-style-type: none;
}
#img1{
display: none;
}
</style>
<script type="text/javascript">
var picData = [
['pic1.jpg','show pic 1'],
['pic2.jpg','show pic 2'],
['pic3.jpg','show pic 3'],
['pic4.jpg','show pic 4']
];
//preload the pics
var picsObj = [];
for(i=0; i < picData.length; i++){
picsObj[i] = [];
picsObj[i][0] = new Image();
picsObj[i][0].src = picData[i][0];
picsObj[i].lnkText = picData[i][1];
}
function showPic(num){
img1Obj.style.display='inline';
img1Obj.src = picsObj[num][0].src;
}
window.onload=function(){
img1Obj = document.getElementById('img1');
//create the links
var ulObj = document.getElementById('linksCont');
for(i=0; i < picsObj.length; i++){
var newLi = document.createElement('li');
var newA = document.createElement('a');
newA.num = i;
newA.appendChild(document.createTextNode(picsObj[i].lnkText));
newA.href='';
newA.onclick=function(){showPic(this.num);return false;}
newLi.appendChild(newA);
ulObj.appendChild(newLi);
}
}
</script>
</head>
<body>
<div>
<img src="" id="img1" alt="" />
</div>
<ul id="linksCont"></ul>
</body>
</html>
stevemtno — 2012-01-10T17:43:10-05:00 — #5
Thanks for the help, Max Height! I really appreciate it.
Is there any way to put a link behind the images?
centered_effect — 2012-01-10T19:03:07-05:00 — #6
Here is an alternative to Max's post:
<ul id="linksCont"></ul>
<div id="picContainer"></div>
<script>
var picData = ['447.jpg', '483.jpg', '494.jpg'],
linkCont = document.getElementById('linksCont'),
picCont = document.getElementById('picContainer'),
imgLinks = [],
i;
for( i = 0; i < picData.length; i++ ) {
linkCont.innerHTML += '<li><a href="#" class="imgLink" rel="' + picData[i] + '">Show Picture ' + (i + 1) + '</a></li>';
}
// querySelectorAll compatibility: developer.mozilla.org/En/DOM/Document.querySelectorAll#Browser_compatibility
imgLinks = document.querySelectorAll('.imgLink');
for( i = 0; i < imgLinks.length; i++ ) {
imgLinks[i].onclick = function() {
picCont.innerHTML = '<img src="' + this.rel + '">';
};
}
</script>
If you want more information, can you do an object filled with the meta data needed like so:
var imgs = [
{
src: 'img1.png',
alt: 'First Image',
text: 'This is an image done on 1/1/2011.'
},
{
src: 'img2.png',
alt: 'Second Image',
text: 'This is an image done on 1/2/2011.'
},
{
src: 'img3.png',
alt: 'Third Image',
text: 'This is an image done on 1/3/2011.'
},
];
for( var i = 0; i < imgs.length; i++ ) {
var imgSrc = imgs[i].src,
imgAlt = imgs[i].alt,
imgTxt = imgs[i].text;
console.log(imgTxt + '<img src="' + imgSrc + '" alt="' + imgAlt + '">')
}
system — 2012-01-10T20:27:55-05:00 — #7
Yes, that can be done fairly easily. This is starting to sound a bit like some sort of homework exercise and so you should post at least your attempt and we can then help you get it working.
But essentially, all you need to do is:
1) wrap the <img> in an <a> in the html
2) add the url you want each clicked image to navigate to in the image's row in picData
3) add 1 line of code in showPic(num) to set the href of the <img>'s <a> to the url for that image
stevemtno — 2012-01-11T10:29:57-05:00 — #8
1 - I think I got that part right
2 - this one too
3 - Purely a guess on my part. I have no clue what to do here.
Here's what I've got so far:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title></title>
<style type="text/css">
#linksCont {
list-style-type: none;
}
#img1{
display: none;
}
</style>
<script type="text/javascript">
var picData = [
['http://www.nova.edu/hpd/otm/pics/4fun/11.jpg','show pic 1','http://www.thenightowl.com'],
['http://www.nova.edu/hpd/otm/pics/4fun/12.jpg','show pic 2','http://www.thenightowl.com'],
['http://www.nova.edu/hpd/otm/pics/4fun/13.jpg','show pic 3','http://www.thenightowl.com'],
['http://www.nova.edu/hpd/otm/pics/4fun/14.jpg','show pic 4','http://www.thenightowl.com']
];
//preload the pics
var picsObj = [];
for(i=0; i < picData.length; i++){
picsObj[i] = [];
picsObj[i][0] = new Image();
picsObj[i][0].src = picData[i][0];
picsObj[i].lnkText = picData[i][1];
}
function showPic(num){
img1Obj.style.display='inline';
img1Obj.src = picsObj[num][0].src;
img1Obj.href = picsObj[num][2].href;
}
window.onload=function(){
img1Obj = document.getElementById('img1');
//create the links
var ulObj = document.getElementById('linksCont');
for(i=0; i < picsObj.length; i++){
var newLi = document.createElement('li');
var newA = document.createElement('a');
newA.num = i;
newA.appendChild(document.createTextNode(picsObj[i].lnkText));
newA.href='';
newA.onclick=function(){showPic(this.num);return false;}
newLi.appendChild(newA);
ulObj.appendChild(newLi);
}
}
</script>
</head>
<body>
<div>
<a href=""><img src="" id="img1" alt="" /></a>
</div>
<ul id="linksCont"></ul>
</body>
</html>
Am I close?
system — 2012-01-11T15:40:31-05:00 — #9
You need to give the <a> an id and then use getElementById() (google it for more info if required) to change the link's href to the url in picData for the current image.
Use the error console in your browser to view any error messages when you open your web page. |
This is a part of a large csv file which I have:
"66.35.223.128","66.35.223.143","1109647232","1109647247","AU","Australia""66.35.223.144","66.35.227.191","1109647248","1109648319","US","United States""66.35.227.192","66.35.227.207","1109648320","1109648335","JP","Japan""66.35.227.208","66.35.230.31","1109648336","1109648927","US","United States""66.35.230.32","66.35.230.47","1109648928","1109648943","AU","Australia""66.35.230.48","66.35.236.207","1109648944","1109650639","US","United States""66.35.236.208","66.35.236.223","1109650640","1109650655","AU","Australia""66.35.236.224","66.36.127.255","1109650656","1109688319","US","United States"
The first two columns are a range of IP addresses. I have an IP address 66.35.250.168 I need to search the csv file to see in which range it lies, and print out the corresponding country name.
Since the first two numbers (66,35) are the same, I intend to search for the line containing this. I can search a complete string(66.35.205.88) by doing this:
import csv
with open('GeoIPCountryWhois.csv', mode='r') as f:
reader = csv.reader(f)
for row in reader:
if row[0] in ['66.35.205.88']:
print row
If I search for 66.35, I don't get any result . Can you please tell me a way in which I can search for a part of the string ('66.35' here) ? Also, can you tell me how I can find the exact line number in which I find the string?
Thanks in advance. |
I have lots of dates in a column in a CSV file that I need to convert from dd/mm/yyyy to yyyy-mm-dd format. For example 17/01/2010 should be converted to 2010-01-17.
How can I do this in Perl or Python?
>>> from datetime import datetime
>>> datetime.strptime('02/11/2010', '%d/%m/%Y').strftime('%Y-%m-%d')
'2010-11-02'
or more hackish way (that doesn't check for validity of values):
>>> '-'.join('02/11/2010'.split('/')[::-1])
'2010-11-02'
>>> '-'.join(reversed('02/11/2010'.split('/')))
'2010-11-02'
Perl:
my $date =~ s/(\d+)\/(\d+)\/(\d+)/$3-$2-$1/;
using python
import string
before = "17/01/2010"
array = string.split(before,"/")
after = array[2] + '-' + array[1] + '-' + array[0]
print after
In Perl you can do:
use strict;
while(<>) {
chomp;
my($d,$m,$y) = split/\//;
my $newDate = $y.'-'.$m.'-'.$d;
}
Perl :
while (<>) {
s/(^|[^\d])(\d\d)\/(\d\d)\/(\d{4})($|[^\d])/$4-$3-$2/g;
print $_;
}
Then you just have to run:
Go with Perl: the
echo "17/01/2010" | perl -pe 's{(\d+)/(\d+)/(\d+)}{$3-$2-$1}g'
If you do need to parse these dates (eg to compute their day of week or other calendar-type operations), look into DateTimeX::Easy (you can install it with
perl -MDateTimeX::Easy -e 'print DateTimeX::Easy->parse("17/01/2010")->ymd("-")'
In glorious perl-oneliner form:
echo 17/01/2010 | perl -p -e "chomp; join('-', reverse split /\//);"
But seriously I would do it like this:
#!/usr/bin/env perl
while (<>) {
chomp;
print join('-', reverse split /\//), "\n";
}
Which will work on a pipe, converting and printing one date per line.
If you are guaranteed to have well-formed data consisting of nothing else but a singleton date in the DD-MM-YYYY format, then this works:
# FIRST METHOD
my $ndate = join("-" => reverse split(m[/], $date));
That works on a
# SECOND METHOD
($ndate = $date) =~ s{
\b
( \d \d )
/ ( \d \d )
/ ( \d {4} )
\b
}{$3-$2-$1}gx;
If you prefer a more "grammatical" regex, so that itâs easier to maintain and update, you can instead use this:
# THIRD METHOD
($ndate = $date) =~ s{
(?&break)
(?<DAY> (?&day) )
(?&slash) (?<MONTH> (?&month) )
(?&slash) (?<YEAR> (?&year) )
(?&break)
(?(DEFINE)
(?<break> \b )
(?<slash> / )
(?<year> \d {4} )
(?<month> \d {2} )
(?<day> \d {2} )
)
}{
join "-" => @+{qw<YEAR MONTH DAY>}
}gxe;
Finally, if you have Unicode data, you might want to be a bit more careful.
# FOURTH METHOD
($ndate = $date) =~ s{
(?&break_before)
(?<DAY> (?&day) )
(?&slash) (?<MONTH> (?&month) )
(?&slash) (?<YEAR> (?&year) )
(?&break_after)
(?(DEFINE)
(?<slash> / )
(?<start> \A )
(?<finish> \z )
# don't really want to use \D or [^0-9] here:
(?<break_before>
(?<= [\pC\pP\pS\p{Space}] )
| (?<= \A )
)
(?<break_after>
(?= [\pC\pP\pS\p{Space}]
| \z
)
)
(?<digit> \d )
(?<year> (?&digit) {4} )
(?<month> (?&digit) {2} )
(?<day> (?&digit) {2} )
)
}{
join "-" => @+{qw<YEAR MONTH DAY>}
}gxe;
You can see how each of these four approaches performs when confronted with sample input strings like these:
my $sample = q(17/01/2010);
my @strings = (
$sample, # trivial case
# multiple case
"this $sample and that $sample there",
# multiple case with non-ASCII BMP code points
# U+201C and U+201D are LEFT and RIGHT DOUBLE QUOTATION MARK
"from \x{201c}$sample\x{201d} through\xA0$sample",
# multiple case with non-ASCII code points
# from both the BMP and the SMP
# code point U+02013 is EN DASH, props \pP \p{Pd}
# code point U+10179 is GREEK YEAR SIGN, props \pS \p{So}
# code point U+110BD is KAITHI NUMBER SIGN, props \pC \p{Cf}
"\x{10179}$sample\x{2013}\x{110BD}$sample",
);
Now letting
Original is: 17/01/2010
First method: 2010-01-17
Second method: 2010-01-17
Third method: 2010-01-17
Fourth method: 2010-01-17
Original is: this 17/01/2010 and that 17/01/2010 there
First method: 2010 there-01-2010 and that 17-01-this 17
Second method: this 2010-01-17 and that 2010-01-17 there
Third method: this 2010-01-17 and that 2010-01-17 there
Fourth method: this 2010-01-17 and that 2010-01-17 there
Original is: from “17/01/2010†through 17/01/2010
First method: 2010-01-2010†through 17-01-from “17
Second method: from “2010-01-17†through 2010-01-17
Third method: from “2010-01-17†through 2010-01-17
Fourth method: from “2010-01-17†through 2010-01-17
Original is: ð…¹17/01/2010–𑂽17/01/2010
First method: 2010-01-2010–𑂽17-01-ð…¹17
Second method: ð…¹2010-01-17–𑂽2010-01-17
Third method: ð…¹2010-01-17–𑂽2010-01-17
Fourth method: ð…¹2010-01-17–𑂽2010-01-17
Now letâs suppose that you actually
U+660 ARABIC-INDIC DIGIT ZERO
U+661 ARABIC-INDIC DIGIT ONE
U+662 ARABIC-INDIC DIGIT TWO
U+663 ARABIC-INDIC DIGIT THREE
U+664 ARABIC-INDIC DIGIT FOUR
U+665 ARABIC-INDIC DIGIT FIVE
U+666 ARABIC-INDIC DIGIT SIX
U+667 ARABIC-INDIC DIGIT SEVEN
U+668 ARABIC-INDIC DIGIT EIGHT
U+669 ARABIC-INDIC DIGIT NINE
or even
U+1D7F6 MATHEMATICAL MONOSPACE DIGIT ZERO
U+1D7F7 MATHEMATICAL MONOSPACE DIGIT ONE
U+1D7F8 MATHEMATICAL MONOSPACE DIGIT TWO
U+1D7F9 MATHEMATICAL MONOSPACE DIGIT THREE
U+1D7FA MATHEMATICAL MONOSPACE DIGIT FOUR
U+1D7FB MATHEMATICAL MONOSPACE DIGIT FIVE
U+1D7FC MATHEMATICAL MONOSPACE DIGIT SIX
U+1D7FD MATHEMATICAL MONOSPACE DIGIT SEVEN
U+1D7FE MATHEMATICAL MONOSPACE DIGIT EIGHT
U+1D7FF MATHEMATICAL MONOSPACE DIGIT NINE
So imagine you have a date in mathematical monospace digits, like this:
$date = "\x{1D7F7}\x{1D7FD}/\x{1D7F7}\x{1D7F6}/\x{1D7F8}\x{1D7F6}\x{1D7F7}\x{1D7F6}";
The Perl code will work just fine on that:
Original is: ðŸ·ðŸ½/ðŸ·ðŸ¶/ðŸ¸ðŸ¶ðŸ·ðŸ¶
First method: ðŸ¸ðŸ¶ðŸ·ðŸ¶-ðŸ·ðŸ¶-ðŸ·ðŸ½
Second method: ðŸ¸ðŸ¶ðŸ·ðŸ¶-ðŸ·ðŸ¶-ðŸ·ðŸ½
Third method: ðŸ¸ðŸ¶ðŸ·ðŸ¶-ðŸ·ðŸ¶-ðŸ·ðŸ½
Fourth method: ðŸ¸ðŸ¶ðŸ·ðŸ¶-ðŸ·ðŸ¶-ðŸ·ðŸ½
I think youâll find that Python has a pretty brainâdamaged Unicode model whose lack of support for abstract characters and strings irrespective of content makes it ridiculously difficult to write things like this.
Itâs also tough to write legible regular expressions in Python where you decouple the declaration of the subexpressions from their execution, since
But hey, if you think thatâs bad in Python compared to Perl (
As you see, you run into real problems when you ask for regex solutions from multiple languages. First of all, the solutions are difficult to compare because of the different regex flavors. But also because no other language can compare with Perl for power, expressivity, and maintainability in its regular expressions. This may become even more obvious once arbitrary Unicode enters the picture.
So if you just wanted Python, you should have asked for only that. Otherwise itâs a terribly unfair contest that Python will nearly always lose; itâs just too messy to get things like this correct in Python, let alone
In contrast, Perlâs regexes excel at both those.
Use Time::Piece (in core since 5.9.5), very similar to the Python solution accepted, as it provides the strptime and strftime functions:
use Time::Piece;
my $dt_str = Time::Piece->strptime('13/10/1979', '%d/%m/%Y')->strftime('%Y-%m-%d');
or
$ perl -MTime::Piece
print Time::Piece->strptime('13/10/1979', '%d/%m/%Y')->strftime('%Y-%m-%d');
1979-10-13
$
|
The Visual Module of VPython - Reference Manual
Date de publication : 4 février 2009
Graphs
Graphs
Graph Plotting
In this section we describe features for plotting graphs with tick marks and labels. Here is a simple example of how to plot a graph (arange creates a numeric array running from 0 to 8, stopping short of 8.1):
from visual.graph import * # import graphing features
funct1 = gcurve(color=color.cyan) # a graphics curve
for x in arange(0., 8.1, 0.1): # x goes from 0 to 8
funct1.plot(pos=(x,5.*cos(2.*x)*exp(-0.2*x))) # plot
Importing from visual.graph makes available all Visual objects plus the graph plotting module. The graph is autoscaled to display all the data in the window.
A connected curve (gcurve) is just one of several kinds of graph plotting objects. Other options are disconnected dots (gdots), vertical bars (gvbars), horizontal bars (ghbars), and binned data displayed as vertical bars (ghistogram; see later discussion). When creating one of these objects, you can specify a color attribute. For gvbars and ghbars you can specify a delta attribute, which specifies the width of the bar (the default is delta=1). For gdots you can specify a shape attribute "round" or "square" (default is shape="round") and a size attribute, which specifies the width of the dot in pixels (default is size=5).
You can plot more than one thing on the same graph:
funct1 = gcurve(color=color.cyan)
funct2 = gvbars(delta=0.05, color=color.blue)
for x in arange(0., 8.1, 0.1):
funct1.plot(pos=(x,5.*cos(2.*x)*exp(-0.2*x))) # curve
funct2.plot(pos=(x,4.*cos(0.5*x)*exp(-0.1*x)))# vbars
In a plot operation you can specify a different color to override the original setting:
mydots.plot(pos=(x1,y1), color=color.green)
When you create a gcurve, gdots, gvbars, or ghbars object, you can provide a list of points to be plotted, just as is the case with the ordinary curve object:
values = [(1,2), (3,4), (-5,2), (-5,-3)]
data = gdots(pos=values, color=color.blue)
This list option is available only when creating the gdots object.
Overall gdisplay options
You can establish a gdisplay to set the size, position, and title for the title bar of the graph window, specify titles for the x and y axes, and specify maximum values for each axis, before creating gcurve or other kind of graph plotting object:
graph1 = gdisplay(x=0, y=0, width=600, height=150,
title='N vs. t', xtitle='t', ytitle='N',
xmax=50., xmin=-20., ymax=5E3, ymin=-2E3,
foreground=color.black, background=color.white)
In this example, the graph window will be located at (0,0), with a size of 600 by 150 pixels, and the title bar will say 'N vs. t'. The graph will have a title 't' on the horizontal axis and 'N' on the vertical axis. Instead of autoscaling the graph to display all the data, the graph will have fixed limits. The horizontal axis will extend from -20 to +50, and the vertical axis will extend from -200. to +5000 (xmin and ymin must be negative; xmax and ymax must be positive.) The foreground color (white by default) is black, and the background color (black by default) is white. If you simply say gdisplay(), the defaults are x=0, y=0, width=800, height=400, no titles, fully autoscaled.
Every gdisplay has the attribute display, so you can place additional labels or manipulate the graphing window. The only objects that you can place in the graphing window are labels, curves, faces, and points.
graph1 = gdisplay()
label(display=graph1.display, pos=(3,2), text="P")
graph1.display.visible = 0 # make the display invisible
You can have more than one graph window: just create another gdisplay. By default, any graphing objects created following a gdisplay belong to that window, or you can specify which window a new object belongs to:
energy = gdots(gdisplay=graph2.display, color=color.blue)
Histograms (sorted, binned data)
The purpose of ghistogram is to sort data into bins and display the distribution. Suppose you have a list of the ages of a group of people, such as [5, 37, 12, 21, 8, 63, 52, 75, 7]. You want to sort these data into bins 20 years wide and display the numbers in each bin in the form of vertical bars. The first bin (0 to 20) contains 4 people [5, 12, 8, 7], the second bin (20 to 40) contains 2 people [21, 37], the third bin (40 to 60) contains 1 person [52], and the fourth bin (60-80) contains 2 people [63, 75]. Here is how you could make this display:
from visual.graph import *
.....
agelist1 = [5, 37, 12, 21, 8, 63, 52, 75, 7]
ages = ghistogram(bins=arange(0, 80, 20), color=color.red)
ages.plot(data=agelist1) # plot the age distribution
.....
ages.plot(data=agelist2) # plot a different distribution
You specify a list (bins) into which data will be sorted. In the example given here, bins goes from 0 to 80 by 20's. By default, if you later say
ages.plot(data=agelist2)
the new distribution replaces the old one. If on the other hand you say
ages.plot(data=agelist2, accumulate=1)
the new data are added to the old data.
If you say the following,
ghistogram(bins=arange(0,50,0.1), accumulate=1, average=1)
each plot operation will accumulate the data and average the accumulated data. The default is no accumulation and no averaging.
gdisplay vs. display A gdisplay window is closely related to a display window. The main difference is that a gdisplay is essentially two-dimensional and has nonuniform x and y scale factors. When you create a gdisplay (either explicitly, or implicitly with the first gcurve or other graphing object), the current display is saved and restored, so that later creation of ordinary Visual objects such as sphere or box will correctly be associated with a previous display, not the more recent gdisplay. |
I am using the "Server Side" flow to get a user's permissions to access some information using Python on Google Appengine.
I am able to get the server generated code from Facebook after the user clicks on the "Allow" button.
However when I get the access token, I run into the following error:
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/init.py", line 515, incallhandler.get(*groups) File "/base/data/home/apps/finisherph/1.348502373491720746/controllers.py", line 21, in get data = urllib2.urlopen(access_token_url)
File "/base/python_runtime/python_dist/lib/python2.5/urllib2.py", line 124, in urlopen return _opener.open(url, data) File "/base/python_runtime/python_dist/lib/python2.5/urllib2.py", line 387, in open response = meth(req, response) File "/base/python_runtime/python_dist/lib/python2.5/urllib2.py", line 498, in http_response 'http', request, response, code, msg, hdrs) File "/base/python_runtime/python_dist/lib/python2.5/urllib2.py", line 425, in error return self._call_chain(*args) File "/base/python_runtime/python_dist/lib/python2.5/urllib2.py", line 360, in _call_chain result = func(*args) File "/base/python_runtime/python_dist/lib/python2.5/urllib2.py", line 506, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 400: Bad Request
Here's the code in my controller where the response from facebook goes after user clicks on the "Allow" button. It's still a hack so the code is a little bit dirty. Still trying to make it work.
class Register(webapp.RequestHandler):
def get(self):
code=self.request.get('code')
logging.debug("code: "+code)
accesst_url=["https://graph.facebook.com/oauth/access_token?"]
accesst_url.append("client_id=CLIENT_ID&")
import urllib
accesst_url.append(urllib.urlencode
({'redirect_uri':'http://my.website.com/register/facebook/'}))
accesst_url.append('&')
accesst_url.append("client_secret=CLIENT_SECRET&")
accesst_url.append("".join(["code=",str(code)]))
logging.debug(accesst_url)
access_token_url="".join(accesst_url)
logging.debug(access_token_url)
import urllib2
data = urllib2.urlopen(access_token_url)
...
...
The error occurs here:
data = urllib2.urlopen(access_token_url)
when I copy and paste the access_token_url from my logs, I get the following error:
{ "error": { "type": "OAuthException", "message": "Error validating verification code." } }
What am I missing here? |
The following code works fine with python.exe but fails with pythonw.exe. I'm using Python 3.1 on Windows 7.
from http.server import BaseHTTPRequestHandler, HTTPServer
class FooHandler(BaseHTTPRequestHandler):
def do_POST(self):
length = int(self.headers['Content-Length'])
data = self.rfile.read(length)
print(data)
self.send_response(200)
self.send_header('Content-Length', '0')
self.end_headers()
httpd = HTTPServer(('localhost', 8000), FooHandler)
httpd.serve_forever()
Something wrong when I start sending responses. Nothing got written back. And if I try another http connection it won't connect. I also tried using self.wfile but no luck either. |
I am trying to scan my harddrive for jpg and mp3 files.
I have written the following script which works if I pass it a directory with file in the root but does not return anything if I pass it the root directory.
I am new to Python so would love some help.
def findfiles(dirname,fileFilter):
filesBySize = {}
def filterfiles(f):
ext = os.path.splitext(f)[1][1:]
if ext in fileFilter:
return True
else:
False
for (path, dirs, fnames) in os.walk(dirname):
if len(fileFilter)>0:
fnames = filter(filterfiles,fnames)
d = os.getcwd()
os.chdir(dirname)
for f in fnames:
if not os.path.isfile(f) :
continue
size = os.stat(f)[stat.ST_SIZE]
if size < 100:
continue
if filesBySize.has_key(size):
a = filesBySize[size]
else:
a = []
filesBySize[size] = a
a.append(os.path.join(dirname, f))
# print 'File Added: %s' %os.path.join(dirname,f)
_filecount = _filecount + 1
os.chdir(d)
return filesBySize
|
#2826 Le 12/03/2013, à 22:08
k3c
Re : TVDownloader: télécharger les médias du net !
@ mulder29
Tu ne donnes pas de renseignements pour qu'on puisse t'aider
as-tu passé la commande sudo apt-get ...
tu as eu un message d'erreur ?
Hors ligne
#2827 Le 12/03/2013, à 22:57
mulder29
Re : TVDownloader: télécharger les médias du net !
Ben oui, j'ai passé la commande
sudo apt-get install build-essential
Ensuite, je passe la commande
make posix
make mingw
et c'est ce qui me donne "commande introuvable"
o_O
Hors ligne
#2828 Le 14/03/2013, à 21:57
Tuxmouraille
Re : TVDownloader: télécharger les médias du net !
Bonsoir,
Juste comme ça ne passant. Je crois que le problème est que la commande mingw n'existe tout simplement pas sur Ubuntu.
MinGW est un outils pour compiler sous Windows des logiciels conçus pour Linux.
http://www.mingw.org/
http://fr.wikipedia.org/wiki/Mingw
Dernière modification par Tuxmouraille (Le 14/03/2013, à 21:59)
Le support d'Optimus pour Linux.
Ubuntu 12.10 64 bits, portable ASUS N53SN-SZ161V, Intel® Core™ i5-2410M @ 2.30GHz, 8080MB SODIM Ram, NVIDIA® GeForce™ GT 550M
Hors ligne
#2829 Le 15/03/2013, à 00:00
thom83
Re : TVDownloader: télécharger les médias du net !
Bonsoir,
Au vu de la réponse donnée par Tuxmouraille, j'ai regardé le README en question et effectivement il est que
- pour Linux il faut faire «make posix»
- pour Windows il faut faire «make mingw»
Le problème vient du fait que le README est ambigu au premier abord.
Bien sur il faut que cela soit fait dans le dossier où les sources ont été décompressées.
Dernière modification par thom83 (Le 15/03/2013, à 00:03)
Hors ligne
#2830 Le 15/03/2013, à 17:15
11gjm
Re : TVDownloader: télécharger les médias du net !
Bonjour ,
Juste pour info : épisodes 11 et 12 d' E N G R E N A G E S , sur D8 .
Ceci pour indiquer les pistes de recherches . Si , non téléchargement .
@echo on
rtmpdump -r "rtmpe://geo2-vod-fms.canalplus.fr:1935/ondemand" -a "ondemand?ovpfv=1.1" -f "WIN 11,5,502,110" -W "http://player.canalplus.fr/site/flash/player.swf" -p "http://www.d8.tv/d8-series/pid5210-d8-engrenages.html?vid=829164" -C Z: -y "mp4:/ondemand/geo2/1303/1052501_11_800k.mp4" -o 1052501_11_800k.flv
pause
rtmpdump -r "rtmpe://geo2-vod-fms.canalplus.fr:1935/ondemand" -a "ondemand?ovpfv=1.1" -f "WIN 11,5,502,110" -W "http://player.canalplus.fr/site/flash/player.swf" -p "http://www.d8.tv/d8-series/pid5210-d8-engrenages.html?vid=829148" -C Z: -y "mp4:/ondemand/geo2/1303/1052501_12_800k.mp4" -o 1052501_12_800k.flv
pause
:fin
Cordialement .
Hors ligne
#2831 Le 15/03/2013, à 19:30
mulder29
Re : TVDownloader: télécharger les médias du net !
Ah okk, et... comment je fais moi ? o_O
Hors ligne
#2832 Le 15/03/2013, à 20:45
thom83
Re : TVDownloader: télécharger les médias du net !
Avec Ubuntu 12.04, la commande
python Bureau/Scripts-TV-Replay/D8.py http://www.d8.tv/d8-series/pid5210-d8-engrenages.html?vid=829164
lance celle-ci
rtmpdump -r "rtmp://geo2-vod-fms.canalplus.fr/ondemand/geo2/1303/1052501_12_1500k.mp4" -o "Engrenages_-_Episode_11.mp4" --resume
pour l'épisode 11
@ mulder29
Quelle version de linux utilise-tu ?
Hors ligne
#2833 Le 15/03/2013, à 23:54
mulder29
Re : TVDownloader: télécharger les médias du net !
Linux version 3.2.0-38-generic (buildd@panlong) (gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) ) #61-Ubuntu SMP Tue Feb 19 12:20:02 UTC 2013
Voila, j'espère que ça suffira ?
Hors ligne
#2834 Le 16/03/2013, à 00:02
thom83
Re : TVDownloader: télécharger les médias du net !
@ k3c
Il y a un petit problème dans le code de D8.py qui établit la commande rtmpdump.
En effet, celle utilisée pour l'épisode 11 charge l'épisode 12. Au #2832 ci-dessus, l'erreur est visible si l'on compare «1052501_12_1500k.mp4» et «Episode_11.mp4».
En substituant le bon numéro à la position 1, le résultat est bon à l'arrivée.
Hors ligne
#2835 Le 16/03/2013, à 00:18
thom83
Re : TVDownloader: télécharger les médias du net !
@ mulder29
Le paquet rtmpdump présent à cette adresse
http://packages.ubuntu.com/fr/precise/rtmpdump
devrait convenir, me semble-t-il.
Télécharger la version qui va bien (i386 ou amd64 suivant l'architecture) et l'installer grâce à gdebi qui demandera éventuellement les éléments nécessaires pour satisfaire les dépendances (il faudra chaque fois ajouter ces dépendances pour pouvoir continuer).
Bon courage.
Hors ligne
#2836 Le 16/03/2013, à 02:29
mulder29
Re : TVDownloader: télécharger les médias du net !
Et maintenant ?
La commande :
python d8.py http://www.d8.tv/d8-divertissement/pid5 … vid=828406
que je dois taper dans le Terminal lancé à partir du fichier D8 ne fonctionne plus au fait.
Hors ligne
#2837 Le 16/03/2013, à 10:02
thom83
Re : TVDownloader: télécharger les médias du net !
Bonjour mulder29 ainsi que les autres participants,
Si le lien ci-dessus n'est pas tronqué, c'est normal que D8.py ne fonctionne pas car j'obtiens l'erreur suivante :
Erreur
Page indisponible
Vérifiez que l'adresse ne contient pas une erreur de frappe
Si l'installation du paquet rtmpdump que j'ai mentionné s'est bien passée, D8.py doit remplir son rôle (à quelques détails près).
Dernière modification par thom83 (Le 16/03/2013, à 10:04)
Hors ligne
#2838 Le 16/03/2013, à 10:10
k3c
Re : TVDownloader: télécharger les médias du net !
@ k3c
Il y a un petit problème dans le code de D8.py qui établit la commande rtmpdump.
En effet, celle utilisée pour l'épisode 11 charge l'épisode 12. Au #2832 ci-dessus, l'erreur est visible si l'on compare «1052501_12_1500k.mp4» et «Episode_11.mp4».
En substituant le bon numéro à la position 1, le résultat est bon à l'arrivée.
je sais.
les vidéos sont sur une page se terminant par d8 ou cplus
et je n'ai pas trouvé de méthode simple pour savoir sur quelle page chercher
je n'ai pas accès à un ordi avant mardi
Hors ligne
#2839 Le 16/03/2013, à 10:42
thom83
Re : TVDownloader: télécharger les médias du net !
@ k3c
Le problème n'est pas trop génant dans la mesure où on se montre attentif au résultat. En effet, il semble qu'il suffise de modifier le numéro de l'épisode dans la commande pour réussir le chargement.
Par exemple, pour ceux qui auraient loupé un épisode de la saison, il est encore possible de le récupérer en mettant le bon numéro dans la commande.
Encore une fois , c'est une chance d'avoir cet outil. Merci.
Hors ligne
#2840 Le 16/03/2013, à 10:52
k3c
Re : TVDownloader: télécharger les médias du net !
Je vais re-examiner ce que fait le plugin xbmc pour différencier les vidéos d8 et cplus
il y a peut-être plus simple, faut que je voie ce qu'il y a de commun dans le html des différentes pages
Hors ligne
#2841 Le 16/03/2013, à 17:53
mulder29
Re : TVDownloader: télécharger les médias du net !
Bonjour mulder29 ainsi que les autres participants,
Si le lien ci-dessus n'est pas tronqué, c'est normal que D8.py ne fonctionne pas car j'obtiens l'erreur suivante :
Erreur
Page indisponible
Vérifiez que l'adresse ne contient pas une erreur de frappe
Si l'installation du paquet rtmpdump que j'ai mentionné s'est bien passée, D8.py doit remplir son rôle (à quelques détails près).
J'obtiens
Traceback (most recent call last):
File "d8.py", line 8, in <module>
a = urlopen(sys.argv[1]).read()
File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, 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 404: Not Found
Donc c'est normal ? o_O
Hors ligne
#2842 Le 16/03/2013, à 18:28
thom83
Re : TVDownloader: télécharger les médias du net !
@ mulder29
16 lignes d'erreur... Le message d'erreur est-il complet ou pas ? Il correspond à quelle commande ?
Le fichier D8.py est-il celui créé pour être utilisé avec linux ou celui pour windows ?
La question «Donc c'est normal ?» est-elle ironique ou pas ?
Des questions simples et détaillées permettraient probablement de renseigner mieux.
Je vais bientôt m'absenter pour la soirée et ne serai probablement en mesure de répondre que demain.
À +
Dernière modification par thom83 (Le 16/03/2013, à 18:30)
Hors ligne
#2843 Le 16/03/2013, à 19:08
mulder29
Re : TVDownloader: télécharger les médias du net !
@thom83
Les lignes d'erreur correspondent au résultat quand je tapes la commande suivante :
python d8.py http://www.d8.tv/d8-divertissement/pid5 … vid=828406
sur le terminal que je lance dans le fichier D8 qui contient le fichier python en question
le fichier D8.py a été créé pour être utilisé avec linux.
La question "donc c'est normal ?" c'était juste pour vérifier que l'on que lorsque tu parles du message d'erreur un peu plus haut :
Erreur
Page indisponible
Vérifiez que l'adresse ne contient pas une erreur de frappe
On parlait bien du même résultat, pour vérifier qu'il n'y avait pas de méprise. ;-)
Hors ligne
#2844 Le 16/03/2013, à 19:34
thom83
Re : TVDownloader: télécharger les médias du net !
Quand je clique sur le lien en couleur, c-à-d http://www.d8.tv/d8-divertissement/pid5 , j'obtiens effectivement l'erreur e00n question sur la page ouverte.
Manifestement l'adresse de l'émission est incomplète. Sur la page où j'ai l'erreur, si je clique sur divertissement, toutes les émissions comportent un nombre à 4 chiffres suivi d'autres mentions. C'est l'adresse complète qui doit figurer dans la commande «python D8.py ....»
Hors ligne
#2845 Le 16/03/2013, à 20:43
ynad
Re : TVDownloader: télécharger les médias du net !
bonsoir,
ça marche avec:
python d8-0.2.py http://www.d8.tv/d8-series/pid5210-d8-engrenages.html
Hors ligne
#2846 Le 16/03/2013, à 22:50
11gjm
Re : TVDownloader: télécharger les médias du net !
Bonjour ,
Pour les mélomanes , ci-après un lien pour "visionner" "La folle journée de Nantes 2013".
http://forum.ubuntu-fr.org/viewtopic.ph … #p12928221
Cordialement .
Hors ligne
#2847 Le 17/03/2013, à 14:24
mulder29
Re : TVDownloader: télécharger les médias du net !
Ah, donc, j'ai tapé ma ligne de commande sur le terminal lancé à partir du fichier D8 :
python d8.py http://www.d8.tv/d8-divertissement/pid5 … vid=828406
Même chose qu'auparavant : le téléchargement et lorsque ça atteint 99,99% et "dowload complte", ça efface le fichier et relance le téléchargement.
Je pensais arrêté le processus à 99,5% de façon à avoir au moins un fichier, mais la vidéo serait elle lisible ?
Hors ligne
#2848 Le 17/03/2013, à 16:32
11gjm
Re : TVDownloader: télécharger les médias du net !
Bonjour ,
@mulder : "c'est dur la culture !!!"
>j'ai tapé "python d8.py ..."
Il faut utiliser le "D8 0.2" , voir post #2816 .
> Même chose qu'auparavant ...
D'après ce que tu indiquais tu n'arrivais à rien . Ça semble avancer (???) .
> Je pensais arrêter le processus à 99,5% de façon à avoir au moins un fichier,
mais la vidéo serait elle lisible ?
1) avec le "D8 0.2" , normalement ça ne devrait pas recommencer .
2) sinon , fais l'essai de lecture , tu verras bien ce que cela donne .
A+ .
Hors ligne
#2849 Le 17/03/2013, à 18:19
mulder29
Re : TVDownloader: télécharger les médias du net !
@mulder : "c'est dur la culture !!!"
>j'ai tapé "python d8.py ..."
Il faut utiliser le "D8 0.2" , voir post #2816 .
Euh un post que je ne comprends absolument pas... o_O
Pour mulder29
tu noteras la ligne qui permet de retrouver l'identifiant de la vidéo
id = s.findAll('div',attrs={"class":u"block-common block-player-programme"})[0]('canal:player')[0]['videoid']
Noter ? C'est à dire ? je le note sur le terminal ? comment je l'utilise ?
sans un parser HTML, c'est galère...
C'est quoi un parser HTML ?
le code
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# D8 version 0.2 par k3c
from urllib2 import urlopen
from lxml import objectify
import bs4 as BeautifulSoup
import sys, subprocess, re
a = urlopen(sys.argv[1]).read()
s = BeautifulSoup.BeautifulSoup(a)
url = ''
def get_HD(d8_cplus):
zz = urlopen('http://service.canal-plus.com/video/rest/getVideosLiees/'+d8_cplus+'/'+id).read()
root = objectify.fromstring(zz)
for element in root.iter():
if element.tag == 'HD':
Que je tapes où ? dans le Terminal ?
Dernière modification par mulder29 (Le 17/03/2013, à 18:20)
Hors ligne
#2850 Le 17/03/2013, à 19:07
11gjm
Re : TVDownloader: télécharger les médias du net !
Bonjour ,
@mulder29 :
Tu retournes au post #2816 .
Sous la ligne "le code" , il y a une fenêtre noire contenant des écritures .
Avec la souris , tu sélectionnes tous les écrits , tu effectues un copier .
Tu ouvres un éditeur de texte , tu y colles les écrits précédents .
Tu sauvegardes le fichier sous le nom de D8_02.py .
Dans le même répertoire que ton D8.py , qui semble fonctionner (enfin presque !!!) .
Dans la fenêtre du terminal , tu tapes toute la commande :
python D8_02.py "http://www.d8.tv/d8-divertissement/pid5 … vid=828406"
et tu tapes sur la touche entrée , pour lancer le process .
Normalement , cela devrait fonctionner .
Je ne comprends pourquoi tu coinces , alors que la procédure est simple .
A+ .
Hors ligne |
there. I apologize for the simple question, but I am a complete novice and need some help. I am trying to run Peter Norvig's Spelling Corrector (http://norvig.com/spell.py), but I'm receiving the following reply:
C:\>spelling.py
Traceback (most recent call last):
File "C:\Python27\spelling.py", line 11, in <module>
NWORDS = train(words(file('big.txt').read()))
IOError: [Errno 2] No such file or directory: 'big.txt'
The script includes an embedded text file (big.txt), which I've created and saved in the same directory as spelling.py. Why can't it find the big.txt file? Secondly, once the script is working, how would I use it against a sample of words needing correction? |
Ok, my first answer has gotten quite a bit of flack, so I thought I'd try a few different ways of doing this and report the differences. Here's my code.
import sys
import itertools
def getFirstDup(c, toTest):
# Original idea using list slicing => 5.014 s
if toTest == '1':
for i in xrange(0, len(c)):
if c[i] in c[:i]:
return c[i]
# Using two sets => 4.305 s
elif toTest == '2':
s = set()
for i in c:
s2 = s.copy()
s.add(i)
if len(s) == len(s2):
return i
# Using dictionary LUT => 0.763 s
elif toTest == '3':
d = {}
for i in c:
if i in d:
return i
else:
d[i] = 1
# Using set operations => 0.772 s
elif toTest == '4':
s = set()
for i in c:
if i in s:
return i
else:
s.add(i)
# Sorting then walking => 5.130 s
elif toTest == '5':
c = sorted(c)
for i in xrange(1, len(c)):
if c[i] == c[i - 1]:
return c[i]
# Sorting then groupby-ing => 5.086 s
else:
c = sorted(c)
for k, g in itertools.groupby(c):
if len(list(g)) > 1:
return k
return None
c = list(xrange(0, 10000000))
c[5000] = 0
for i in xrange(0, 10):
print getFirstDup(c, sys.argv[1])
Basically, I try this in six different ways, as listed in the source file. I used the Linux time command and collected the realtime runtimes, running the commands like so
time python ./test.py 1
with 1 being which algorithm I wanted to try. Each algorithm looks for the first duplicate in 10,000,000 integers, and runs ten times. There is one duplication in the list, which is "mostly sorted" though I did try reverse sorted lists without noticing a proportional difference between algorithms.
My original suggestion did poorly at 5.014 s. My understanding of icyrock.com's solution also did poorly at 4.305 s. Next I tried using a dictionary to create a LUT, which gave the best runtime at 0.763 s. I tried using the in operator on sets, and got 0.772 s, nearly as good as the dictionary LUT. I tried sorting and walking the list, which gave a pitiful time of 5.130 s. Finally, I tried John Machin's suggestion of the itertools, which gave a poor time of 5.086 s.
In summary, a dictionary LUT seems to be the way to go, with set operations (which may use LUTs in its implementation) being a close second.
Update: I tried razpeitia's suggestion, and apart from the fact that you need to know precisely what duplicate key you're looking for, the actual algorithm did the worst so far (66.366 s).
Update 2: I'm sure someone is going to say that this test is biased because the duplicate location is near one end of the list. Try running the code using a different location before downvoting and report your results! |
Mangatd
[Résolu] Kdenlive rendu impossible et conflit avec libavcodec-extra-53
Bonjour,
Comme l'indique le sujet, je ne peux pas faire de rendu à cause d'un problème de codecs :
- Pour Xvid4, il lui manque libxvid
- Pour H264, il lui manque libx264
- Pour AVI DV, pcm_s16le
- Pour MPEG4 et Flash, libmp3lame
J'aimerais pouvoir encoder ma vidéo en Xvid (je ne peux pas en Theora car cette vidéo sera envoyé sur Youtube, au pire il faut que je la ré-encode derrière...
Le gros, gros problème, c'est que d'après ce qu'on lit ici et la sur Internet, il faut installer libavcodec-extra-53. Or, si je l'installe via Synaptic, les dépendances m'obligent de désinstaller pleins de logiciels dont audacious, vlc, et... Kdenlive lui-même ! ! Enfin, c'est ce qui me dit d'habitude, par ce que je viens juste de réessayer pour vous afficher la liste complète des logiciels, mais à la place j'ai ça, maintenant :
libavcodec-extra-53:
Dépend : libavutil-extra-51 (<4:0.8.3ubuntu0.12.04.1-99) mais 4:0.8.3ubuntu0.12.04.1+medibuntu1 doit être installé
Est en conflit avec : libavcodec53 mais 4:0.8.3-0ubuntu0.12.04.1 doit être installé
Ce matin, je devais choisir entre soit garder libavcodec-extra-53, soit mes logiciels ! Là, je suis encore plus coincé
Voici mon source.list :
# deb cdrom:[Lubuntu 12.04 _Precise Pangolin_ - Release i386 (20120423)]/ precise main multiverse restricted universe
# 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
## Major bug fix updates produced after the final release of the
## distribution.
deb 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 http://fr.archive.ubuntu.com/ubuntu/ precise-updates universe
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://fr.archive.ubuntu.com/ubuntu/ precise multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ precise-updates multiverse
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://fr.archive.ubuntu.com/ubuntu/ precise-backports main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu/ precise-security main restricted
deb http://security.ubuntu.com/ubuntu/ precise-security universe
deb http://security.ubuntu.com/ubuntu/ precise-security multiverse
## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
deb http://archive.canonical.com/ubuntu/ precise partner
deb-src http://archive.canonical.com/ubuntu/ precise partner
## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
deb http://extras.ubuntu.com/ubuntu/ precise main
deb http://fr.archive.ubuntu.com/ubuntu/ precise-proposed restricted main multiverse universe
# deb-src http://extras.ubuntu.com/ubuntu/ precise main
deb http://download.virtualbox.org/virtualbox/debian/ precise contrib
## Depôt MultiSystem
deb http://liveusb.info/multisystem/depot/ all main
Notez que j'ai essayé d'encoder en AVI DV et avec le preset DVD (réglages par défaut, je n'ai jamais touché à ça) et que dans les 2 cas l'encodage à planté, je me retrouve dans les 2 cas avec un fichier contenant que les 9 ou 10 premières secondes de vidéo
Ma configuration :
Lubuntu 12.04 Precise Pangolin
1 Go de RAM
Processeur AMD Athlon 64 Processor 3200 + 2Go
Kdenlive Version 0.9.2
Utilisation de la plate-forme de développement de KDE 4.8.4 (4.8.4)
Pour MLT, j'ai trouvé ça sur Synaptic : libmlt++3 - Version : 0.8.0-0ubuntu0~sunab~precise3
Merci d'avance
PS : Tiens, je ne vois pas les dépots de Sunab dans mon sources.list alors que je suis sur que je les ais !
Dernière modification par Mangatd (Le 20/02/2014, à 17:31)
Hors ligne
xabilon
Re : [Résolu] Kdenlive rendu impossible et conflit avec libavcodec-extra-53
Salut
Normalement, si tu restes sur les dépôts officiels de Precise, tu peux installer les bibliothèques ***-extra-*** sans problème, les logiciels en ayant besoin dépendant des paquets extra ou non-extra.
Exemple : vlc, dans la liste des dépendances tu vois bien que les deux sont acceptées.
Pour Kdenlive, ça passe par sa dépendance ffmpeg/libav-tools, et là aussi les 2 versions peuvent être installées.
Cependant, ta version de Kdenlive n'est pas celle des dépôts Ubuntu officiels, et c'est peut-être là que ça coince.
Si tu as beaucoup de dépôts tiers et que tu pioches dedans, ça peut mener à ce genre de situation (les dépôts ne sont pas que dans le sources.list, il peut aussi y en avoir dans le dossier /etc/apt/sources.list.d).
Je pense qu'il faudrait commencer par désactiver tous les dépôts non-officiels, puis désinstaller tous les logiciels concernés par les bibliothèques libav
Ensuite installer tous les paquets listés ici, dans leur version "extra", puis le paquet ffmpeg, et enfin les applications que tu as précédemment désinstallées (vlc, audacious, kdenlive ...).
Une fois tout cela en place, tu pourras éventuellement ré-activer les autres dépôts, et vérifier si les mises à jour ne causent pas de conflits
Dernière modification par xabilon (Le 05/08/2012, à 06:47)
Pour passer un sujet en résolu : modifiez le premier message et ajoutez [Résolu] au titre.
Hors ligne
Mangatd
Re : [Résolu] Kdenlive rendu impossible et conflit avec libavcodec-extra-53
Bon, ça a dégénéré lors de la désinstallation des paquets si bien que j’ai du réinstaller Lubuntu (? !).
Après réinstallation et rajout du dépôt de Sunab et des codecs, je n'ai plus été embêté par les dépendances (il m'a juste demandé de désinstaller libavcodec53 et libavutil51. Il m'a aussi installé libavutil-extra-51 (4:0.8.3ubuntu0.12.04.1) et libopenjpeg2 (1.3+dfsg-4).
Pourtant, j'ai exactement le même problème qu'avant. J'ai essayé d'installer en plus les suppléments restreins Ubuntu mais ça ne change rien.
J'ai relancé l’assistant de configuration de Kdenlive, il a bien trouvé libxvid, libx264 et libmp3lame. En revanche, pas de pcm_s16le (coup de bol, je ne prévois pas d'utiliser AVI DV). J’ai relancé Kdenlive et... PLUS DE MESSAGE D'ERREUR ! Je vais encoder ma vidéo maintenant et je vous tiens au courant de la situation. SI ma vidéo est encodée correctement, je passe en Résolu...
Je serais curieux par ailleurs de savoir quel dépôt vient s’entrechoquer avec Kdenlive pour mettre le boxon, mais maintenant j'ai peur qui si je les installe, j'ai à nouveau le problème et que je ne puisse plus retourner en arrière même en supprimant les dépôts en trop ! (ce qui n'est pas logique, d'ailleurs, quand on supprime un dépôt, le paquet retourne à la version du dépôt officiel si il existe ou disparaît...)
Dernière modification par Mangatd (Le 20/02/2014, à 17:33)
Hors ligne
xabilon
Re : [Résolu] Kdenlive rendu impossible et conflit avec libavcodec-extra-53
Non, si tu supprimes un dépôt, les paquets issus de ce dépôt restent installés en l'état, jusqu'à ce qu'un paquet de même nom mais de version supérieure et issu des autres dépôts vienne le remplacer.
Sur Ubuntu, étant donné que les dépôts tiers servent habituellement à avoir des version plus récentes, et qu'Ubuntu gèle les versions des paquets à chaque sortie, cela n'arrive que lors d'une mise à niveau de version, ou si tu choisis de rétrograder manuellement le paquet.
Pour les libs-extra, parfois le problème vient lorsque les PPA prennent les paquets directement de Debian. Sur Debian, les paquets "non-extra" sont dans les dépôts officiels, et les paquets "extra" dans le dépôt Marillat (debian-multimedia), mais les paquets ont exactement le même nom sur les deux dépôts. Si on introduit ce type de paquet dans Ubuntu, ça peut mener à des problèmes.
Je ne sais pas quel dépôt peut te causer des soucis, mais dans le doute il vaut mieux s'abstenir. Si tu as besoin d'un dépôt tiers pour un paquet en particulier, active le dépôt, installe ce paquet particulier, puis désactive le dépôt.
Le dépôt Sunab/kdenlive-release ne contient que kdenlive, mlt et frei0r, ce n'est pas tout à fait le même jeu de dépendances que dans le kdenlive officiel, donc il faut faire gaffe à tout ce qui concerne libmlt, melt, ffmpeg ... afin de ne pas mélanger et créer des incohérences et des conflits.
libavcodec(-extra-)53 est aussi un paquet recommandé par kdenlive version Sunab, alors qu'il ne l'est pas par la version des dépôts officiels (c'est ffmpeg qui se charge de l'installer)
Pour passer un sujet en résolu : modifiez le premier message et ajoutez [Résolu] au titre.
Hors ligne
Mangatd
Re : [Résolu] Kdenlive rendu impossible et conflit avec libavcodec-extra-53
C'est justement pour ça que j'aime ajouter des dépôts : bénéficier des dernières versions des logiciels, car malheureusement dans de nombreux cas, Ubuntu nous laisse une version et ne propose jamais de mise à jour pour celui-ci (sûrement à cause du nombre important de softs), ce qui est assez embêtant pour des logiciels qui sont en stade de développement et qui buguent beaucoup (Kdenlive est un bon exemple, il n'y a que depuis la 0.9.2 que je commence d’être tranquille). C'était particulièrement embêtant à l'époque où j'étais sous Hardy Heron (une LTS, donc) : même pas un an après sa sortie, je me suis rendu compte que plusieurs logiciels ou sites comme Getdeb ne supportaient déjà plus cette version pourtant LTS !
Pour en revenir à Kdenlive, j'ai encodé une 1ère fois en Xvid4, mais il m'a envoyé promener.
J'ai réessayé une 2ème fois, ça a plus ou moins marché. En fait j'ai bien ma vidéo finale, mais il m'a en même temps envoyé promener à la fin...
La vidéo est correcte niveau encodage, si ce n'est que 1,6 Go pour une vidéo de 54 minutes en 1000 Ko, ça me parait beaucoup
Il faudra attendre un petit moment avant que je remonte une autre vidéo, j’espère que ça ne vas pas se casser la figure d'ici là...
Dernière modification par Mangatd (Le 13/01/2013, à 23:43)
Hors ligne
aspu
Re : [Résolu] Kdenlive rendu impossible et conflit avec libavcodec-extra-53
salut.
je remonte le post car je viens d'installer une 12.04 en 64 et plusieurs formats sont non exportables et pourtant je cherche ! ( dans le menu de rendu > sans perte / haute qualité )
libavcodec-extra-53 installé
frei0r-plugins installé
swh-plugins installé
infos données par kedenlive .
libmp3lame codec audio non géré > recherche dans la bibliothèque = 5 réponses installées
libx264 codec vidéo non géré > recherche dan le bibliothèque = 2 réponses installées
Avec redémarrage a la clef mais rien n'y fait !
Que faire ?
Merci.
Dernière modification par aspu (Le 08/03/2013, à 20:42)
Hors ligne
aspu
Re : [Résolu] Kdenlive rendu impossible et conflit avec libavcodec-extra-53
j'ai réglé le problème en désinstallant Kdenlive puis j'ai viré le dossier .kde dans "home" et ensuite réinstallation de kdenlive .
Il me reste le format non exportable HuffYUV losless (video)+ PCM (sound) car Codec audio non gégré : pcm_s16le que je ne trouve avec synaptic ou la biblio .
Bien que je ne l'utilise pas si l'un d'entre vous a la solution ça pourrait servir à d'autres .
Dernière modification par aspu (Le 08/03/2013, à 20:38)
Hors ligne
Mangatd
Re : [Résolu] Kdenlive rendu impossible et conflit avec libavcodec-extra-53
Là, je ne vois pas du tout, tu as bien suivi les instructions du message 2 (sait-on jamais) ?
Hors ligne
xfcali
Re : [Résolu] Kdenlive rendu impossible et conflit avec libavcodec-extra-53
Bonjour,
Même problème aujourd'hui
Résolu en allant dans /home/<<nom>>/.kde/share/config/kdenliverc.
et en rajoutant pcm_s16le et libmp3lame dans la section unmanaged ligne audio codecs
Hors ligne
kikibelux
Re : [Résolu] Kdenlive rendu impossible et conflit avec libavcodec-extra-53
Bonjour,
Même problème aujourd'hui
Résolu en allant dans /home/<<nom>>/.kde/share/config/kdenliverc.
et en rajoutant pcm_s16le et libmp3lame dans la section unmanaged ligne audio codecs
Merci, cela fait plus d'une semaine que j'ai posé la question sur le forum et suis resté en rade ! lien vers le forum
Ceci dit, de mon côté je n'ai pas les codecs pour le h.264, si qqn à une idée !
actuelement sur ubuntu 12.04 64b gnome-shell
ex :KDE4.2 Kubuntu 10.04 64b
--------------------------------------------------------------------
Kikibelux issu de www.loligrub.be un LUG belge avec de la bière belge et Libre...)
Hors ligne |
Given multiple amounts to be given, and list of notes (you cannot repeat them). I need to find notes combinations to give away all amounts.
For Eample: if notes are:
[1,1,5,6,6,8,8,10]and amounts are[15, 14, 16].
The solution can be
{15:(10,5), 14:(6,8), 16:(1,1,6,8)}
This is a variation of change-making problem as described here. Below is the code using dynamic programming for standard change-making problem, given V (set of infinite denominations) and C(the amount). How to modify it for non-repeating notes and multiple amounts. Also need the final combination for each amount.
def min_change(V, C):
m, n = len(V)+1, C+1
table = [[0] * n for x in xrange(m)]
for j in xrange(1, n):
table[0][j] = float('inf')
for i in xrange(1, m):
for j in xrange(1, n):
aC = table[i][j - V[i-1]] if j - V[i-1] >= 0 else float('inf')
table[i][j] = min(table[i-1][j], 1 + aC)
return table[m-1][n-1]
Update:
Change making problem is NP-complete. There is detailed paper here http://www.or.deis.unibo.it/kp/Chapter5.pdf Nonetheless there are solutions which are fairly optimal and which give results. |
This program has been disqualified.
Author pyfex
Submission date 2011-06-23 19:31:15.186639
Rating 5004
Matches played 2
Win rate 50.0
# See http://overview.cc/RockPaperScissors for more information about rock, paper, scissors
# Switching with multiple different switching strategies. 450 different predictors. Maybe
# it gets disqualified for that, but let's see.
import random
import operator
from collections import defaultdict
if input == "":
both_hist = ""
my_hist = ""
opp_hist = ""
my_stats = {'R':0, 'P':0, 'S': 0}
beat = {'P': 'S', 'S': 'R', 'R': 'P'}
cede = {'P': 'R', 'S': 'P', 'R': 'S'}
both_patterns = defaultdict(str)
opp_patterns = defaultdict(str)
my_patterns = defaultdict(str)
def shift(n, move):
return {0: move, 1:beat[move], 2:cede[move]}[n%2]
def unshift(n, move):
return {0: move, 1:cede[move], 2:beat[move]}[n%2]
score = {'RR': 0, 'PP': 0, 'SS': 0, 'PR': 1, 'RS': 1, 'SP': 1,'RP': -1, 'SR': -1, 'PS': -1,}
output = random.choice(["R", "P", "S"])
candidates = [output] * 450
performance = [[(2,0)]*6, [(2,0)]*6, [0]*6, [(2,0)]*450, 0, 0]
main_performance = [0, 0, 0, 0, 0, 0]
main_candidates = [output] * 6
indices = [0, 0, 0, 0] # only the first 4 main strats are switching strats
main_index = 0
wins = losses = ties = 0
else:
my_stats[output] += 1
sc = score[output+input]
if sc == 1:
wins += 1
elif sc == 0:
ties += 1
elif sc == -1:
losses += 1
both_hist += output+input
my_hist += output
opp_hist += input
for length in range(min(5, len(my_hist)), 0, -1):
opp_patterns[opp_hist[-length:]] += output + input
my_patterns[my_hist[-length:]] += output + input
both_patterns[both_hist[-2*length:]] += output + input
for i, c in enumerate(candidates[:6]):
performance[0][i] = ({1:performance[0][i][0]+1, 0: 2, -1: 2}[score[c+input]],
performance[0][i][1]+score[c+input])
performance[1][i] = ({1:performance[1][i][0]+1, 0: performance[1][i][0], -1: 2}[score[c+input]],
performance[1][i][1]+score[c+input])
performance[2][i] += score[c+input]
for i, c in enumerate(candidates):
performance[3][i] = ({1:performance[3][i][0]+1, 0: 2, -1: 2}[score[c+input]],
performance[3][i][1]+score[c+input])
indices[0] = performance[0].index(max(performance[0], key=lambda x: x[0]**3+x[1]))
indices[1] = performance[1].index(max(performance[1], key=lambda x: x[0]**3+x[1]))
indices[2] = performance[2].index(max(performance[2]))
indices[3] = performance[3].index(max(performance[3], key=lambda x: x[0]**3+x[1]))
for i, c in enumerate(main_candidates):
main_performance[i] += score[c+input]
main_index = main_performance.index(max(main_performance))
output = random.choice(['R', 'P', 'S'])
candidates = [output] * 450
for length in range(min(5, len(my_hist)), 0, -1):
p = both_patterns[both_hist[-2*length:]]
if p != "":
opp = p[-1]
my = p[-2]
candidates[0] = beat[opp]
candidates[1] = cede[my]
candidates[2] = opp
candidates[3] = my
candidates[4] = cede[opp]
candidates[5] = beat[my]
for i, a in enumerate(candidates[:6]):
for offset in range(3):
candidates[6+24*i+offset*8] = shift(offset+wins, a)
candidates[6+24*i+offset*8+1] = shift(offset+wins+ties, a)
candidates[6+24*i+offset*8+2] = shift(offset+losses+ties, a)
candidates[6+24*i+offset*8+3] = shift(offset+losses, a)
candidates[6+24*i+offset*8+4] = unshift(offset+wins, a)
candidates[6+24*i+offset*8+5] = unshift(offset+wins+ties, a)
candidates[6+24*i+offset*8+6] = unshift(offset+losses+ties, a)
candidates[6+24*i+offset*8+7] = unshift(offset+losses, a)
main_candidates[4] = beat[opp]
break
for length in range(min(5, len(my_hist)), 0, -1):
p = my_patterns[my_hist[-length:]]
if p != "":
opp = p[-1]
my = p[-2]
candidates[150] = beat[opp]
candidates[151] = cede[my]
candidates[152] = opp
candidates[153] = my
candidates[154] = cede[opp]
candidates[155] = beat[my]
for i, a in enumerate(candidates[150:156]):
for offset in range(3):
candidates[150+6+24*i+offset*8] = shift(offset+wins, a)
candidates[150+6+24*i+offset*8+1] = shift(offset+wins+ties, a)
candidates[150+6+24*i+offset*8+2] = shift(offset+losses+ties, a)
candidates[150+6+24*i+offset*8+3] = shift(offset+losses, a)
candidates[150+6+24*i+offset*8+4] = unshift(offset+wins, a)
candidates[150+6+24*i+offset*8+5] = unshift(offset+wins+ties, a)
candidates[150+6+24*i+offset*8+6] = unshift(offset+losses+ties, a)
candidates[150+6+24*i+offset*8+7] = unshift(offset+losses, a)
break
for length in range(min(5, len(opp_hist)), 0, -1):
p = opp_patterns[opp_hist[-length:]]
if p != "":
opp = p[-1]
my = p[-2]
candidates[300] = beat[opp]
candidates[301] = cede[my]
candidates[302] = opp
candidates[303] = my
candidates[304] = cede[opp]
candidates[305] = beat[my]
for i, a in enumerate(candidates[300:306]):
for offset in range(3):
candidates[300+6+24*i+offset*8] = shift(offset+wins, a)
candidates[300+6+24*i+offset*8+1] = shift(offset+wins+ties, a)
candidates[300+6+24*i+offset*8+2] = shift(offset+losses+ties, a)
candidates[300+6+24*i+offset*8+3] = shift(offset+losses, a)
candidates[300+6+24*i+offset*8+4] = unshift(offset+wins, a)
candidates[300+6+24*i+offset*8+5] = unshift(offset+wins+ties, a)
candidates[300+6+24*i+offset*8+6] = unshift(offset+losses+ties, a)
candidates[300+6+24*i+offset*8+7] = unshift(offset+losses, a)
break
for i in range(4):
main_candidates[i] = candidates[indices[i]]
main_candidates[5] = cede[max([e for e in my_stats.items()], key=operator.itemgetter(1))[0]]
output = main_candidates[main_index]
|
inconnu
Re : Petit guide pour aider au choix d'un langage
Encore une fois merci pour toutes ces références (j'ai déjà trois bouquins de 300 pages à m'infuser ). Bon c'est quand même passionnant, dès fois un peu complexe, mais je suis globalement assez surpris de la qualité. Pour tout dire, je ne pensais pas qu'il existait des ouvrages en Français, aussi complet et accessible au débutant. Par exemple sur l'architecture de l'ordinateur.
Je voulais vous demander, à tout hasard hein, si vous connaissiez une référence d'un bouquin ou d'un site, sur l'assembleur ? Ou peut être que le bouquin sur l'architecture de l'ordinateur va aborder ce langage de manière suffisante (j'en suis aux microinstructions ) ?
Le Farfadet Spatial
Re : Petit guide pour aider au choix d'un langage
Salut à tous !
Je voulais vous demander, à tout hasard hein, si vous connaissiez une référence d'un bouquin ou d'un site, sur l'assembleur ? Ou peut être que le bouquin sur l'architecture de l'ordinateur va aborder ce langage de manière suffisante (j'en suis aux microinstructions ) ?
Bon, d'abord, ce n'est pas une question pour les débutants, donc je ne vais pas l'ajouter à la présentation.
Sinon, pour répondre à ta question, cela dépend fondamentalement de l'architecture à laquelle tu t'intéresses. Tu sais déjà programmer, donc tu as surtout besoin des jeux d'instructions et de savoir comment fonctionne le matériel. En conséquence, je te conseille de regarder les documentations des constructeurs et, en effet, des ouvrages génériques sur les architectures (par exemple ce qu'il y a dans la présentation du début de ce fil de discussion). De mon temps, il y avait La Bible PC de Michäel TISCHER, mais je crois que ce livre n'est plus édité. Tu peux déjà jeter un œil vers :
Assembleur x86
Kip R. IRVINE
Campus Press
Cela dit, ce livre est vraiment orienté DOS (et architecture x86).
Si tu n'as pas de problème avec l'anglais, tu peux aller voir ce site :
Il y a de quoi faire.
Juste une dernière chose : au vu des architectures actuelles et des capacités qui sont celles des compilateurs désormais, l'assembleur n'est plus le moyen de faire les programmes les plus rapides. De plus, l'assembleur n'est pas, par définition, portable. En revanche, cela reste toujours le moyen d'accéder finement au matériel. Je te conseille donc de ne pas chercher à faire des programmes entiers en assembleur, mais de t'habituer à coder en assembleur les parties spécifiques où tu as besoin de cet accès.
Voilà, j'espère que cela aide.
À bientôt.
Le Farfadet Spatial
L'antre du farfadet :
http://le.farfadet.spatial.free.fr/
Textes, musiques et peintures
Hors ligne
tshirtman
Re : Petit guide pour aider au choix d'un langage
tiens j'étais passé à coté de ça, je traîne pas assez sur le forum (enfin pas assez partout).
C'est sympa comme idée, et ça peut en effet aider un débutant, mais je suis un peu déçus par certaines mise en avant ou en retrait, tu fais le choix de donner ton avis sur les langage, ce qui ouvre donc à la critique de ces avis .
Personnelement je pense que conseiller le PHP comme "excellent choix" sans préciser plus est dangereux, car s'il a l'avantage de la simplicité du déploiement (apache mod_php présent partout), c'est loin d'être un bon langage, il est bourré de problèmes syntaxiques et encourage les mauvaises pratiques, l'avis est je pense à nuancer sérieusement.
Python (bon, je suis fan, "full disclosur") par contre est clairement mis en retrait, alors que c'est un langage d'une grande clarté, complètement objet, très fonctionnel (et très doué pour d'autre paradigmes), très indiqué pour le débutant, mais en effet, le swinnen n'est pas une bonne référence, les bouquins de tarek sont mieux. Bref, à mon sens, parmis les premiers langage a soumettre à un débutant, du fait de sa simplicité, la richesse de sa std, la clarté de sa syntax, le dynamisme de sa comunauté, et j'en passe.
Le c++, bon, comme beaucoup de gens t'es fan, et tu l'indique en gros, comme la solution à tous les problèmes… tu nuances quand même: ce n'est pas un langage pour débutant (ouf), il faut quand même être clair, s'il peut servir de solution à pratiquement tous les développement possible (mais quel langage moderne ne peut pas y prétendre?) il est clairement peu clair, trop complexe, personne ne le maitrise à fond, toute entreprise s'en servant sérieusement en interne, pose des règles très strictes à son utilisation, pour que tout le monde s'en serve pareil (sinon personne ne parle le même c++) (voir par exemple les règles de codage pour le c++ chez google ). Et s'il était si parfait, le java (qui le le porte a un niveau supérieur) n'aurait pas eu un tel succès, mais le java a ses propres problèmes.
Bref, je pense pas mal de mal de c++ (et ceci m'a aidé à savoir pourquoi).
Mais je le répète, excellente initiative.
Hors ligne
Le Farfadet Spatial
Re : Petit guide pour aider au choix d'un langage
Salut à tous !
tu fais le choix de donner ton avis sur les langage
Ce n'est pas un choix, il est tout simplement impossible de faire autrement : ce n'est pas la peine de se le cacher, à partir du moment où quelqu'un donne un conseil pour le choix d'un langage, il donne son avis. Cela dit, j'ai essayé d'être aussi objectif que possible, d'une part. D'autre part, il est clairement indiqué dès le départ qu'il y a nécessairement une part de subjectivité dans la présentation. D'ailleurs, ton intervention, je ne t'en fais pas le reproche, est très fortement marquée par ta propre subjectivité.
Personnelement je pense que conseiller le PHP comme "excellent choix"
Ce n'est pas ce qui est écrit :
Pour le web, PHP (en général couplé à MySQL) est un très bon choix.
Je ne vois pas en quoi c'est faux. Même si, oui, Python est un langage plus sérieux.
sans préciser plus est dangereux, car s'il a l'avantage de la simplicité du déploiement (apache mod_php présent partout), c'est loin d'être un bon langage, il est bourré de problèmes syntaxiques et encourage les mauvaises pratiques, l'avis est je pense à nuancer sérieusement.
Je reconnais bien là le Python-maniaque ! Cela dit, d'accord : que penses-tu qu'il faudrait indiquer ?
Python (bon, je suis fan, "full disclosur") par contre est clairement mis en retrait
Il n'est certainement pas mis en retrait. Je ne vois pas ce qui te permet de dire cela. Par contre, je trouve que les Python-maniaques ont tendance à vouloir absolument que l'on dise que Python est le meilleur langage du monde. Python a des qualités, mais il n'existe pas de langage parfait pour tout, Python pas plus que les autres.
Le c++, bon, comme beaucoup de gens t'es fan
Là encore, je ne sais pas ce qui te permet de dire ça. En tout cas, ce n'est certainement pas vrai. S'il se trouve que c'est le langage que j'utilise le plus souvent, c'est en raison d'un choix pragmatique, certainement pas parce que je pense que c'est le meilleur langage du monde, ni mon préféré, ni celui que je vais utiliser dans toutes les situations.
et tu l'indique en gros, comme la solution à tous les problèmes…
J'indique clairement qu'il est difficile, mal enseigné et qu'il n'est pas adapté pour débuter : en quoi cela sous-entend que ce serait la solution à tous les problèmes ?
Et s'il était si parfait, le java (qui le le porte a un niveau supérieur) n'aurait pas eu un tel succès, mais le java a ses propres problèmes.
Encore une fois, je n'ai jamais pensé ni affirmé que C++ est parfait. Ensuite, Java et C++ ne sont pas concurrents, leurs domaines d'applications ne sont absolument pas les mêmes. Java n'est pas le niveau supérieur de C++. Les concurrents, à l'heure actuelle, de C++ sont C et Fortran, les concurrents de Java sont C# et Objective-C.
Bon, tu adores Python et déteste C++. Il n'empêche que C++ a de vrais qualités et que Python ne peut servir à tout. Lorsque l'on montre les indéniables qualités de C++, cela ne veut pas dire qu'on dit qu'il est la solution pour tout. À l'inverse, si on ne dit pas que Python est le seul langage à considérer, cela ne veut pas dire qu'on le met en retrait.
À bientôt.
Le Farfadet Spatial
L'antre du farfadet :
http://le.farfadet.spatial.free.fr/
Textes, musiques et peintures
Hors ligne
tshirtman
Re : Petit guide pour aider au choix d'un langage
sans vouloir entrer dans une polémique stérile, les quelques points qui me font pensé que ton jugement de python, comme de C++, sont biaisés…
Dans à peu près le même domaine que Perl, mais avec peut-être une syntaxe plus claire : Python.
on lit ici que python sert grosso modo aux mêmes choses que perl (principalement des petits scripts systeme, un peu de web, mais perl est clairement en perte de vitesse de ce coté là) et que ça syntaxe est *peut être* plus claire que celle de l'un des languages considéré comme l'un des plus cryptiques existant… pour un langage généralement loué pour sa clarté c'est un peu fort… pour un langage de plus en plus adopté par les scientifiques en remplacement du fortran qu'ils trainent depuis 30ans, pour un langage énormément utilisé dans le web, dans les applis industrielles, dans le dev d'outil graphique, dans de plus en plus de jeux vidéos… c'est quand même un peu fort de le comparer aux mêmes utilisations que perl…
Enfin, un langage extrêmement versatile et généraliste,
là j'aurais pus m'attendre à ce que tu parle de python… mais non c'est bien le classique c++, le langage du futur d'il y a 20ans, qui n'a pas atteins ses objectifs de pdm malgré le fait qu'il s'appuie honteusement sur le succès du C sans en reprendre les principaux avantages, simplicité et cohérence, sans apporter un modèle objet complet… bref, sans le mériter…
edit: sur l'aspect plus constructif, je pense que faire un peu de mise en forme (séparation des langages en sections, avec titre en gras, lien vers le site du langage…) pourrais donner une meilleur visibilité en langages en bas de liste, qui sont un peu perdus dans le flou, pour qui n'a pas encore lus l'ensemble d'une traite.
Dernière modification par tshirtman (Le 14/03/2010, à 21:59)
Hors ligne
Le Farfadet Spatial
Re : Petit guide pour aider au choix d'un langage
Salut à tous !
on lit ici que python sert grosso modo aux mêmes choses que perl (principalement des petits scripts systeme, un peu de web, mais perl est clairement en perte de vitesse de ce coté là) et que ça syntaxe est *peut être* plus claire que celle de l'un des languages considéré comme l'un des plus cryptiques existant… pour un langage généralement loué pour sa clarté c'est un peu fort…
L'argument de lisibilité n'est pas facile à manipuler, raison pour laquelle j'ai mis le « peut-être ».
Aujourd'hui, il est indéniable que Python, Perl et Ruby ont des domaines d'applications semblables et, pour l'instant, aucun n'a vraiment pris le pas sur les autres, en dépit de l'effet de loupe de Ubuntu. Même si, personnellement, je suis plus intéressé par Python, je pense qu'aujourd'hui, dans une présentation, on ne peut pas passer l'un des trois sous silence et il reste encore pertinent de les comparer les uns aux autres.
pour un langage de plus en plus adopté par les scientifiques en remplacement du fortran qu'ils trainent depuis 30ans
Python ne vient pas en remplacement de Fortran pour les scientifiques. Il vient plutôt en remplacement de Matlab ou de R. De plus, il reste inadéquat pour pas mal de cas : par exemple, il est inapproprié au calcul numérique intensif.
pour un langage énormément utilisé dans le web, dans les applis industrielles, dans le dev d'outil graphique, dans de plus en plus de jeux vidéos… c'est quand même un peu fort de le comparer aux mêmes utilisations que perl…
Hé bien Perl est utilisé dans le web, dans des applications industrielles, dans le développement d'outils graphiques, dans des jeux vidéos... Chez pas mal de scientifique également. Du coup, il est parfaitement pertinent de les comparer dans ce cadre.
Enfin, un langage extrêmement versatile et généraliste,
là j'aurais pus m'attendre à ce que tu parle de python… mais non c'est bien le classique c++
Hé bien, il est incontestable que C++ est extrêmement versatile, à tel point que son créateur l'a vu utilisé dans des domaines qu'il n'envisageait pas (voir Le Langage C++ de Bjarne STROUSTRUP).
Je suis désolé, mais, pas plus que C++, je n'ai pas que Python dans la tête.
le langage du futur d'il y a 20ans, qui n'a pas atteinds ses objectifs de pdm malgrès le fait qu'il s'appuis honteusement sur le succès du C sans en reprendre les principaux avantages, simplicité et cohérence, sans apporter un modele objet complet… bref, sans le mériter…
Donc, c'est moi qui ait un point de vue partial et biaisé...
Déjà, je ne sais pas où tu as trouvé le moindre objectif de parts de marché pour C++, qui est à l'origine un projet marginal, dont le succès a surpris (voir The Design and Evolution of C++ de Bjarne STROUSTRUP). On est très loin des ambitions de CPL à son époque ou de D plus récemment.
Ensuite, ce n'est pas honteux de s'appuyer sur le passé, au contraire, c'est une bonne chose, c'est même une pratique nécessaire.
Enfin, le modèle objet était balbutiant aux début de C++ et c'est notamment l'expérience acquise avec ce langage qui a permis de le faire évoluer et à devenir mature.
Inutile d'essayer : je ne dirais pas que Python est le meilleur langage du monde parfait pour tout, ni non plus que C++ est lamentable. Ni l'une ni l'autre de ces affirmations n'est vraie, ceci d'un point de vue parfaitement objectif.
Par contre, si tu me donnais les précautions que tu voudrais que je donne concernant PHP, je serais intéressé.
À bientôt.
Le Farfadet Spatial
L'antre du farfadet :
http://le.farfadet.spatial.free.fr/
Textes, musiques et peintures
Hors ligne
tshirtman
Re : Petit guide pour aider au choix d'un langage
Le nom C++ n'a pas été choisit au hasard, j'ai pas lus le bouquin (de référence) de Bjarn en entier (j'avoue que son style, de même que la syntaxe de son langage m'a assommé), mais j'ai bien lus le début, le but est bien de dire "c'est comme le C, mais avec des classes, mais en moins bricolage que 'C with classes'" C, à l'époque était le roi du monde… mais bon oui, on va dire que c'était un petit projet (comme C en 1968-9, c'est marrant). Quand je parle de s'appuyer sur le succès je ne parle pas de technique (même si le C++ à fait des erreurs du fait de vouloir rester compatible avec C) mais de marketing, le succès en entreprise du C++ (même partiel) est largement du au fait qu'il soit "presque C, mais avec des trucs en plus, donc ça peut servir" dans la tête de beaucoup de gens (tu constate toi même qu'il est très mal enseigné la plupart du temps) et donc profite d'un aura qu'il ne mérite pas.
Pour le python dans les calculs numériques, numpy ne doit pas t'être étranger, c'est puissant… certes il faut être capable d'exprimer tes problèmes de façons matricielles, mais c'est vraiment rapide… Certes on peut aller plus vite, notamment en C, mais autant coder un module C spécialisé dans les calculs qu'on a a faire (si numpy ne convient pas), et faire tout le code autour en python.
Pour PHP, j'aurais tendance à dire "un langage extrêmement répandus pour le WEB, facile à apprendre, mais souffrant d'un syntaxe assez peu cohérente, et de failles de sécurité récurrentes si employés sans une extrême rigueur", ou un truc du genre… disons qu'un langage conçus pour faire compteur de pages de CV à la base… ben ça donne ça…
Hors ligne
Le Farfadet Spatial
Re : Petit guide pour aider au choix d'un langage
Salut à tous !
Quand je parle de s'appuyer sur le succès je ne parle pas de technique (même si le C++ à fait des erreurs du fait de vouloir rester compatible avec C) mais de marketing
C++ n'appartient à personne, comment parler de marketing ?
Pour le python dans les calculs numériques, numpy ne doit pas t'être étranger, c'est puissant… certes il faut être capable d'exprimer tes problèmes de façons matricielles, mais c'est vraiment rapide… Certes on peut aller plus vite, notamment en C, mais autant coder un module C spécialisé dans les calculs qu'on a a faire (si numpy ne convient pas), et faire tout le code autour en python.
Bof.
Non, vraiment, il faut se rendre compte qu'absolument tous les langages, Python inclus, ont leurs limites et leurs domaines d'application. En dépit de la qualité de Numpy, Python n'est pas du tout adapté au calcul numérique à haute performance. Il n'a de toute façon pas été conçu pour cela et ce n'est pas l'objectif de Numpy -- il s'agit plutôt d'un moyen de le rendre très concurrentiel par rapport à Matlab.
Pour PHP, j'aurais tendance à dire "un langage extrêmement répandus pour le WEB, facile à apprendre, mais souffrant d'un syntaxe assez peu cohérente, et de failles de sécurité récurrentes si employés sans une extrême rigueur", ou un truc du genre… disons qu'un langage conçus pour faire compteur de pages de CV à la base… ben ça donne ça…
À la base, PHP est une collection de scripts qui ont été développés pour un site personnel. Il a rencontré un vrai succès parce qu'il a été le bon langage au bon moment. Finalement, c'est la même histoire que C et C++.
Alors, oui, il est permissif et il faut faire attention à la façon dont on code avec. Cela dit, c'est plus un problème de faire attention aux références que l'on donne à son sujet. Pour moi, cela n'empêche qu'il demeure une bonne porte d'entrée à la programmation. Veux-tu dire que tu le déconseillerais à un débutant ? Mais alors, pour quelqu'un qui veut faire du web dynamique et seulement du web dynamique, que lui conseiller ? Sachant que c'est tout de même moins immédiat avec Python, qui n'est d'ailleurs pas proposé par tous les hébergeurs.
Bon, je suis désolé, mais je ne vois pas ce que je peux faire de tout cela.
À bientôt.
Le Farfadet Spatial
L'antre du farfadet :
http://le.farfadet.spatial.free.fr/
Textes, musiques et peintures
Hors ligne
tshirtman
Re : Petit guide pour aider au choix d'un langage
Bah, tu en fais ce que tu veux, j'ai dis ce que j'avais à dire ^^.
Non, vraiment, il faut se rendre compte qu'absolument tous les langages, Python inclus, ont leurs limites et leurs domaines d'application
c'est vachement dogmatique, et ça me fait penser que tu cherche un domaine ou python ne serait pas le roi juste par ce que pour toi ce n'est pas possible de se dire "general purpose" et de tenir le paris…
Sinon, juste sur la forme
edit: sur l'aspect plus constructif, je pense que faire un peu de mise en forme (séparation des langages en sections, avec titre en gras, lien vers le site du langage…) pourrais donner une meilleur visibilité en langages en bas de liste, qui sont un peu perdus dans le flou, pour qui n'a pas encore lus l'ensemble d'une traite.
c'est moins une affaire de gout personnels que de clarté, je pense pas que ce soit trop controversé comme opinion.
a++
Hors ligne
Le Farfadet Spatial
Re : Petit guide pour aider au choix d'un langage
Salut à tous !
Non, vraiment, il faut se rendre compte qu'absolument tous les langages, Python inclus, ont leurs limites et leurs domaines d'application
c'est vachement dogmatique, et ça me fait penser que tu cherche un domaine ou python ne serait pas le roi juste par ce que pour toi ce n'est pas possible de se dire "general purpose" et de tenir le paris…
Ça-y-est, je vais me faire taxer de dogmatisme...
Depuis les années 60, on a vu plein de langage dont l'ambition affichée était de devenir le langage parfait pour tout. Il y a eu PL/I ou CPL, par exemple. Tous ont été des échecs retentissant : non seulement ils n'ont jamais réussi à s'imposer, mais en plus, ils n'ont jamais fait disparaître les langages qu'ils entendaient supplanter, à savoir principalement Fortran et Cobol. Ces expériences répétées me font, mais pas seulement moi, considérer avec beaucoup de circonspection toutes les tentatives qui prétendent réaliser un tel objectif. D'autant que différents domaines d'applications peuvent avoir des besoins contradictoires en matière de langage de programmation.
Toujours est-il qu'aujourd'hui il n'existe pas de langage parfait pour tout. Ce n'a d'ailleurs jamais été l'objectif de Python. Il n'est notamment pas approprié au calcul numérique intensif, comme déjà dit ici, même s'il est pertinent de l'utiliser dans les traitements périphériques. Python n'est pas adapté à la programmation système. Python n'est pas non plus nécessairement le meilleur choix dans de l'embarqué -- non, dans ce cas, je ne crois pas que C++ ni même C soit un bon choix. Et ainsi de suite, j'arrête l'inventaire à la Prévert.
Vraiment, il est important, si l'on apprécie un langage et que l'on veut vraiment le servir, de bien se rendre compte qu'il a un certain domaine d'application et de bien cerner ce domaine. Parce que, lorsque quelqu'un a un problème particulier, lui dire sans chercher à analyser le problème « utilise Python, c'est parfait pour tout », c'est non seulement dogmatique, mais en plus un bon moyen de le dégouter du langage lorsque, sans faire attention, on lui a conseillé ce langage alors qu'il n'est justement pas approprié au problème.
je pense que faire un peu de mise en forme (séparation des langages en sections, avec titre en gras, lien vers le site du langage…) pourrais donner une meilleur visibilité en langages en bas de liste, qui sont un peu perdus dans le flou, pour qui n'a pas encore lus l'ensemble d'une traite.
Ça, en revanche, c'est une remarque que je vais prendre en compte.
À bientôt.
Le Farfadet Spatial
L'antre du farfadet :
http://le.farfadet.spatial.free.fr/
Textes, musiques et peintures
Hors ligne
no_spleen
Re : Petit guide pour aider au choix d'un langage
Bonjour,
Cela m'intéresserai pas mal si un fan de python pour le calcul scientifique pouvait faire un petit code de benchmark pour que l'on puisse comparer avec le c++ ou le fortran.
tshirtman, tu te sentirais capable de faire un code python réalisant, par exemple,
- le remplissage d'une matrice carrée M de taille n avec des nombres aléatoires
- le produit matriciel MxM
- L'affichage du temps de calcul ?
Hors ligne
Le Farfadet Spatial
Re : Petit guide pour aider au choix d'un langage
Salut à tous !
- L'affichage du temps de calcul ?
Faire du benchmark est intéressant, c'est certain. Cela dit, il vaut mieux éviter de faire afficher le temps de calcul par le code lui-même et avoir recours à la fonction « time ». Le reste du code n'est pas difficile à faire. Par contre, il faut prendre une taille de matrice conséquente pour pouvoir dire quelque chose.
Également, cela ne serait qu'une étape, il faudrait songer à une application un peu plus réaliste.
En tout cas, ça m'intéresse aussi. Une simple multiplication matricielle doit ressembler à ça (je laisse à un Python-manique le soin de sortir un meilleur code) :
import numpy
A = numpy.random.rand(100000,100000)
B = numpy.random.rand(100000,100000)
C = A * B
print C
Je n'ai pas testé.
À bientôt.
Le Farfadet Spatial
L'antre du farfadet :
http://le.farfadet.spatial.free.fr/
Textes, musiques et peintures
Hors ligne
no_spleen
Re : Petit guide pour aider au choix d'un langage
Ton code à l'air de marcher. Je vais faire quelques tests. Juste une question, les matrices de numpy sont des simples ou double précision ?
Hors ligne
tshirtman
Re : Petit guide pour aider au choix d'un langage
Ce qui est bien en python c'est que quand on a un code simple et clair, c'est el général le code optimal pour la tache... le tiens me parait tout à fait correct, j'ai juste enlevé le print, qui élimine tout intéret au bench, vu la lenteur des IO en général, et des terminaux en particulier.
Tu t'es posé la question de la taille mémoire nécessaire pour ce code? ^^ 100000*100000 int ça fait 10 000 000 000 de fois 32bits, j'ai peur de manquer de ram là (en fait il me laisse pas faire, ça doit être pour ça ^^) t'as une lib en C++ qui te fais ça? J'ai divisé par 100 (un 0 de chaque coté) et c'est encore un peu long (sur mon eeepc), mais ça passe. Si quelqu'un veux bien me donner un code C++ équivalent, que je bench… savoir si c'est des facteurs ou des magnitudes la différence de perf… si c'est des facteurs < 10 je vois vraiment pas pourquoi quiconque se donnerait le mal de faire ça en C++ ^^.
pour l'embarqué en effet python est un peu gros (problème de stdlib énorme) mais il y a des solutions comme Cython ou ShedSkin, qui compilent du Python en C/C++ relativement optimisé, tout python n'est pas implémenté mais c'est très correct…
je lance avec time et je te dis quand ça se termine.
Hors ligne
no_spleen
Re : Petit guide pour aider au choix d'un langage
Voila,
J'ai utilisé des matrices 1000 x 1000 pour que cela tienne en mémoire (Le farfadet doit avoir plus l'habitude des matrices creuses), et j'ai réalisé la multiplication 10 fois.
Le code python
import numpy
for i in range(10):
A = numpy.random.rand(1000,1000)
B = numpy.random.rand(1000,1000)
C = A * B
le résultat
time python matmul.py real 0m0.791suser 0m0.640ssys 0m0.148s
le code fortran
PROGRAM TEST
IMPLICIT NONE
DOUBLE PRECISION :: A(1000,1000),B(1000,1000),C(1000,1000)
INTEGER :: i
DO i=1,10
CALL random_number(A)
CALL random_number(B)
CALL dgemm('N','N', 1000, 1000, 1000, 1 , A , 1000 , B , 1000 , 1 , C , 1000)
END DO
END PROGRAM TEST
Le résultat
time ./matmul real 0m0.415suser 0m0.384ssys 0m0.016s
Ce code fortran a été compilé avec l'intel fortran et l'implémentation MKL de blas, ce qui fait peut être la différence...
Hors ligne
tshirtman
Re : Petit guide pour aider au choix d'un langage
avec des matrices de 10000*10000 c'est vachement plus long ^^ (sur eeepc901).
real 9m36.119suser 0m27.438ssys 0m23.717
edit: sur ma machine de boulot (E8200 @ 2.66GHz), c'est bien plus raisonnable:
real 0m8.727suser 0m6.848ssys 0m1.664s
j'installe fortran-compiler, j'ai jamais touché à ce langage ^^.
Dernière modification par tshirtman (Le 15/03/2010, à 11:47)
Hors ligne
no_spleen
Re : Petit guide pour aider au choix d'un langage
tshirtman, le petit exemple plus haut m'a séduit par la simplicité du langage. Et je me demande si je ne vais pas me prêter au même exercice que récemment avec le C++, c'est à dire écrire un petit code FEM en python, pour comparer les avantages et inconvénients (voir le post "de l'utilité de la POO en calcul scientifique").
Sur amazon, j'ai trouvé ce livre
"Python - Les Fondamentaux du langage - La Programmation pour les scientifiques. de Matthieu Brucher"
Le connais-tu ? Connais-tu une autre référence moderne ? Ce qui m'attire dans ce livre est qu'il semble spécifiquement orienté sur le calcul scientifique.
Hors ligne
tshirtman
Re : Petit guide pour aider au choix d'un langage
Content de voir que le langage te plaît . Non je ne le connais pas, et je n'ai pas spécialement lus de livres sur le sujet, mon utilisation de python est plus généraliste, j'ai lus beaucoup d'articles sur l'utilisation du python dans les sciences (biologie, physique…), mais je pourrais difficilement te recommander un livre (je suis plus "net" que bouquins pour apprendre).
ps: Pourrais tu m'indiquer la ligne exacte avec laquelle tu as compilé ton code fortran plus haut? que je compare le produit matriciel de 10000² sur ma machine? ^^
Hors ligne
no_spleen
Re : Petit guide pour aider au choix d'un langage
en fait j'utilise le compilateur INTEL FORTRAN et les librairies MKL d'intel.
J'ai un makefile que j'utilise pour tous mes programmes fortran
F= /opt/intel/FORTRAN/11.1/064/bin/ia32/ifort
I = /opt/intel/mkl/10.2.4.032/include/32
L = /opt/intel/mkl/10.2.4.032/lib/32
matmul : matmul.f90
$F -O4 -o matmul matmul.f90 -I$I -L$L -lmkl_blas95 -lmkl_lapack95 -lmkl_intel -lmkl_sequential -lmkl_solver -lmkl_lapack -lmkl_core -liomp5 -lguide -lpthread -lm
J'ai voulu compiler l'exemple avec gfortran et l'implémentation debian de blas, mais c'est extrêmement lent chez moi, je ne comprend pas pourquoi, voila ce que j'ai fait
gfortran -O4 -o matmul matmul.f90 -L/usr/lib -lblas
J'ai l'impression que gfortran n'aime pas les grosses matrices, ce qui serait le comble pour un compilateur destiné uniquement à du calcul numérique !
Hors ligne
no_spleen
Re : Petit guide pour aider au choix d'un langage
Les compilateurs INTEL pour C++ et fortran sont gratuits sur linux
Hors ligne
tshirtman
Re : Petit guide pour aider au choix d'un langage
ok, téléchargement en cours ^^ (quasi 700mo en tout, c'est du lourd, je sais pas comment on faisait du fortran en 1957, huhu).
Dernière modification par tshirtman (Le 15/03/2010, à 16:40)
Hors ligne
no_spleen
Re : Petit guide pour aider au choix d'un langage
et t'as essayé avec gfortran ?
Hors ligne
tshirtman
Re : Petit guide pour aider au choix d'un langage
ça compile, et ça s'exécute, mais c'est bien plus lent que python là…
real 4m45.748suser 4m44.974ssys 0m0.748s
là ou python mets moins d'une seconde (j'en suis resté au 1000x1000 là)
Dernière modification par tshirtman (Le 15/03/2010, à 17:01)
Hors ligne
no_spleen
Re : Petit guide pour aider au choix d'un langage
Ben oui, apparemment gfortran est très mauvais. Rien ne sert d'avoir un bon langage si l'on a pas un bon compilo !!!
Hors ligne
tshirtman
Re : Petit guide pour aider au choix d'un langage
on peut parler de pypy pour les perfs de python aussi
http://speed.pypy.org/overview/
pfff il faut libstdc++5 maintenant… ok, un problème de lib à l'exécution maintenant, c'est vachement fun a installer ce truc ^^
Dernière modification par tshirtman (Le 15/03/2010, à 17:31)
Hors ligne |
#1001 Le 25/04/2010, à 17:05
oGu
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour à tous !
Tout d'abord félicitations pour l'excellente tenue de ce forum et pour tous les scripts que j'ai piqué sur ce topic!!
Etant passé de Firefox à IceCat dernièrement, j'aimerais qu'un Ubuntero sachant scripter adapte ce fichier (qui défragmente les données sqlite de Firefox) à mon nouveau browser :
#!/usr/bin/env python
# coding=utf8
from os import getenv,getuid,kill,waitpid
from subprocess import call,Popen,PIPE
from os.path import abspath,join,exists
from signal import SIGTERM
def recup_rep_profiles():
base_profile=join(getenv('HOME'),".mozilla","firefox")
profiles_ini=join(base_profile,"profiles.ini")
rep_profiles=[]
lignes=open(profiles_ini).read().splitlines()
for ligne in lignes:
ligne=ligne.strip()
if ligne.startswith("Path="):
rep_profiles.append(join(base_profile,ligne[5:]))
return rep_profiles
def patch_sessionstore(sessionstore):
if not exists(sessionstore): return
chaine=open(sessionstore,"rb").read()
chaine=chaine.replace('session:{state:"running"}})','session:{state:"stopped"}})')
open(sessionstore,"wb").write(chaine)
def recup_firefox_pids():
lignes=Popen(['pgrep','-x','firefox','-U',str(getuid())],stdout=PIPE).communicate()[0]
firefox_pids=[]
for ligne in lignes.splitlines():
ligne=ligne.strip()
if not ligne: continue
firefox_pids.append(int(ligne))
return firefox_pids
def kill_firefox(firefox_pids):
for pid in firefox_pids: kill(pid,SIGTERM)
# Récupère les chemins vers les profiles
profiles=recup_rep_profiles()
# Récupère les PID des processus Firefox en cours d’exécution
pids=recup_firefox_pids()
# Demande confirmation si Firefox est en cours d’exécution
if pids:
retour=call(['zenity','--question','--title=Attention','--text=Firefox est encours d’exécution\nSi vous cliquez sur Valider, Firefox sera fermé le temps d’effectuer l’optimisation et relancé après'])
if retour==1: exit(1)
# Arrête Firefox
kill_firefox(pids)
# Patche les fichiers sessionstore.js
for profile in profiles:
patch_sessionstore(join(profile,"sessionstore.js"))
# Compacte les bases de données
progress=Popen(["zenity","--title","Optimisation","--text","Optimisation en cours...","--progress","--pulsate","--auto-close"],stdin=PIPE)
for profile in profiles:
Popen(['find',profile,'-name','*.sqlite','-print','-exec','sqlite3','{}','VACUUM',';'],stdout=progress.stdin)
progress.stdin.close()
# Relance Firefox s’il était lancé
if pids:
Popen(['firefox'],stderr=open("/dev/null"),stdout=open("/dev/null"))
Est-ce techniquement possible? Si oui merci d'avance à celui/ceux qui se pencheront sur la transformation de ce code!
Bye!
Ogu
Dernière modification par oGu (Le 25/04/2010, à 17:06)
Ubunteros de tous les pays, unissez-vous !
Hors ligne
#1002 Le 27/04/2010, à 13:02
bugs néo
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
ce script permet de rendre plus rapide Firefox?
jeu de course open source earth-race (le jeu est en réécriture complète depuis janvier, afin de pouvoir aller plus vite par la suite)
Hors ligne
#1003 Le 27/04/2010, à 14:12
oGu
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour!
Oui, c'est ce qu'il est censé faire : en défragmentant les bases de données (awesome bar etc...) il rend leur accès plus rapide.
Après j'ignore si l'effet est réel, ou si c'est un placebo...
Quelques liens :
-ici la page avec le script originel (tiens, je me rends compte que l'accentuation pose problème avec le script que j'ai posté, ce qui n'est pas le cas sur le script initial)
http://zigazou.wordpress.com/2009/05/21/optimisation-et-gain-despace-sous-firefox-3/
-pour les fans de la ligne de commande, la procédure à suivre :
http://www.webdevonlinux.fr/2009/04/optimiser-le-demarrage-de-firefox/
Dernière modification par oGu (Le 27/04/2010, à 14:17)
Ubunteros de tous les pays, unissez-vous !
Hors ligne
#1004 Le 29/04/2010, à 12:46
2F
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
bonjour,
un script utile (de débutant mais qui focntionne) pour éviter de se déplacer quand on fait de la maintenance.
il permet d'avoir pas mal d'infos sur une machine win et après permet quasiement tout si vous faites vos scripts en bat, reg ou vbs pour les lancer sur la machine distante.
il faut :
-winexe
-zenity
-un dossier en lecture seule au moins, accessible depuis le réseau (à renseigner dans gdiag.conf)
-la suite pstools à insérer dans ce même dossier
ce script peut être très évolutif et très utile, j'utilise moi, une version non graphique avec nos scripts perso du boulot qu'on lance directement par le menu.
donc j'ai voulu le rendre général. vos remarques, conseils sont les bienvenu.
gdiag.sh
#! /bin/bash
# Effectue des diagnostiques et rapporte des informations sur des pc win
# Licence : GPL
# Dépendance : winexe, zenity, la suite pstools sur un serveur, rdesktop, samba
# Il faut un accès en lecture seule au moins sur un serveur acessible depuis l'exterieur (a renseigner dans gdiag.conf)
#à finir
#finir lancement script personnaliser (script) : vérifier la présence du fichier sur le serveur
#possibilité de tuer un processus avec tskill PID
. ./gdiag.conf
pingo="Ping"
nmap="Nmap"
proc="Processus en cours"
heure="Resynchroniser date & heure"
service="Services (processus) : start, stop, restart"
script="Lancer un script .vbs .reg ou .bat"
psinfo="Infos PC (programmes installés, SP, ram, HDD, etc..)"
mstsc="Ouvrir port RDP, rdesktop & fermer RDP"
msconfig="Afficher msconfig démarrage"
browse="Parcourir le disque C:/"
logs="Afficher les erreurs du journal d'évènements des 24H"
diag="Diag complet"
reboot="Rebooter la machine"
console="Accéder à la console DOS distante"
autre="Passer sur une autre machine"
quit="Quitter"
machine () {
target=$(zenity --entry --title="Gdiag" --text="Nom de machine ou IP");
if ping -c 1 -w 3 $target
then
mdp=$(zenity --entry --hide-text --title="Gdiag" --text="Mot de passe administrateur");
menu
else
echo "$target ne ping pas !!" | zenity --text-info --title="$target NE PING PAS !" --width 500 --height 200 && machine
fi
}
machine
menu () {
rm -Rf res.txt && killall winexe
action=`zenity --list --title "$titre" --width 500 --height 550 --radiolist --column=Choix --column "Action" TRUE "$pingo" FALSE "$nmap" FALSE "$proc" FALSE "$heure" FALSE "$service" FALSE "$script" FALSE "$psinfo" FALSE "$mstsc" FALSE "$msconfig" FALSE "$browse" FALSE "$logs" FALSE "$reboot" FALSE "$console" FALSE "$autre" FALSE "$diag" FALSE "$quit"`
}
while [ "$choix" != "quit" ]; do
menu
case "$action" in
"$pingo")
ping $target | zenity --text-info --width 700 --height 500 --title="$pingo de $target"
;;
"$nmap")
nmap $target | zenity --text-info --width 700 --height 500 --title="$nmap de $target"
;;
"$proc")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k qprocess * /system & exit" | zenity --text-info --width 600 --height 800 --title="$proc"
;;
"$heure")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k w32tm /resync /rediscover & exit" | zenity --progress --pulsate --auto-close && echo "Allume un cierge mais $target devrait être à l'heure maintenant" | zenity --text-info --title="$heure de $target" --width 400 --height 200
;;
#stopper, relancer ou lancer un service : mettre le nom du service sans l'extension
"$service")
serv=$(zenity --entry --title="Gdiag" --text="Nom du service");
action=`zenity --list --title "Services" --width 500 --height 550 --radiolist --column=choix --column "Action" TRUE "lancer" FALSE "stopper" FALSE "relancer" FALSE "$quit"`
case "$action" in
"lancer")
acte=start
;;
"stopper")
acte=stop
;;
"relancer")
acte=restart
;;
"quit")
menu
;;
esac
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k \\\\"$serveur"\psservice.exe /accepteula $acte $serv & exit" | zenity --progress --pulsate --auto-close && echo "le service $serv est $acte sur $target" | zenity --text-info --width 400 --height 200 --title="$relancetb2 sur $target"
;;
# pour lancer un programme bat vbs ou reg depuis le dossier du serveur : mettre le nom exacte du fichier avec extension
"$script")
#choix du fichier script
file=$(zenity --entry --title="Gdiag" --text="Nom du script dans le dossier $serveur avec son extension :");
#vérifie l'extension du fichier
ext=`echo $file | grep -o '\.[^.]*$'`
case $ext in
".bat")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k start \\\\"$serveur"\\"$file" & exit" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".BAT")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k start \\\\"$serveur"\\"$file" & exit" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".vbs")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k cscript \\\\"$serveur"\"$file" & exit"" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".VBS")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k cscript \\\\"$serveur"\"$file" & exit"" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".reg")
winexe -U "$target"/administrateur%$mdp //"$target" "regedit /S \\\\"$serveur"\"$file" & exit"" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".REG")
winexe -U "$target"/administrateur%$mdp //"$target" "regedit /S \\\\"$serveur"\"$file" & exit"" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
*)
zenity --warning --text="extension non supportée"
;;
esac
;;
#liste les infos pc
"$psinfo")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k \\\\"$serveur"\psinfo.exe -d -s /accepteula & exit" | zenity --text-info --title="$psinfo de $target" --width 700 --height 300
;;
#ouvre le port RDP, lance rdesktop et ferme le port RDP
"$mstsc")
winexe -U "$target"/administrateur%$mdp //"$target" "regedit /S \\\\"$serveur"\mstscon.reg"
notify-send -i /usr/share/icons/gnome/scalable/apps/gnome-terminal.svg Hop "Ouverture du Terminal serveur client sur "$target"" && sleep 5 && rdesktop "$target" && winexe -U "$target"/administrateur%$mdp //"$target" "regedit /S \\\\"$serveur"\mstscoff.reg" && notify-send -i /usr/share/icons/gnome/scalable/apps/gnome-terminal.svg Hop "Fermeture du Terminal serveur client sur "$target""
;;
#msconfig
"$msconfig")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k reg query HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run & exit" > res.txt 2>&1 | zenity --progress --pulsate --auto-close
cat res.txt |grep REG_SZ | zenity --text-info --title="$msconfig de $target" --width 700 --height 300
;;
"$browse")
`nautilus smb://administrateur@"$target"/c$`
;;
#affiche les erreurs du journal d'évènements des 24H
"$logs")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k \\\\"$serveur"\psloglist.exe -d 1 -f e /accepteula & exit" >res.txt | zenity --progress --pulsate --auto-close && cat res.txt|grep -e ] -e Time| zenity --text-info --title="$autorun de $target" --width 400 --height 200
;;
#ping, nmap, liste processus, infos pc, msconfig et erreurs journal évènement des 24H
"$diag")
rm -f resultat.txt
ping3=`ping -c 3 "$target"`
echo -n "#### \\033[1;31mPING\\033[0m ####"
echo -n "#### PING ####" > resultat.txt
echo " " >> resultat.txt
echo " " >> resultat.txt
echo -n "$ping3" >> resultat.txt
echo " " >> resultat.txt
echo " " >> resultat.txt
echo -n "#### \\033[1;31mNMAP\\033[0m ####" &&
echo " " >> resultat.txt
echo "#### NMAP ####" >> resultat.txt
echo " " >> resultat.txt
gnome-terminal -x nmap "$target" -o nmap.txt && sleep 4 && cat nmap.txt |grep -v Nmap | grep -v Interesting >> resultat.txt
echo -n "#### \\033[1;31mINFOS PC\\033[0m ####"
echo -n "#### INFOS PC ####" >> resultat.txt
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k \\\\"$serveur"\psinfo.exe -d -s /accepteula & exit" >> resultat.txt
echo " " >> resultat.txt
echo -n "#### \\033[1;31mPROCESSUS\\033[0m ####"
echo -n "#### PROCESSUS ####" >> resultat.txt
echo " " >> resultat.txt
echo " " >> resultat.txt
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k qprocess * /system & exit" >> resultat.txt
echo -n "#### \\033[1;31mMSCONFIG\\033[0m ####"
echo " " >> resultat.txt
echo -n "#### MSCONFIG ####" >> resultat.txt
echo " " >> resultat.txt
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k reg query HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run & exit" > res.txt && cat res.txt |grep REG_SZ >> resultat.txt
echo " "
echo "rapport terminé" && clear && cat resultat.txt | zenity --text-info --title="$diag de $target" --width 800 --height 600
;;
#reboot
"$reboot")
net rpc shutdown -r -C "Votre ordianteur va redémarrer" -f -I "$target" -U administrateur%$mdp | zenity --text-info --title="reboot de $target en cours..." --width 400 --height 400
;;
#ok, tapez exit pour terminer le processus correctement
"$console")
gnome-terminal -x winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k qprocess * /system" &
;;
"$autre")
machine
;;
"$quit")
break;;
*)
esac
done
exit 0
le fichier de conf pauvre mais utile pour que ca serve à tout le monde
gdiag.conf
#mettre de la forme serveur="ip-serveur\mon dossier\scripts"
serveur=
et 2 tout petit .reg (a mettre aussi dans le dossier) qui servent dans le script... à vous de faire les votre après :
mstscon.reg
Windows Registry Editor Version 5.00[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server]"fDenyTSConnections"=dword:00000000
mstscoff.reg
Windows Registry Editor Version 5.00[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server]"fDenyTSConnections"=dword:00000001
voilà.
Bon app!
Dernière modification par 2F (Le 04/05/2010, à 17:02)
Hors ligne
#1005 Le 08/05/2010, à 16:28
malagasy
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour,
je n'y connais rien du tout en script, alors je voudrai savoir si quelqu'un peut me faire un petit script qui lance au démarrage de gnome:
compiz --replace
puisque depuis la mise à jour vers lucid, gnome n'aime pas trop compiz, et il faut que je lance cette commande à chaque fois,
Merci
Hors ligne
#1006 Le 08/05/2010, à 17:16
Levi59
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour,
je n'y connais rien du tout en script, alors je voudrai savoir si quelqu'un peut me faire un petit script qui lance au démarrage de gnome:
compiz --replace
puisque depuis la mise à jour vers lucid, gnome n'aime pas trop compiz, et il faut que je lance cette commande à chaque fois,
Merci
pourquoi un script? il te suffit de mettre "compiz-replace" dans les programmes au démarrage non?
Au pire si il faut le lancer en décalé, met "sleep X && compiz-replace" en remplaçant X par le nombre de seconde nécessaires.
Hors ligne
#1007 Le 08/05/2010, à 20:51
#1008 Le 08/05/2010, à 21:24
Levi59
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
c'est pour ça que j'adore cette communauté .. merci, ça marche
À vot' service M'sieurs! ^^
Dernière modification par Levi59 (Le 08/05/2010, à 21:25)
Hors ligne
#1009 Le 08/05/2010, à 22:59
#1010 Le 18/05/2010, à 10:16
yamo
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour,
Comme j'en avait marre de synaptic je me suis fait un script de mise à jour basé sur apt-get.
Tout d'abord, j'ai pris l'habitude de mettre tous mes scripts dans ~/bin ça permet d'avoir un répertoire home un peu rangé! Et de les lancer très simplement sans devoir ajouter ./ au début
Vous aller trouver étrange que je commence tout de suite par mettre à jour mais c'est par ce que j'utilise cron-apt qui permet de télécharger en tâche de fond les paquets, comme ça les mises paraissent encore plus rapides!
Attention, la mise à jour d'un système n'est pas triviale, lisez ces scripts avant de les utiliser. Personnellement, j'essaie toujours de comprendre ce que va faire une commande avant de l'exécuter.
Je n'ai laissé que la version console, la version graphique n'a pas vraiment d’intérêt vu que ça fonctionne bien de base en graphique.
~/bin/update.console.sh :
#!/bin/bash
# ~/bin/update.console.sh
# mise à jour du 11/12/2011
echo "mise à jour" &&
sudo nice -n 19 ionice -c 3 apt-get dist-upgrade -y &&
echo "nettoyage" &&
sudo nice -n 19 ionice -c 3 apt-get clean &&
echo "nettoyage" &&
sudo nice -n 19 ionice -c 3 apt-get autoclean &&
echo "coup de balai" &&
sudo nice -n 19 ionice -c 3 apt-get autoremove &&
echo "toc toc toc" &&
sudo nice -n 19 ionice -c 3 apt-get -qq update &&
## l'usage de -qq est totalement déconseillé en dehors d'update!
echo "mise à jour" &&
sudo nice -n 19 ionice -c 3 apt-get dist-upgrade -y &&
echo "dernieres mises à jour" &&
grep -v '\(half\|configure\|trigproc\|triggers-pending\|startup\|install-info\|unpacked\|config-files\|triggers-awaited\|installed\)' /var/log/dpkg.log
Pour tester mon script voici un script d'installation :
mkdir ~/bin & cd ~/bin/ &&
wget http://pasdenom.info/scripts/update.console.sh &&
chmod 554 ~/bin/update.console.sh
Enfin pour lancer le script il suffit de taper en console :
update.console.sh
Dernière modification par yamo (Le 11/12/2011, à 12:31)
Hors ligne
#1011 Le 28/05/2010, à 12:49
kazylax
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour,
un script existe pour Emesene ? de msn messenger
Cordialement,
Hors ligne
#1012 Le 28/05/2010, à 13:11
kyncani
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
J'aimerais savoir comment récupérer la liste des paquets installé manuellement.
Je sais récupérer la liste de tous les paquet installer, mais c'est très casse pied de la nettoyer pour ne conserver que les 60 intéressants...
J'ai donc mis les tag "auto" qu'il faut dans aptitude mais je ne sais pas comment en extraire la liste
aptitude search '~i!~M'
Hors ligne
#1013 Le 28/05/2010, à 20:56
Phendrax
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Yop
J'ai écrit une petite interface en python pour xinput que j'ai appelé gtk-xinput. Cela permet de facilement créer des pointeurs à l'écran et de leur associer des souris.
L'interface affiche donc la liste des pointeurs et chaque souris qui lui est associée. Sur le screen on peut voir par exemple que Logitech G500 est associée au pointeur dont l'id=2.
On peut créer des nouveaux pointeurs à l'écran avec le bouton "Ajouter" (en leur donnant un nom contenant uniquement des caractères alphanumériques) et en supprimer avec le bouton "Supprimer".
Le bouton "Recharger" sert à rafraichir l'affichage, par exemple si on vient de brancher une nouvelle souris.
Par défaut les souris sont associées au pointeur Virtual core. Il suffit de les glisser vers le pointeur que l'on veut.
Pour l'installer il est nécessaire d'avoir python, pygtk, libglade et xinput
sudo apt-get install python python-gtk2 libglade2-0 xinput
Le paquet debian de gtk-xinput peut être téléchargé ici : http://dl.free.fr/getfile.pl?file=/zoIHihCO
Le programme peut ensuite être lancé avec la commande gtk-xinput.
[Edit : il semblerait que le programme ne fonctionne que sous Lucid Lynx notamment à cause de la méthode set_visible() qui ne semble pas exister dans les versions précédentes et à cause de l'affichage de la commande xinput qui diffère selon les versions]
Dernière modification par Phendrax (Le 28/05/2010, à 21:47)
HP Pavillon dv6800 - Ubuntu 10.10 - GNOME 2.32.0
Hors ligne
#1014 Le 29/05/2010, à 01:42
BorX
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Marrant
Ça permet d'utiliser plusieurs souris en même temps ??
Autant je trouve ça vraiment intéressant, autant j'ai du mal à voir dans quel contexte l'utiliser...
A plusieurs ?
Pour les ambidextres ?
Hors ligne
#1015 Le 29/05/2010, à 04:43
kyncani
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Deux personnes sur une même machine
Hors ligne
#1016 Le 29/05/2010, à 12:01
hulk
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
MON scripte iptables
utilisation iptables start ou iptables stop
a placer dans /etc/init.d/ et a rendre exécutable puis l'activer avec update-rc.d
#! /bin/sh
### BEGIN INIT INFO
# Provides: iptables
# Required-Start:
# Required-Stop:
# Should-Start:
# Should-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 1 6
# Short-Description: script iptables
### END INIT INFO
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
case "$1" in
start)
### SUPRESSION de TOUTES LES ANCIENNES TABLES (OUVRE TOUS!!) ###
iptables -F
iptables -X
### BLOC TOUS !! (seules les autorisations des raigle aprés celle-ci sont prise en compte) ###
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP
### ACCEPT ALL interface loopbaak ###
iptables -I INPUT -i lo -j ACCEPT
iptables -I OUTPUT -o lo -j ACCEPT
### axepte en entrer les connection deja etablie (en gros sa permet d'axépter que les conection inicier
### par sont propre PC)
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
### DNS indispensable pour naviguer facilement sur le web ###
iptables -A OUTPUT -p udp -m udp --dport 53 -j ACCEPT
### HTTP navigation internet non sécuriséer ###
iptables -A OUTPUT -p tcp -m tcp --dport 80 -j ACCEPT
### HTTPS pour le site de banque .... ###
iptables -A OUTPUT -p tcp -m tcp --dport 443 -j ACCEPT
### emesene,pindgin,amsn... ####
iptables -A OUTPUT -p tcp -m tcp --dport 1863 -j ACCEPT
### pop thunderbird ... réceptions des message ####
iptables -A OUTPUT -p tcp -m tcp --dport 110 -j ACCEPT
### smtp thunderbird ... envoi des messages ###
iptables -A OUTPUT -p tcp -m tcp --dport 25 -j ACCEPT
### ntpdate ( client ntp )... sincro a un serveur de temp ###
iptables -A OUTPUT -p udp -m udp --dport 123 -j ACCEPT
### client-transmition
iptables -A OUTPUT -p udp -m udp --sport 51413 -j ACCEPT
iptables -A OUTPUT -p tcp -m tcp -s 192.168.1.2/255.255.255.255 --sport 30000:65000 -o eth0 -j ACCEPT
# remplacer 192.168.1.2 par votre adresse ip et eth0 par l'interface connecter a internet.
### ping ... autorise a pinger un ordinateur distent ###
iptables -A OUTPUT -p icmp -j ACCEPT
### ping ... autorise l'extèrieur a vous pinger ###
# iptables -A INPUT -p icmp -j ACCEPT # enlever le # du début de ligne pour activer cette règle
### LOG ### Log tous ce qui qui n'est pas accepter par une règles précédente
# prés requit : sudo apt-get install sysklogd
# echo 'kern.warning /var/log/iptables.log' > /etc/syslog.conf
iptables -A OUTPUT -j LOG --log-level 4
iptables -A INPUT -j LOG --log-level 4
iptables -A FORWARD -j LOG --log-level 4
;;
stop)
### OUVRE TOUS !! ###
iptables -F
iptables -X
;;
*)
N=/etc/init.d/${0##*/}
echo "Usage: $N {start|stop}" >&2
exit 1
;;
esac
exit 0
pour vérifier les log en temps réel 10 dernier entréer.
tail -f /var/log/iptables.log
Dernière modification par hulk (Le 07/12/2010, à 23:15)
Amilo A 1667G , turion64 , X700 .
debian squeeze amd64
driver libre radeon
Hors ligne
#1017 Le 31/05/2010, à 20:56
shamanphenix
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Pendant que je vous lisais, ça m'a donné envie, alors j'ai rapidement fait un premier jet (il faudrait que je rajoute un vidage de la corbeille, des miniatures Nautilus, etc. mais là n'est pas la question pour le moment ) pour mettre à jour mon système :
#!/bin/sh
# Permets de nettoyer et mettre à jour son système.
# Dépendance(s) : libnotify-bin ou zenity
# zenity --info --text="Mise à jour du système"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-working.png "Mise à jour du système"
# Mettre à jour la liste des fichiers disponibles dans les dépôts :
# zenity --info --text="Mise à jour de la liste des fichiers disponibles dans les dépôts"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-update-cache.png "Mise à jour de la liste des fichiers disponibles dans les dépôts"
sudo apt-get update
# Mettre à jour tous les paquets installés vers les dernières versions :
# zenity --info --text="Mise à jour de tous les paquets installés vers les dernières versions"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-upgrade.png "Mise à jour de tous les paquets installés vers les dernières versions"
sudo apt-get upgrade -y
# Mettre à jour tous les paquets installés vers les dernières versions en installant de nouveaux paquets si nécessaire :
# zenity --info --text="Mise à jour de tous les paquets installés vers les dernières versions en installant de nouveaux paquets si nécessaire"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-upgrade.png "Mise à jour de tous les paquets installés vers les dernières versions en installant de nouveaux paquets si nécessaire"
sudo apt-get dist-upgrade -y
# Supprimer les copies des paquets installés :
# zenity --info --text="Suppression des copies des paquets installés"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-cleanup.png "Suppression des copies des paquets installés"
sudo apt-get clean
# Supprimer les copies des paquets désinstallés :
# zenity --info --text="Suppression copies des paquets désinstallés"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-cleanup.png "Suppression copies des paquets désinstallés"
sudo apt-get autoclean -y
# zenity --info --text="Le système a été mis à jour"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-upgrade.png "Le système a été mis à jour"
Alors je sais, c'est super mal de mettre des "sudo" dans un script, et en plus c'est tout pourri puisque dans ce cas on est obligé de lancer le bouzin dans un terminal pour saisir le mot de passe root alors que j'aurais bien voulu le mettre dans mes scripts Nautilus...
Est-ce que l'un(e) d'entre vous aurait une idée géniale, par hasard ?
[edit]PS : c'est dommage que la balise "code" du forum ne colorie pas le texte, ça aiderait beaucoup à la lisibilité.[/edit]
Dernière modification par shamanphenix (Le 31/05/2010, à 20:57)
"Ubuntu". Si tous les gens du monde voulaient bien se tenir par la main... ce serait bien plus facile pour les électrocuter.
What did /home/user/DARTHVADER say to /home/user/DARTHVADER/LUKESKYWALKER ?I AM YOUR PARENT FOLDER.
Hors ligne
#1018 Le 31/05/2010, à 21:01
TatrefThekiller
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
gksudo ?
Hors ligne
#1019 Le 31/05/2010, à 21:12
shamanphenix
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
gksudo ?
En effet c'est une bonne idée, je pourrais remplacer le premier "sudo" par un "gksudo" (ça devrait suffire pour les autres, non ?), mais je dois avouer que je préfèrerais que cela soit entièrement automatisé (je sais saymal).
"Ubuntu". Si tous les gens du monde voulaient bien se tenir par la main... ce serait bien plus facile pour les électrocuter.
What did /home/user/DARTHVADER say to /home/user/DARTHVADER/LUKESKYWALKER ?I AM YOUR PARENT FOLDER.
Hors ligne
#1020 Le 31/05/2010, à 22:00
kyncani
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Ce genre de truc en en-tête peut marcher je crois :
if test `id -u` -ne 0; then
if test "$DISPLAY" = ""; then
exec sudo "$0" "$@"
else
exec gksudo "$0" "$@"
fi
exit 1
fi
Hors ligne
#1021 Le 01/06/2010, à 00:04
BorX
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Ou sinon
o Donner au script les droits root :
-rwx------ root root leScript
o Y virer tous les sudo qui sont à l'intérieur
o Et l'appeler avec sudo leScript
Ce qui continuera à demander un mot de passe à son lancement, sauf si on modifie le fichier /etc/sudoers de façon à ce script puisse être exécuté avec un sudo sans mot de passe.
Quelque chose du style
%sudo ALL=NOPASSWD: leScript
Mais je ne me souviens plus trop de la syntaxe.
C'est pas compliqué, faut chercher un tout petit peu
Hors ligne
#1022 Le 01/06/2010, à 08:21
draco31.fr
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
[edit]PS : c'est dommage que la balise "code" du forum ne colorie pas le texte, ça aiderait beaucoup à la lisibilité.[/edit]
C'est possible sur le wiki si tu indiques le langage ... mais à ma connaissance, ça n'a pas été prévu pour le forum.
Cela dit, il te suffit d'en faire la demande sur le topic de la nouvelle version du forum, ou de créer un rapport de bug sur launchpad pour le projet ubuntu-fr.org
Hors ligne
#1023 Le 01/06/2010, à 12:38
Levi59
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
shamanphenix a écrit :
[edit]PS : c'est dommage que la balise "code" du forum ne colorie pas le texte, ça aiderait beaucoup à la lisibilité.[/edit]
C'est possible sur le wiki si tu indiques le langage ... mais à ma connaissance, ça n'a pas été prévu pour le forum.
Cela dit, il te suffit d'en faire la demande sur le topic de la nouvelle version du forum, ou de créer un rapport de bug sur launchpad pour le projet ubuntu-fr.org
Ou encore de créer un plugin FF bien que ce ne soit pas du tout dans mes cordes... ^^
Si quelqu'un en est capable, voila un bon challenge!
Hors ligne
#1024 Le 01/06/2010, à 22:41
Nik0s
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
J'ai créé un petit script pour récupérer des wallpapers sur Interfacelift. Il y a, je pense, possibilité de l'améliorer, mais en voici le code
retiré
Dernière modification par Nik0s (Le 03/06/2010, à 20:46)
Hors ligne |
If you are using django-haystack, you may notice that filter by None won’t work:
from haystack.query import SearchQuerySet
SearchQuerySet().filter(some_field=None)
Haystack won’t report any error and will return no results.
Workaround for this I found by using Raw input field type value. So, solution follows:
from haystack.inputs import Raw
SearchQuerySet().exclude(some_field=Raw("[* TO *]")})
Other way around, filter all documents that have non-emtpy field value:
from haystack.inputs import Raw
SearchQuerySet().filter(some_field=Raw("[* TO *]")})
This could work for SOLR too and for other Haystack backends one can apply the same concept but with specific syntax of backend search language.
This solution is posted to StackOverflow where one can find more details: http://stackoverflow.com/a/22576854/565525
I have a form that contains forms.URLField:
class MyForm(ModelForm):
long_url = forms.URLField(label=_(u"URL" ), max_length=300, required=True,)
When a user inputs value that has trailing spaces, default URLField validation fails: Enter a valid URL.
I haven’t found some standardized and elegant way how to allow this, and looking into the source of django.form forms.py and fields.py I found several ways how to workaround this.
Chose inheriting Form._clean_fields method and changing form.data before validation occurs. Form.data is immutable QueryDict instance, so I needed to override this.
Finally:
def _clean_fields(self):
if "long_url" in self.data:
orig = self.data._mutable
self.data._mutable = True
self.data["long_url"] = self.data["long_url"].strip()
self.data._mutable = orig
return super(MyForm, self)._clean_fields()
This could be generalized, i.e. how to prepare field values for all input fields before validation. Example, remove leading and trailing blanks from all string fields. Create a custom base ModelForm class which needs to be inherited. This implementation is more robust, since it supports MergedDict object too (dict attribute contains list of QueryDicts which are merged):
class MyModelForm(ModelForm):
def _clean_fields(self):
for qdict in getattr(self.data, "dicts", [self.data]):
orig = qdict._mutable
qdict._mutable = True
for k, v in qdict.iteritems():
if isinstance(v, basestring):
qdict[k] = v.strip()
qdict._mutable = orig
return super(MyModelForm, self)._clean_fields()
class ShortenUrlNewForm(MyModelForm):
long_url = forms.URLField(label=_(u"URL" ), max_length=300, required=True,)
This can be applied for normal Forms too.
django has one interesting tag:
debug
Outputs a whole load of debugging information, including the current context and imported modules.
I use this boilerplate to display it properly:
<pre> {% filter force_escape %} {% debug %} {% endfilter %} </pre>
Other debug template techniques I posted on stackoverflow.
edit hosts:
sudo vim /etc/hosts
and add:
127.0.0.1 somesite.zz
127.0.0.1 robert.somesite.zz
127.0.0.1 lujo-lujo.zz
127.0.0.1 robert.lujo-lujo.zz
test it:
- start local dev server # in my case django app
- open browser: robert.somesite.zz
Usually OS X application can have multiple active windows. One can see the list of opened windows in application Window menu bar, and change the focus by selecting one of them. I was searching for some OS X keyboard shortcut to do this without mouse. There are several ways to do this (https://support.apple.com/kb/HT1343), but I find these two the most convenient:
The important thing is that the cycling is done through all windows of all opened applications - like a “better” alt-tab.
Recently I needed to solve algorithm problem “sum digits of all whole numbers to nr N”. I wanted to find out solution that scales, i.e. that doesn’t iterate through all numbers. After playing around with algorithm, I found it out.
Read More
In my spare time I’m learning clojure.
Haven’t done any serious stuff (yet), but I have been solving problems on 4clojure.com. I was pretty satisfied how it went, and my final goal was to reach top list 200.
Read More
The last few days I was answering questions on stackoverflow - mainly related to python and db2. It came out a bit addictive. Now I have 20 answers, raised my reputation to 449 and reached top 10% this week :).
Check my profile at http://stackoverflow.com/users/565525/robert-lujo .
Update: The addiction needed to stop. Resume: 51 answers, reputation > 1200. It was fun :)
Destructuring assignment (a.k.a. tuple unpack) in Python, seems to be very useful thing. The most basic variant:
»> x,y = 1,2
»> x,y
(1, 2)
what is identical to:
»> x, y = [1,2]
»> x, y = (1,2)
Read More
I had just released 0.20 version of permset.
Permset is simple standalone utility script to manage *nix permissions on file and directory trees based on patterns.
Check the example session to get into the idea behind.
I use Twitter primarly as a bookmarking service.
I know that Twitter is not bookmarking service and there are specialized services for such needs. In my case, using this way started as an experiment, but later I found this way very convenient.
I wrote a script that enables me to incrementally backup all my tweets in a textual file in YAML format, by parsing HTML Twitter pages. Explanation and the script follows …
Read More
Mercurial provides many ways to do branch based development. I was searchingfor the best in-repo branch solution. I chose named branches …
Read More
The article provides some information and tips on the subject: how to count characters, bytes and words in Vim.
Read More
Recently I invested some time to learn about new and popular language Go. I wanna give a test-drive, and since I have Windows XP and there is no GO official windows Go port, I needed to do some manual work.
Read More |
I'm seriously confused with getting django-socialregistration working.
So my settings file:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.request"
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'socialregistration.middleware.FacebookMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
FACEBOOK_REQUEST_PERMISSIONS = 'email,user_about_me'
AUTHENTICATION_BACKENDS = (
'socialregistration.auth.FacebookAuth',
'django.contrib.auth.backends.ModelBackend',
)
INSTALLED_APPS = (
...
'socialregistration',
...
)
FACEBOOK_APP_ID = '...'
FACEBOOK_API_KEY = '...'
FACEBOOK_SECRET_KEY = '...'
My views are using the request context, my templates have the required items to display the button and when click the FB connect button does open the pop up asking me if I want to connect with the app.
So here's where I get lost in what should happen.
Case 1: I'm a new user, never registered with example.com but I do have a FB account and see the FB connect button, so I click on it to register (this is django-socialregistration, shouldn't it be the starting point for the registration process?). Get the pop up and click the "allow" button on the FB pop up page and ... I get redirected to a page "/accounts/login/" with "Your username and password didn't match. Please try again."
In the Admin there's nothing created - no user account, no socialregistration facebook profiles, nada. If I go into my Facebook account settings it shows that I'm connected to my app.
Case 2: I'm an existing user, I login to my site, then click on the FB connect button. I get pop up, I click "allow" and get redirected to profile page. In the Admin, there is a new socialregistration facebook profile. I then log out of the site, come back and click on the facebook connect button and ... get redirected to "/accounts/login/" and the same your username/password didn't match.
help?! I've hit google so much trying to find others with the problem nada - folks talking about errors (errors I'd love, would let me track down wth is happening, but all I can tell is the authentication is just a big fat fail.).
Thanks in advance.
Edit: Partial fix on the issue to my question aboveMake sure you're pointing in your settings.py to the template folder for the socialregistration app or move the templates into a location that's on your template path. That was my problem to the above question - however, I'm still not able to get this app working. |
Retrieving Mails with Twisted
Programming a POP3 client to retrieve mails in the Twisted framework is more complex and takes more code. The logic to retrieve mails is all in a class that subclasses POPClient (from twisted.mail.pop3client). Due to the event-driven nature of Twisted, it's easier to define a method for each step, register the success, and failure callbacks to the method to enter the next step and handle any error, respectively.
from twisted.internet.protocol import ClientCreator
from twisted.mail.pop3client import POP3Client
class MyPOP3Client(POP3Client):
def serverGreeting(self, msg):
POP3Client.serverGreeting(self, msg)
self.login(self.myuser, self.mypass).addCallbacks(
self.do_stat, errorHandler)
def do_stat(self, result):
self.stat().addCallbacks(self.do_retrieve, errorHandler)
In the class MyPOP3Client, the first step to get mails is the serverGreeting method, which Twisted will invoke when the client starts. This method invokes the superclass's serverGreeting, and then logs in to the POP3 server with a user name and password. The login method returns a Deferred object, invoking the addCallbacks method to register the do_stat method (called upon successful login), and the errorHandler method (called on login error).
Similarly, the do_stat method invokes POP3Client's stat method to perform a POP3 STAT command, and registers the next step as do_retrieve. Because the call to method stat is asynchronous, it cannot return its results to the caller with return values. Instead, it passes the results as arguments to the success callback registered to the stat method. The second parameter to the do_retrieve method is a list, of which the first element is the number of messages in the POP3 account.
def do_retrieve(self, stats):
self.format = "%-3s %-15s %s"
self.num_messages = stats[0]
self.cur_message = 0
print self.myuser, "has", self.num_messages, "messages"
if self.num_messages > 0:
if deletion:
print "Deleting", self.num_messages, "messages",
self.delete(0).addCallbacks(self.do_delete_msg, errorHandler)
else:
print self.format % ("Num", "From", "Subject")
self.retrieve(0).addCallbacks(self.do_retrieve_msg, errorHandler)
else:
reactor.stop()
def do_retrieve_msg(self, lines):
msg = email.message_from_string("\r\n".join(lines))
print self.format % (self.cur_message, msg["From"], msg["Subject"])
self.cur_message += 1
if (self.cur_message < self.num_messages):
self.retrieve(self.cur_message).addCallbacks(
self.do_retrieve_msg, errorHandler)
else:
reactor.stop()
If there is no message in the mailbox, the code calls reactor.stop to tell Twisted to shutdown. Otherwise, it invokes retrieve(0) to get the first message. Its success callback, do_retrieve_msg, handles the message by displaying its summary, and then retrieves the next message. Because the method do_retrieve_msg gets invoked for all subsequent messages, the code uses an instance variable, cur_message, to keep track of the current message number and to determine when it has handled all messages. When it has processed everything, it stops the Twisted main loop.
Because the logic of mail retrieval is similar to deletion, both features are in the same class, MyPOP3Client. The instance variable deletion denotes the current mode of working. You can see its initialization in __init__, along with the user name and password. More interesting is the setting of allowInsecureLogin to true, which allows login to a server without authentication challenge non-encrypted transport.
def __init__(self):
self.myuser = user
self.mypass = passwd
self.deletion = deletion
self.allowInsecureLogin = True
def do_delete_msg(self, str):
print ".",
self.cur_message += 1
if (self.cur_message < self.num_messages):
self.delete(self.cur_message).addCallbacks(
self.do_delete_msg, errorHandler)
else:
print " done."
q = self.quit()
q.addCallbacks(lambda _: reactor.stop(), errorHandler)
To delete a mail, call the delete method of class POP3Client. Similar to the core poplib module, this method just marks the mail for deletion, and the actual deletion occurs when you send the POP3 command QUIT to the server, as with the quit method. Finally, Twisted's execution thread stops when the quitting action completes.
pop3 = ClientCreator(reactor, MyPOP3Client)
d = pop3.connectTCP(host, 110)
reactor.run()
With the implementation of the desired mail handling in class MyPOP3Client, you can launch the client. With its descriptive name, the class ClientCreator (from twisted.internet.protocol) provides a convenient way to start a communication client. This code passes the reactor and the MyPOP3Client class to create a ClientCreator, and begins the mail retrieval by calling connectTCP with the specified server and port number. Twisted's execution loop then kicks off by reactor.run().
Invoking do_retrieve_msg repeatedly for all messages is conceptually tedious and lengthy, when compared to the DeferredList mechanism which keeps track of several actions and gets notified when all actions complete, as in the case of sending mails. However, collecting the Deferreds of multiple calls to retrieve of POP3Client in a DeferredList simply does not work in Twisted (Versions 2.2.0 and 2.4.0). The success callback never gets invoked (see mail-twisted.py).
Doing Telnet with Twisted
Twisted can power a Telnet client in a way similar to, but simpler than, the POP3 client. the Telnet conversation logic goes in a subclass of Telnet (from twisted.conch.telnet).
def stop(host):
from twisted.internet.protocol import ClientCreator
from twisted.conch.telnet import Telnet
class MyTelnet(Telnet):
def dataReceived(self, data):
if "Login id:" in data:
self._write("root\n")
elif "Password:" in data:
self._write("root\n")
elif "Welcome" in data:
d = self._write("shutdown\n")
def connectionLost(self, reason):
reactor.stop()
print "done."
mytelnet = ClientCreator(reactor, MyTelnet)
d = mytelnet.connectTCP(host, 4555)
reactor.run()
The class MyTelnet overrides two methods of class Telnet. The first method, dataReceived, is called when data arrives at the client. It checks the data received and calls the _write method to send the user name, password, or the shutdown command accordingly to the server. The second method is connectionLost, which Twisted calls when the server closes the telnet session. In that case, the program simply terminates the Twisted execution loop. The Telnet client starts by using the ClientClient class, connected to port 4555 of the James mail server.
When to Be Twisted?
The two functionally equivalent programs, one using Python core modules and the other using the Twisted framework, significantly differ from each other in terms of programming style and the amount of code. Then when should you use either of the two options?
For basic programs such as the command-line client of this example, the Python core networking modules are more desirable due to the simplicity and performance advantages. However, most real-world networking programs are very complex, and Twisted's asynchronous programming model is more effective. For example, BitTorrent, the popular peer-to-peer file sharing client that performs massive parallel downloading of data chunks from different sources, uses Twisted. Twisted also works well in programs with graphical user interface (GUI), because its asynchronous nature fits more seamlessly with the event-driven programming models of modern GUI frameworks. In fact, Twisted has integration with popular GUI frameworks including PyGTK, Qt, Tkinter, WxPython, and Win32.
The other area where Twisted shines is in server programming. A typical network server uses multithreading so that it can handle multiple clients concurrently. The asynchronous mechanism of Twisted alleviates the creation and handling of threads by server programs. In addition, Twisted provides several protocols on which to build new networking services, enabling rapid development of complex servers. One such project is Quotient, which adopts Twisted to build a multiprotocol messaging server that supports a variety of protocols and services including SMTP, POP3, IMAP, webmail, and SIP.
Kendrew Lau is a consultant in Hong Kong, with focus on Java, Linux, and other OSS technologies.
Return to the Python DevCenter. |
Here's my ORM entity class. The primary key is composite cause 'id_string' may be the same for different users (identified by uid). One thing I understood from Postgres SQL error when creating a table based on this class (
ProgrammingError: (ProgrammingError) there is no unique constraint matching given keys for referenced table "sync_entities"
) is that I need to add something to parent_id_string's ForeignKey() argument. And that something is, I think, the current record's uid.
Do you suggest to try using different primary key (autoincrementing integer) or there is some other way?
class SyncEntity(Base):
__tablename__ = 'sync_entities'
__table_args__ = (ForeignKeyConstraint(['uid'], ['users.uid'], ondelete='CASCADE'), {})
uid = Column(BigInteger, primary_key=True)
id_string = Column(String, primary_key=True)
parent_id_string = Column(String, ForeignKey('sync_entities.id_string'))
children = relation('SyncEntity',
primaryjoin=('sync_entities.c.id_string==sync_entities.c.parent_id_string'),
backref=backref('parent', \
remote_side=[id_string]))
# old_parent_id = ...
version = Column(BigInteger)
mtime = Column(BigInteger)
ctime = Column(BigInteger)
name = Column(String)
non_unique_name = Column(String)
sync_timestamp = Column(BigInteger)
server_defined_unique_tag = Column(String)
position_in_parent = Column(BigInteger)
insert_after_item_id = Column(String, ForeignKey('sync_entities.id_string'))
insert_after = relation('SyncEntity',
primaryjoin=('sync_entities.c.id_string==sync_entities.c.insert_after_item_id'),
remote_side=[id_string])
deleted = Column(Boolean)
originator_cache_guid = Column(String)
originator_client_item_id = Column(String)
specifics = Column(LargeBinary)
folder = Column(Boolean)
client_defined_unique_tag = Column(String)
ordinal_in_parent = Column(LargeBinary)
|
When plotting several y axis in Matplotlib, is there a way to specify how to align the origin (and/or some ytick labels) of the right axis with a specific value of the left axis?
Here is my problem: I would like to plot two set of data as well as their difference (basically, I am trying to reproduce this kind of graph).
I can reproduce it, but I have to manually adjust the ylim of the right axis so that the origin is aligned with the value I want from the left axis.
I putted below an example of a simplified version of the code I use. As you can see, I have to manually adjust scale of the right axis to align the origin of the right axis as well as the square.
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
grp1 = np.array([1.202, 1.477, 1.223, 1.284, 1.701, 1.724, 1.099,
1.242, 1.099, 1.217, 1.291, 1.305, 1.333, 1.246])
grp2 = np.array([1.802, 2.399, 2.559, 2.286, 2.460, 2.511, 2.296,
1.975])
fig = plt.figure(figsize=(6, 6))
ax = fig.add_axes([0.17, 0.13, 0.6, 0.7])
# remove top and right spines and turn ticks off if no spine
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('left')
# postition of tick out
ax.tick_params(axis='both', direction='out', width=3, length=7,
labelsize=24, pad=8)
ax.spines['left'].set_linewidth(3)
# plot groups vs random numbers to create dot plot
ax.plot(np.random.normal(1, 0.05, grp2.size), grp2, 'ok', markersize=10)
ax.plot(np.random.normal(2, 0.05, grp1.size), grp1, 'ok', markersize=10)
ax.errorbar(1, np.mean(grp2), fmt='_r', markersize=50,
markeredgewidth=3)
ax.errorbar(2, np.mean(grp1), fmt='_r', markersize=50,
markeredgewidth=3)
ax.set_xlim((0.5, 3.5))
ax.set_ylim((0, 2.7))
# create right axis
ax2 = fig.add_axes(ax.get_position(), sharex=ax, frameon=False)
ax2.spines['left'].set_color('none')
ax2.spines['top'].set_color('none')
ax2.spines['bottom'].set_color('none')
ax2.xaxis.set_ticks_position('none')
ax2.yaxis.set_ticks_position('right')
# postition of tick out
ax2.tick_params(axis='both', direction='out', width=3, length=7,
labelsize=24, pad=8)
ax2.spines['right'].set_linewidth(3)
ax2.set_xticks([1, 2, 3])
ax2.set_xticklabels(('gr2', 'gr1', 'D'))
ax2.hlines(0, 0.5, 3.5, linestyle='dotted')
#ax2.hlines((np.mean(adult)-np.mean(nrvm)), 0, 3.5, linestyle='dotted')
ax2.plot(3, (np.mean(grp1)-np.mean(grp2)), 'sk', markersize=12)
# manual adjustment so the origin is aligned width left group2
ax2.set_ylim((-2.3, 0.42))
ax2.set_xlim((0.5, 3.5))
plt.show()
|
You need to modify np.linalg.det to get the speed. The idea is that det() is a Python function, it does a lot of check first, and call the fortran routine, and does some array calculate to get the result.
Here is the code from numpy:
def slogdet(a):
a = asarray(a)
_assertRank2(a)
_assertSquareness(a)
t, result_t = _commonType(a)
a = _fastCopyAndTranspose(t, a)
a = _to_native_byte_order(a)
n = a.shape[0]
if isComplexType(t):
lapack_routine = lapack_lite.zgetrf
else:
lapack_routine = lapack_lite.dgetrf
pivots = zeros((n,), fortran_int)
results = lapack_routine(n, n, a, n, pivots, 0)
info = results['info']
if (info < 0):
raise TypeError, "Illegal input to Fortran routine"
elif (info > 0):
return (t(0.0), _realType(t)(-Inf))
sign = 1. - 2. * (add.reduce(pivots != arange(1, n + 1)) % 2)
d = diagonal(a)
absd = absolute(d)
sign *= multiply.reduce(d / absd)
log(absd, absd)
logdet = add.reduce(absd, axis=-1)
return sign, logdet
def det(a):
sign, logdet = slogdet(a)
return sign * exp(logdet)
To speedup this function, you can omit the check (it becomes your Responsibility to keep the input right), and collect the fortran results in an array, and do the final calculations for all the small arrays without for loop.
Here is my result:
import numpy as np
from numpy.core import intc
from numpy.linalg import lapack_lite
N = 1000
M = np.random.rand(N*10*10).reshape(N, 10, 10)
def dets(a):
length = a.shape[0]
dm = np.zeros(length)
for i in xrange(length):
dm[i] = np.linalg.det(M[i])
return dm
def dets_fast(a):
m = a.shape[0]
n = a.shape[1]
lapack_routine = lapack_lite.dgetrf
pivots = np.zeros((m, n), intc)
flags = np.arange(1, n + 1).reshape(1, -1)
for i in xrange(m):
tmp = a[i]
lapack_routine(n, n, tmp, n, pivots[i], 0)
sign = 1. - 2. * (np.add.reduce(pivots != flags, axis=1) % 2)
idx = np.arange(n)
d = a[:, idx, idx]
absd = np.absolute(d)
sign *= np.multiply.reduce(d / absd, axis=1)
np.log(absd, absd)
logdet = np.add.reduce(absd, axis=-1)
return sign * np.exp(logdet)
print np.allclose(dets(M), dets_fast(M.copy()))
and the speed is:
timeit dets(M)
10 loops, best of 3: 159 ms per loop
timeit dets_fast(M)
100 loops, best of 3: 10.7 ms per loop
So, by doing this, you can speedup by 15 times. That is a good result without any compiled code.
note: I omit the error check for the fortran routine. |
I'm writing simple GUI using wxPyhon and faced some problems.
My application does simple things: it draws triangle on the form and rotates it when user clicks arrow buttons or drags a mouse cursor over the form.
THe problems I see now are following:
1. Then I drag a mouse sursor fast the triangle rotates with keeping old image visible for a short time. When keeping moving a cursor fast for a while the drawing on the form is looking like 2 or 3 triangles.
2. If I expand the form to entire size of the screen the triangle moves unsmoothly, with small jumps from old appearance to a new one. I looked at coordinates of a mouse cursor during that rotating and noticed that they are tracked with gaps. Friend of mine said me that it is because I redraw the entire window of the application every time I wand to rotate the triangle a little bit. And that's why it works slowly and it slow down the tracking of a mouse cursor.
To refresh the view I'm using wx.Panel.Refresh() method. As drawing context I'm using wx.BufferedDC()
Please tell me how to draw CORRECTLY dynamicaly changing pictures/drawings on the wxPython forms, especially the way I make in that application.
I could place my code here, but it's too long. So if I must tell something more about my case - ask me please, I will answer.
Thanks !
class SimpleGraphics(wx.Panel):
def __init__(self, parent, size=(50, 50)):
super(SimpleGraphics, self).__init__(parent,
size=size,
style=wx.NO_BORDER)
self.color = "Black"
self.thickness = 2
self.pen = wx.Pen(self.color, self.thickness, wx.SOLID)
self.MARGIN = 1 #px
self.points = [[0.0, 0.5], [0.5, 0.0], [-0.5, -0.5]]
self.pos = (0, 0)
self.cur_vector = Vector2D(1, 1)
self.InitBuffer()
self.Bind(wx.EVT_SIZE, self.OnSize)
self.Bind(wx.EVT_IDLE, self.OnIdle)
self.Bind(wx.EVT_KEY_DOWN, self.OnKeyArrow)
# MOUSE TRACKING
self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
self.Bind(wx.EVT_MOTION, self.OnMotion)
self.Bind(wx.EVT_PAINT, self.OnPaint)
def InitBuffer(self):
self.client_size = self.GetClientSize()
self.buffer = wx.EmptyBitmap(self.client_size.width, self.client_size.height)
dc = wx.BufferedDC(None, self.buffer)
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear()
self.DrawImage(dc)
self.reInitBuffer = False
def OnSize(self, event):
self.reInitBuffer = True
def repaint_the_view(self):
self.InitBuffer()
self.Refresh()
def OnIdle(self, event):
if self.reInitBuffer:
self.repaint_the_view()
def OnKeyArrow(self, event):
key_code = event.GetKeyCode()
if key_code == wx.WXK_LEFT:
self.rotate_points(degrees_to_rad(5))
elif key_code == wx.WXK_RIGHT:
self.rotate_points(degrees_to_rad(-5))
self.repaint_the_view()
event.Skip()
def OnLeftDown(self, event):
# get the mouse position and capture the mouse
self.pos = event.GetPositionTuple()
self.cur_vector = create_vector2d(self.pos[0], self.pos[1],
self.client_size.width / 2,
self.client_size.height / 2)
self.CaptureMouse()
def OnLeftUp(self, event):
#release the mouse
if self.HasCapture():
self.ReleaseMouse()
def OnMotion(self, event):
if event.Dragging() and event.LeftIsDown():
newPos = event.GetPositionTuple()
new_vector = create_vector2d(newPos[0], newPos[1],
self.client_size.width / 2,
self.client_size.height / 2)
if new_vector.lenth() > 0.00001:
c = cos_a(self.cur_vector, new_vector)
s = sin_a(self.cur_vector, new_vector)
rot_matr = rotation_matrix(s, c)
self.rotate_points(rot_matr=rot_matr)
dc = wx.BufferedDC(wx.ClientDC(self), self.buffer) # this line I've added after posting the question
self.repaint_the_view()
self.cur_vector = new_vector
event.Skip()
def OnPaint(self, event):
wx.BufferedPaintDC(self, self.buffer)
def DrawImage(self, dc):
dc.SetPen(self.pen)
new_points = self.convetr_points_to_virtual()
dc.DrawPolygon([wx.Point(x, y) for (x, y) in new_points])
def to_x(self, X_Log):
X_Window = self.MARGIN + (1.0 / 2) * (X_Log + 1) * (self.client_size.width - 2 * self.MARGIN)
return int(X_Window)
def to_y(self, Y_Log):
Y_Window = self.MARGIN + (-1.0 / 2) * (Y_Log - 1) * (self.client_size.height - 2 * self.MARGIN)
return int(Y_Window)
def convetr_points_to_virtual(self):
return [(self.to_x(x), self.to_y(y)) for (x, y) in self.points]
def rotate_points(self, angle_in_degrees=None, rot_matr=None):
if angle_in_degrees is None:
self.points = [rotate_point(x, y , rotator_matrix=rot_matr) for (x, y) in self.points]
else:
self.points = [rotate_point(x, y , angle_in_degrees) for (x, y) in self.points]
class SimpleGraphicsFrame(wx.Frame):
def __init__(self, parent, *args, **kwargs):
wx.Frame.__init__(self, parent, *args, **kwargs)
# Attributes
self.panel = SimpleGraphics(self)
# Layout
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.panel, 1, wx.EXPAND)
self.SetSizer(sizer)
class SimpleGraphApp(wx.App):
def OnInit(self):
self.frame = SimpleGraphicsFrame(None,
title="Drawing Shapes",
size=(300, 400))
self.frame.Show()
return True
if __name__ == '__main__':
app = SimpleGraphApp(False)
app.MainLoop()
|
#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 have two models in different apps: modelA and modelB. They have a one-to-one relationship. Is there a way django can automatically create and save ModelB when modelA is saved?
class ModelA(models.Model):
name = models.CharField(max_length=30)
class ModelB(models.Model):
thing = models.OneToOneField(ModelA, primary_key=True)
num_widgets = IntegerField(default=0)
When I save a new ModelA I want a entry for it to be saved automatically in ModelB. How can I do this? Is there a way to specify that in ModelA? Or is this not possible, and I would just need to create and save ModelB in the view?
Edited to say the models are in different apps. |
A basic simulation of GBM doesn't seem to work. What am I doing wrong? The following code always outputs values less than 1e-20, instead of something distributed randomly around 1.0:
import math
import random
p = 1
dt = 1
mu = 0
sigma = 1
for k in range(100):
p *= math.exp((mu - sigma * sigma / 2) * dt +
sigma * random.normalvariate(0, dt * dt))
print(p)
I'm running:
ActivePython 3.1.2.3 (ActiveState Software Inc.) based on Python 3.1.2 (r312:79147, Mar 22 2010, 12:30:45) [MSC v.1500 64 bit (AMD64)] on win32
My OS is Windows 7 Professional on i7-930 CPU (64-bit).
I'd be happy to run any other tests on my machine to isolate the problem. |
Python-Powered Templates with Cheetah
by Andrew Glover
01/13/2005
XML transformation via XSL Transformations (XSLT) is quite popular and indeed powerful. Well-constructed XSL can produce HTML, PDF, XML, and just about any other text format imaginable. XSLT, however, requires that the subject data be a well-structured XML document, which often is not the case. Consequently, developers often transform native data structures (that is, business objects) into XML so as to use XSLT. This process, unfortunately, can increase code complexity and development time for a problem that has an easier solution: a template engine.
Template engines facilitate the construction of various formatted documents by allowing a static template to contain placeholders for dynamic output. Hence, there is no temporary format such as XML.
If the desired output is an HTML document, a template engine will operate on an HTML template that contains placeholders for values substituted at runtime. Using a template engine's transformation process is as simple as reading the template and providing a mapping of runtime values. The output of the transformation is the native format of the template--in this case, an HTML document. Similar to XSLT, template engines can produce any format possible, such as XML, HTML, and SQL; additionally, one can even use template engines as code generators. Template engines additionally facilitate the Model View Controller architecture by embodying the view component in templates.
Introducing Cheetah
Cheetah is an extremely effective Python-powered template engine that can generate any text-based format. Cheetah's impressive yet simple template language (based on Python) can yield the most complex of documents; moreover, Cheetah's object-oriented representation of documents creates plenty of opportunities for the reuse of code. Cheetah also possesses an impressive caching mechanism that fits a variety of performance scenarios.
Cheetah is surprisingly simple to use, as it essentially has two language constructs: placeholders and directives. Placeholders are values to substitute at runtime, and directives in effect are commands to execute at runtime. Placeholders are signified by $ signs and directives by # signs.
Is It Really That Easy?
With placeholders and directives in mind, the code below demonstrates a simple Cheetah template for generating PyUnit test cases.
1 import unittest
2
3 class ${classundertest}_test(unittest.TestCase):
4 def setUp(self):
5 pass
6 def tearDown(self):
7 pass
8 #for $testcase in $testcases
9 def test${testcase}(self):
10 pass
11 #end for
Cheetah will substitute the placeholder $clssundertst at runtime to create a string, such as query_test, that will form the test case's class name. Additionally, notice the directive, which in this case is a for loop, which iterates over a collection of testcases to create a series of class methods with names starting with test.
More on $Placeholders
To make ambiguous placeholders less ambiguous, you can surround them with {s, (s, [s, or nothing at all. Placeholders, furthermore, can be complex objects, which Cheetah can navigate quite easily through autocalling.
1 <person>
2 <firstname>$fname</firstname>
3 <middleinitial>$(mi)</middleinitial>
4 <lastname>${lname}</lastname>
5 <dateofbirth>$p.dob</dateofbirth>
6 </person>
As demonstrated in the above example, Cheetah is quite flexible when it comes to syntax. Notice that p.dob actually calls the dob attribute of the p object. Autocalling is quite flexible; you can use dictionaries as well as lists. Here's an example of autocalling with a dictionary:
1 <person> 2 <firstname>$dict.fname</firstname> 3 <middleinitial>$dict['mi']</middleinitial> 4 <lastname>$dict.lname</lastname> 5 <dateofbirth>$dict.dob</dateofbirth> 6 </person>
In the code above, $dict is a dictionary object defined something like this:
1 mp = {"fname":"Emily", "mi":"M", \
2 "lname":"Smith", "dob":"04/21/74"}
3 inputmap = {"dict":mp}
The $dict placeholder maps to a dictionary, mp, which contains the keys accessed in the previous code.
Directives
Directives are constructs that control the flow of template logic. With directives, templates can contain if/else logic blocks as well as looping constructs. What's more, it's possible to define Python functions through directives and call them throughout a template.
Using conditional logic is straightforward, as the syntax is Python.
1 #if $status == 'rejected'
2 <b>Don't call us, we'll call you</b>
3 #elif $status == 'passed'
4 We'll be calling you soon.
5 #end if
Looping constructs, like the for loop, are just as simple.
1 #for $person in $people
2 <TR>
3 <TD>$person.name</TD>
5 <TD>$person.weight</TD>
6 <TD>$person.height</TD>
7 </TR>
8 #end for
In the above example, a list named people contains a collection of objects having attributes of name, weight, and height.
If you need repetition, use the repeat directive:
1 <p> 2 Remember, your proposal was: <br/> 3 #repeat $times 4 $status <br/> 5 #end repeat 6 </p>
Notice how the #repeat directive takes a placeholder, in this case $times, which represents the number of times to repeat the text in the directive's body.
Occasionally, templates may need additional logic defined in a function. Strict Model-View-Controller design tries to avoid putting too much logic in a view, but you can define functions in templates and call them throughout the template at runtime.
The following example defines a function named caps switches the case of the passed-in parameter. Line 8 shows how to reference the directive and pass in placeholders.
1 #def caps($var)
2 $var.swapcase() #slurp
3 #end def
4
5 <html>
6 <body>
7 <p>
8 Your proposal was <b> $caps($status) </b>
9 </p>
The #slurp declaration in the code above consumes the newline so the resulting output is:
1 <html> 2 <body> 3 <p> 4 Your proposal was <b> REJECTED </b> 5 </p>
Caching
As mentioned earlier, Cheetah possesses a powerful caching mechanism for use in templates. As with everything else found in Cheetah, putting it to work is easy.
In performance-intensive scenarios, caching placeholders can increase a template's rendering speed. To cache a placeholder indefinitely (or as long as the template resides in memory), use the * syntax.
1 <p>
2 Submissions will be accepted
3 for $*days calendar days so please keep
4 trying until then.
5 </p>
In the above example, Cheetah caches the days placeholder as long as the template resides in memory.
If a template has more sophisticated caching requirements, you can cache placeholders for time intervals or even cache entire template regions. To cache for a specific time limit, add the desired value in terms of seconds, minutes, hours, days, or weeks.
1 <p>
2 After that, our $*4d*judges judges will
3 annouce the winners!
4 </p>
The above example caches the placeholder, judges, for four days. For seconds, use an s, minutes an m, hours an h, and weeks a w.
Caching an entire region is as simple as wrapping the region with a #cache directive.
1 #cache 2 <p> 3 Thanks again, <br/> 4 $staff 5 </p> 6 #end cache
Incidentally, you can also fine-tune the #cache directive with time intervals. See the Cheetah documentation for more details.
Using Templates
There are a few different ways to use templates. One of the easiest is to define the template in a file (commonly ending with a .tmpl suffix). To use it, read the template at runtime and supply it with a list of placeholder values. The list of placeholder values is a simple map, where the key should match the actual placeholder name. See the code below for an example.
1 tcs = ['runquery', 'executequery', 'deletequery']
2 mp = {"classundertest":"query_runner", "testcases":tcs}
3
4 from Cheetah.Template import Template
5 t = Template(file="default_pyunit.tmpl", searchList=[mp])
As demonstrated above, Cheetah performs placeholder mappings at template instantiation; hence, you create a template and retrieve its associated output in two lines of code (lines 4 and 5). Notice the map defined in line 2 contains keys, which presumably match placeholders found in the template, default_pyunit.tmpl, as shown in the code from the first example.
Cheetah treats templates as objects; moreover, these template objects are quite flexible and offer a few other usage strategies. To use templates as objects (accessing attributes, functions, and so on), you must compile them with Cheetah's compile command. For more information regarding compiling Cheetah templates, see the sidebar below.
A compiled template's placeholders become attributes, which can be set at runtime. Directives become executable Python code. As shown below, using a compiled template is as simple as importing it and setting the object's associated attributes.
1 from default_pyunit import default_pyunit
2
3 tmpl = default_pyunit()
4 tmpl.classundertest = "query_runner"
5 tmpl.testcases = ['runquery', 'executequery']
6
7 print tmpl
Putting It All Together
Armed with a basic knowledge of how to tap Cheetah's power, you can quickly build dynamic applications and have a good time of it! Imagine a scenario where a development team, using a bug-tracking system (such as Bugzilla), would like a weekly email report (in HTML, of course) that summarized all new bugs. The desired viewable information for a bug is the bug's ID number, the project containing the bug, the developer to whom the bug has been assigned, and a short description of the bug.
The template for this reporting application, as it turns out, is quite easy. Given a list of bug objects, a for loop directive will iterate over the list, creating a row in an HTML table with the corresponding ID, project name, owner, and description. In addition, some logic will determine whether the collection is empty so as to display an alternate message (perhaps congratulating the team for not creating any bugs for the week!).
With the view (the template) and the model (a bug object) defined, the controller becomes quite simple. First, query the bug database, then fill the template, and finally send the corresponding HTML email report via SMTP.
1 def runreport():
2 """
3 main method to run the report
4 """
5
6 import com.vanward.roach.template.template_engine as teng
7 import com.vanward.roach.email.email_engine as eeng
8
9 buglist = _getbuglist(7)
10 bmap = {"bugs":buglist, "numbugs":len(buglist), "numdays":7}
11 message = teng.getcontent(bmap)
12
13 email = _getemail(message)
14
15 eeng.sendemail(email)
In the code above, the runreport() function does a few things. Line 9 retrieves a list of bugs from the _getbuglist() function, which queries a database for bugs by time. Line 10 places the returned list of bugs in a map, along with the number of bugs, the length of buglist, and the number of days on which the query performed a search. Line 11 retrieves the content of the report from the teng object (see below) and then passes it to an email engine, which sends the resulting report.
1 def getcontent(mapvls):
2 from Cheetah.Template import Template
3 t = Template(file=_templatename(), searchList=[mapvls])
4 return t.respond()
5
6 def _templatename():
7 import com.vanward.roach.util.properties as prop
8 tmpl = prop.templateproperties
9 return tmpl["tmpl"]
The above code demonstrates a simple template engine that, when given a map of values, will instantiate a template and return the resulting body. Lines 6 through 9 define a function that returns the template's fully qualified name, such as $/var/tmp/bug_report.tmpl.
1 #include "header.txt"
2 <span>Bugzilla Weekly Summary</span>
3 #if $numbugs > 0
4 <p>Over the past $numdays days, the following bugs were created.
5 Click on the bug id to view the actual bugzilla bug report page.</p>
6 <br/>
7 <table border="0" width="400" valign="top">
8 <TR>
9 <TD>Bug Id</TD>
10 <TD>Project</TD>
11 <TD>Assigned To</TD>
12 <TD>Short Description</TD>
13 </TR>
14 #for $bug in $bugs
15 <TR>
16 <TD><A HREF="http://acme.org/show_bug.cgi?id=$bug.id">$bug.id</A></TD>
17 <TD>$bug.product</TD>
18 <TD>$bug.assignedto</TD>
19 <TD>$bug.shortdescrpt</TD>
20 </TR>
21 #end for
22 </table>
23 #else
24 <p>No bugs were created in bugzilla this week. </p>
25 #end if
26 #include "footer.txt"
The code above shows the resulting HTML bug report template. Line 1 and 26 demonstrate the #include directive, which as you have probably guessed by now includes text from outside a template. In this case, the report includes header and footer files, each containing a bit of static HTML. Line 3 demonstrates a simple #if directive, which will print some summary information if there are any bugs. The trailing #else and #end if are found on lines 23 and 25, respectively. Lines 14 through 21 use a #for directive to iterate over a list of bugs, creating an HTML table row for each one. Figure 1 shows the results of the Cheetah bug-reporting application.
Figure 1. Output of the bug-reporting application.
Cheetah offers the ability to compile template files into Python modules containing a class representing the template. These classes are easy to extend or agument. To compile a template, run the
This yields a Python module with the same name as the template (in this case called
class default_pyunit(Template)
The class extends Cheetah's Template class, which is the default base class for all templates.
Conclusion
The Cheetah template engine's simple language constructs and ease of use make data transformations a snap in terms of development time and complexity. What's more, Cheetah does not prevent architectures from using an MVC pattern, and Cheetah's built-in caching mechanism and object-oriented representation of templates yield an impressive alternative to XML transformations.
The next time you have the task of building an application with a "view," consider putting Cheetah to the test.
Resources
Cheetah's home
Cheetah User Guide
Velocity--a Java alternative
FreeMarker--another Java alternative
Bugzilla's home
Return to the Python DevCenter. |
Here's the very dumb way:
def divisorGenerator(n):
for i in xrange(1,n/2+1):
if n%i == 0: yield i
yield n
The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)
I can find prime factors and their multiplicity fast enough. I've an generator that generates factor in this way:
(factor1, multiplicity1)
(factor2, multiplicity2)
(factor3, multiplicity3)
and so on...
i.e. the output of
for i in factorGenerator(100):
print i
is:
(2, 2)(5, 2)
I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make
for i in divisorGen(100):
print i
output this:
124510202550100
UPDATE: Many thanks to Greg Hewgill and his "smart way" :)Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D
UPDATE 2: Stop saying this is a duplicate of this post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers. |
Using the filemanager Path Finder on mac os x, i wanna retrieve the selected files/folders with python by using py-appscript. py-appscript is a high-level event bridge that allows you to control scriptable Mac OS X applications from Python.
In applescript it would be something like
tell application "Path Finder"
set selection_list to selection -- list of fsItems (fsFiles and fsFolders)
set _path to posix path of first item of selection_list
do shell script "python " & quoted form of _path
end tell
In python it would instead something like
from appscript import *
selectection_list = app('Path Finder').selection.get() # returns reference, not string
So, how can i convert the references in selection_list to python-strings? |
I am deploying my django application on a server, and on last stages I am getting this error:
ExtractionError at /admin/
Can't extract file(s) to egg cache
The following error occurred while trying to extract file(s) to the Python egg
cache:
[Errno 13] Permission denied: '/.python-eggs'
The Python egg cache directory is currently set to:
/.python-eggs
Perhaps your account does not have write access to this directory? You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory.
Request Method: GET
Request URL: http://go-ban.org/admin/
Exception Type: ExtractionError
Exception Value:
Can't extract file(s) to egg cache
The following error occurred while trying to extract file(s) to the Python egg
cache:
[Errno 13] Permission denied: '/.python-eggs'
The Python egg cache directory is currently set to:
/.python-eggs
Perhaps your account does not have write access to this directory? You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory.
Exception Location: /usr/lib/python2.5/site-packages/pkg_resources.py in extraction_error, line 887
Python Executable: /usr/bin/python
Python Version: 2.5.2
Python Path: ['/home/oleg/sites/goban', '/usr/lib/python2.5/site-packages/PIL-1.1.7-py2.5-linux-i686.egg', '/usr/lib/python2.5/site-packages/PyAMF-0.5.1-py2.5-linux-i686.egg', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/PIL', '/var/lib/python-support/python2.5']
Server time: Sun, 6 Dec 2009 14:05:47 +0200
Maybe someone come across similar issue?
The strangest thing here is that I am using another django site on this host with no such error :( |
The sorted() function should sort items alphabetically taking caps into account.
>>> string = "Don't touch that, Zaphod Beeblebox!"
>>> words = string.split()
>>> print( sorted(words) )
['Beeblebox!', "Don't", 'Zaphod', 'that,', 'touch']
But if for some reason sorted() ignored caps, then you could do it manually with a sort of list comprehension if you wanted:
words = sorted([i for i in words if i[0].isupper()]) + sorted([i for i in words if i[0].islower()])
This creates two separate lists, the first with capitalized words and the second without, then sorts both individually and conjoins them to give the same result.
But in the end you should definitely just use sorted(); it's much more efficient and concise.
EDIT: Sorry, I might have miss-interpreted your question; if you want to organize just Caps and not without sorting alphabetically, then this works:
>>> string = "ONE TWO one THREE two three FOUR"
>>> words = string.split()
>>> l = []
>>> print [i for i in [i if i[0].isupper() else l.append(i) for i in words] if i!=None]+l
['ONE', 'TWO', 'THREE', 'FOUR', 'one', 'two', 'three']
I can't find a method that's more efficient then that, so there you go. |
What I would like to figure out how to sum every two rows of an array. EG convert a to b in this example:
a=array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
b=array([[ 4, 6, 8, 10],
[20, 22, 24, 26]])
Current code looks something like this:
b=[]
for num in range(len(a)/2):
b.append(a[num*2]+a[num*2+1])
Surely there must be a faster way. Thank you for your time.
Answer found as:
b=a[::2,:]+a[1::2,:]
Which actually helps me expand on a secondary problem of how to skip the initial two rows.
>>> a=np.arange(24).reshape(6,-1)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]])
>>> b=np.vstack((a[:2],a[2::2,:]+a[3::2,:]))
>>> b
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[20, 22, 24, 26],
[36, 38, 40, 42]])
Much thanks for the help. |
I'm trying to build my first GAE app with jinja2. After overcoming a dozen small errors, now I'm stuck with this:
Traceback (most recent call last):
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1536, in __call__
rv = self.handle_exception(request, response, e)
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1530, in __call__
rv = self.router.dispatch(request, response)
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1102, in __call__
return handler.dispatch()
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "C:\Users\CG\Documents\udacity\HiMon\main.py", line 31, in get
template = jinja_environment.get_template('index.html')
File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\environment.py", line 719, in get_template
return self._load_template(name, self.make_globals(globals))
File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\environment.py", line 693, in _load_template
template = self.loader.load(self, name, globals)
File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\loaders.py", line 115, in load
source, filename, uptodate = self.get_source(environment, name)
File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\loaders.py", line 180, in get_source
raise TemplateNotFound(template)
TemplateNotFound: index.html
Here my yaml file:
application: himotherversion: 1runtime: python27api_version: 1threadsafe: yeshandlers:- url: /favicon\.ico static_files: favicon.ico upload: favicon\.ico- url: .* script: main.applibraries:- name: webapp2 version: "2.5.1"- name: jinja2 version: "2.6"
Here my code:
import os
import webapp2
import jinja2
jinja_environment = jinja2.Environment(autoescape=True,
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
class MainPage(webapp2.RequestHandler):
def get(self):
template_values = {
'name': 'Serendipo',
'verb': 'extremely happy'
}
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render(template_values))
app = webapp2.WSGIApplication([('/', MainPage)],
debug=True)
Here my .html template:
<!DOCTYPE html>
<html>
<head>
<title>Look Ma, I'm using Jinja!</title>
</head>
<body>
Hi there - I'm {{ name }}, and I {{ verb }} programming!
</body>
</html>
Despite the error message, I have a folder called "templates" and, within it, created the index.html file:
I also have installed jinja2.
Does anyone have any idea of the cause of this error now? |
assuming I running Scala 2.8.0 RC1, the following scala code should print out the content of the file "c:/hello.txt"
for ( line<-Source.fromPath( "c:/hello.txt" ).getLines )
println( line )
However, when I run it, I get the following error
<console>:10: error: missing arguments for method getLines in class Source;
follow this method with `_' if you want to treat it as a partially applied function
Error occured in an application involving default arguments.
val it = Source.fromPath("c:/hello.scala").getLines
From what I understand, Scala should use the default argument "compat.Platform.EOL" for "getLines". I am wondering if I did wrong or is it a bug in scala 2.8
Thanks |
That is okay
By the way, It is going to be a couple of hours before I sleep. The time here is 20:18 PM
'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.'
'God exists because Mathematics is consistent, and the devil exists because we cannot prove it'
'Humanity is still kept intact. It remains within.' -Alokananda
Offline
Early night. I will begin preparing what I know about it.
In mathematics, you don't understand things. You just get used to them.I have the result, but I do not yet know how to get it.All physicists, and a good many quite respectable mathematicians are contemptuous about proof.
Offline
Whats your time now?
'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.'
'God exists because Mathematics is consistent, and the devil exists because we cannot prove it'
'Humanity is still kept intact. It remains within.' -Alokananda
Offline
8:00 am and soon I will be going offline.
In mathematics, you don't understand things. You just get used to them.I have the result, but I do not yet know how to get it.All physicists, and a good many quite respectable mathematicians are contemptuous about proof.
Offline
OK Have a good day
'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.'
'God exists because Mathematics is consistent, and the devil exists because we cannot prove it'
'Humanity is still kept intact. It remains within.' -Alokananda
Offline
Here is the difference in the two methods.
In mathematics, you don't understand things. You just get used to them.I have the result, but I do not yet know how to get it.All physicists, and a good many quite respectable mathematicians are contemptuous about proof.
Offline
Impressive...
'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.'
'God exists because Mathematics is consistent, and the devil exists because we cannot prove it'
'Humanity is still kept intact. It remains within.' -Alokananda
Offline
Are you sure it starts with h/3?
Besides, how is the same thing as drawing curves?
'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.'
'God exists because Mathematics is consistent, and the devil exists because we cannot prove it'
'Humanity is still kept intact. It remains within.' -Alokananda
Offline
Sorry, we were both posting at the same time and I could not edit fast enough.
The basic formula looks like this:
with
h = (b-a)/n
x_i = a + i*h
In mathematics, you don't understand things. You just get used to them.I have the result, but I do not yet know how to get it.All physicists, and a good many quite respectable mathematicians are contemptuous about proof.
Offline
'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.'
'God exists because Mathematics is consistent, and the devil exists because we cannot prove it'
'Humanity is still kept intact. It remains within.' -Alokananda
Offline
It's convergence is much faster than the trapezoidal rule.
In mathematics, you don't understand things. You just get used to them.I have the result, but I do not yet know how to get it.All physicists, and a good many quite respectable mathematicians are contemptuous about proof.
Offline
So, should I program it?
'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.'
'God exists because Mathematics is consistent, and the devil exists because we cannot prove it'
'Humanity is still kept intact. It remains within.' -Alokananda
Offline
If you like, then we will see if our answers compare.
In mathematics, you don't understand things. You just get used to them.I have the result, but I do not yet know how to get it.All physicists, and a good many quite respectable mathematicians are contemptuous about proof.
Offline
def integrate(f, a, b, n):
h = float(b-a)/n
x = lambda i: (a + i*h)
s1 = 0
for j in xrange(1,(n/2)):
s1 += f(x(2*j))
s1 *= 2
s2 = 0
for j in xrange(1,(n/2)+1):
s2 += f(x(2*j - 1))
s2 *= 4
s = h/3*(f(x(0)) + f(x(n)) + s1 + s2)
return s
'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.'
'God exists because Mathematics is consistent, and the devil exists because we cannot prove it'
'Humanity is still kept intact. It remains within.' -Alokananda
Offline
Let's try it on your integral with n =30.
I got .12501848174018723 using an M and a procedural program.
What did you get?
In mathematics, you don't understand things. You just get used to them.I have the result, but I do not yet know how to get it.All physicists, and a good many quite respectable mathematicians are contemptuous about proof.
Offline
I am getting that too.
The sad part is that I did not get the feeling of making the curves. . It was sort of dry...
'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.'
'God exists because Mathematics is consistent, and the devil exists because we cannot prove it'
'Humanity is still kept intact. It remains within.' -Alokananda
Offline
I could make a drawing for you later that might help.
In mathematics, you don't understand things. You just get used to them.I have the result, but I do not yet know how to get it.All physicists, and a good many quite respectable mathematicians are contemptuous about proof.
Offline
That I can do for myself with a lot more colors than you would use xD
Never mind, but the formula at post 109 is not looking like a curve or giving a feeling of it. Sadly, it works...
'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.'
'God exists because Mathematics is consistent, and the devil exists because we cannot prove it'
'Humanity is still kept intact. It remains within.' -Alokananda
Offline
You have a nice program that you can use later on to integrate functions that you will not be able to do by hand and there will ne lots of them.
In mathematics, you don't understand things. You just get used to them.I have the result, but I do not yet know how to get it.All physicists, and a good many quite respectable mathematicians are contemptuous about proof.
Offline
Why will integration problems come to me in the reality?
Could you explain how you got that formula?
'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.'
'God exists because Mathematics is consistent, and the devil exists because we cannot prove it'
'Humanity is still kept intact. It remains within.' -Alokananda
Offline
Integration is the area under a curve. They come up in physics and probability a lot.
I copied it. It is in many books and also on Wikipedia.
In mathematics, you don't understand things. You just get used to them.I have the result, but I do not yet know how to get it.All physicists, and a good many quite respectable mathematicians are contemptuous about proof.
Offline
hahaha
okay
'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.'
'God exists because Mathematics is consistent, and the devil exists because we cannot prove it'
'Humanity is still kept intact. It remains within.' -Alokananda
Offline
I figured you wanted a real formula and not a bobbym creation.
In mathematics, you don't understand things. You just get used to them.I have the result, but I do not yet know how to get it.All physicists, and a good many quite respectable mathematicians are contemptuous about proof.
Offline
Nope. I want something that gives me the geometric feeling of the area. It can be anything, a program or a formula or some philosophy.
'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.'
'God exists because Mathematics is consistent, and the devil exists because we cannot prove it'
'Humanity is still kept intact. It remains within.' -Alokananda
Offline
I looked at two geogebra programs but they were not very impressive.
Here is the best image I have so far.
In mathematics, you don't understand things. You just get used to them.I have the result, but I do not yet know how to get it.All physicists, and a good many quite respectable mathematicians are contemptuous about proof.
Offline |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.