PERLFAQ5
Section: Perl Programmers Reference Guide (1)Updated: 2009-08-15
Index Return to Main Contents
NAME
perlfaq5 - Files and FormatsDESCRIPTION
This section deals with I/O and the ``f'' issues: filehandles, flushing, formats, and footers.How do I flush/unbuffer an output filehandle? Why must I do this?
(contributed by brian d foy)You might like to read Mark Jason Dominus's ``Suffering From Buffering'' at http://perl.plover.com/FAQs/Buffering.html .
Perl normally buffers output so it doesn't make a system call for every bit of output. By saving up output, it makes fewer expensive system calls. For instance, in this little bit of code, you want to print a dot to the screen for every line you process to watch the progress of your program. Instead of seeing a dot for every line, Perl buffers the output and you have a long wait before you see a row of 50 dots all at once:
# long wait, then row of dots all at once while( <> ) { print "."; print "\n" unless ++$count % 50; #... expensive line processing operations }
To get around this, you have to unbuffer the output filehandle, in this case, "STDOUT". You can set the special variable $| to a true value (mnemonic: making your filehandles ``piping hot''):
$|++; # dot shown immediately while( <> ) { print "."; print "\n" unless ++$count % 50; #... expensive line processing operations }
The $| is one of the per-filehandle special variables, so each filehandle has its own copy of its value. If you want to merge standard output and standard error for instance, you have to unbuffer each (although STDERR might be unbuffered by default):
{ my $previous_default = select(STDOUT); # save previous default $|++; # autoflush STDOUT select(STDERR); $|++; # autoflush STDERR, to be sure select($previous_default); # restore previous default } # now should alternate . and + while( 1 ) { sleep 1; print STDOUT "."; print STDERR "+"; print STDOUT "\n" unless ++$count % 25; }
Besides the $| special variable, you can use "binmode" to give your filehandle a ":unix" layer, which is unbuffered:
binmode( STDOUT, ":unix" ); while( 1 ) { sleep 1; print "."; print "\n" unless ++$count % 50; }
For more information on output layers, see the entries for "binmode" and "open" in perlfunc, and the "PerlIO" module documentation.
If you are using "IO::Handle" or one of its subclasses, you can call the "autoflush" method to change the settings of the filehandle:
use IO::Handle; open my( $io_fh ), ">", "output.txt"; $io_fh->autoflush(1);
The "IO::Handle" objects also have a "flush" method. You can flush the buffer any time you want without auto-buffering
$io_fh->flush;
How do I change, delete, or insert a line in a file, or append to the beginning of a file?
(contributed by brian d foy)The basic idea of inserting, changing, or deleting a line from a text file involves reading and printing the file to the point you want to make the change, making the change, then reading and printing the rest of the file. Perl doesn't provide random access to lines (especially since the record input separator, $/, is mutable), although modules such as "Tie::File" can fake it.
A Perl program to do these tasks takes the basic form of opening a file, printing its lines, then closing the file:
open my $in, '<', $file or die "Can't read old file: $!"; open my $out, '>', "$file.new" or die "Can't write new file: $!"; while( <$in> ) { print $out $_; } close $out;
Within that basic form, add the parts that you need to insert, change, or delete lines.
To prepend lines to the beginning, print those lines before you enter the loop that prints the existing lines.
open my $in, '<', $file or die "Can't read old file: $!"; open my $out, '>', "$file.new" or die "Can't write new file: $!"; print $out "# Add this line to the top\n"; # <--- HERE'S THE MAGIC while( <$in> ) { print $out $_; } close $out;
To change existing lines, insert the code to modify the lines inside the "while" loop. In this case, the code finds all lowercased versions of ``perl'' and uppercases them. The happens for every line, so be sure that you're supposed to do that on every line!
open my $in, '<', $file or die "Can't read old file: $!"; open my $out, '>', "$file.new" or die "Can't write new file: $!"; print $out "# Add this line to the top\n"; while( <$in> ) { s/\b(perl)\b/Perl/g; print $out $_; } close $out;
To change only a particular line, the input line number, $., is useful. First read and print the lines up to the one you want to change. Next, read the single line you want to change, change it, and print it. After that, read the rest of the lines and print those:
while( <$in> ) # print the lines before the change { print $out $_; last if $. == 4; # line number before change } my $line = <$in>; $line =~ s/\b(perl)\b/Perl/g; print $out $line; while( <$in> ) # print the rest of the lines { print $out $_; }
To skip lines, use the looping controls. The "next" in this example skips comment lines, and the "last" stops all processing once it encounters either "__END__" or "__DATA__".
while( <$in> ) { next if /^\s+#/; # skip comment lines last if /^__(END|DATA)__$/; # stop at end of code marker print $out $_; }
Do the same sort of thing to delete a particular line by using "next" to skip the lines you don't want to show up in the output. This example skips every fifth line:
while( <$in> ) { next unless $. % 5; print $out $_; }
If, for some odd reason, you really want to see the whole file at once rather than processing line by line, you can slurp it in (as long as you can fit the whole thing in memory!):
open my $in, '<', $file or die "Can't read old file: $!" open my $out, '>', "$file.new" or die "Can't write new file: $!"; my @lines = do { local $/; <$in> }; # slurp! # do your magic here print $out @lines;
Modules such as "File::Slurp" and "Tie::File" can help with that too. If you can, however, avoid reading the entire file at once. Perl won't give that memory back to the operating system until the process finishes.
You can also use Perl one-liners to modify a file in-place. The following changes all 'Fred' to 'Barney' in inFile.txt, overwriting the file with the new contents. With the "-p" switch, Perl wraps a "while" loop around the code you specify with "-e", and "-i" turns on in-place editing. The current line is in $_. With "-p", Perl automatically prints the value of $_ at the end of the loop. See perlrun for more details.
perl -pi -e 's/Fred/Barney/' inFile.txt
To make a backup of "inFile.txt", give "-i" a file extension to add:
perl -pi.bak -e 's/Fred/Barney/' inFile.txt
To change only the fifth line, you can add a test checking $., the input line number, then only perform the operation when the test passes:
perl -pi -e 's/Fred/Barney/ if $. == 5' inFile.txt
To add lines before a certain line, you can add a line (or lines!) before Perl prints $_:
perl -pi -e 'print "Put before third line\n" if $. == 3' inFile.txt
You can even add a line to the beginning of a file, since the current line prints at the end of the loop:
perl -pi -e 'print "Put before first line\n" if $. == 1' inFile.txt
To insert a line after one already in the file, use the "-n" switch. It's just like "-p" except that it doesn't print $_ at the end of the loop, so you have to do that yourself. In this case, print $_ first, then print the line that you want to add.
perl -ni -e 'print; print "Put after fifth line\n" if $. == 5' inFile.txt
To delete lines, only print the ones that you want.
perl -ni -e 'print unless /d/' inFile.txt ... or ... perl -pi -e 'next unless /d/' inFile.txt
How do I count the number of lines in a file?
One fairly efficient way is to count newlines in the file. The following program uses a feature of tr///, as documented in perlop. If your text file doesn't end with a newline, then it's not really a proper text file, so this may report one fewer line than you expect.
$lines = 0; open(FILE, $filename) or die "Can't open `$filename': $!"; while (sysread FILE, $buffer, 4096) { $lines += ($buffer =~ tr/\n//); } close FILE;
This assumes no funny games with newline translations.
How can I use Perl's -i option from within a program?
"-i" sets the value of Perl's $^I variable, which in turn affects the behavior of "<>"; see perlrun for more details. By modifying the appropriate variables directly, you can get the same behavior within a larger program. For example:
# ... { local($^I, @ARGV) = ('.orig', glob("*.c")); while (<>) { if ($. == 1) { print "This line should appear at the top of each file\n"; } s/\b(p)earl\b/${1}erl/i; # Correct typos, preserving case print; close ARGV if eof; # Reset $. } } # $^I and @ARGV return to their old values here
This block modifies all the ".c" files in the current directory, leaving a backup of the original data from each file in a new ".c.orig" file.
How can I copy a file?
(contributed by brian d foy)Use the "File::Copy" module. It comes with Perl and can do a true copy across file systems, and it does its magic in a portable fashion.
use File::Copy; copy( $original, $new_copy ) or die "Copy failed: $!";
If you can't use "File::Copy", you'll have to do the work yourself: open the original file, open the destination file, then print to the destination file as you read the original. You also have to remember to copy the permissions, owner, and group to the new file.
How do I make a temporary file name?
If you don't need to know the name of the file, you can use "open()" with "undef" in place of the file name. In Perl 5.8 or later, the "open()" function creates an anonymous temporary file:
open my $tmp, '+>', undef or die $!;
Otherwise, you can use the File::Temp module.
use File::Temp qw/ tempfile tempdir /; $dir = tempdir( CLEANUP => 1 ); ($fh, $filename) = tempfile( DIR => $dir ); # or if you don't need to know the filename $fh = tempfile( DIR => $dir );
The File::Temp has been a standard module since Perl 5.6.1. If you don't have a modern enough Perl installed, use the "new_tmpfile" class method from the IO::File module to get a filehandle opened for reading and writing. Use it if you don't need to know the file's name:
use IO::File; $fh = IO::File->new_tmpfile() or die "Unable to make new temporary file: $!";
If you're committed to creating a temporary file by hand, use the process ID and/or the current time-value. If you need to have many temporary files in one process, use a counter:
BEGIN { use Fcntl; my $temp_dir = -d '/tmp' ? '/tmp' : $ENV{TMPDIR} || $ENV{TEMP}; my $base_name = sprintf "%s/%d-%d-0000", $temp_dir, $$, time; sub temp_file { local *FH; my $count = 0; until( defined(fileno(FH)) || $count++ > 100 ) { $base_name =~ s/-(\d+)$/"-" . (1 + $1)/e; # O_EXCL is required for security reasons. sysopen FH, $base_name, O_WRONLY|O_EXCL|O_CREAT; } if( defined fileno(FH) ) { return (*FH, $base_name); } else { return (); } } }
How can I manipulate fixed-record-length files?
The most efficient way is using pack() and unpack(). This is faster than using substr() when taking many, many strings. It is slower for just a few.Here is a sample chunk of code to break up and put back together again some fixed-format input lines, in this case from the output of a normal, Berkeley-style ps:
# sample input line: # 15158 p5 T 0:00 perl /home/tchrist/scripts/now-what my $PS_T = 'A6 A4 A7 A5 A*'; open my $ps, '-|', 'ps'; print scalar <$ps>; my @fields = qw( pid tt stat time command ); while (<$ps>) { my %process; @process{@fields} = unpack($PS_T, $_); for my $field ( @fields ) { print "$field: <$process{$field}>\n"; } print 'line=', pack($PS_T, @process{@fields} ), "\n"; }
We've used a hash slice in order to easily handle the fields of each row. Storing the keys in an array means it's easy to operate on them as a group or loop over them with for. It also avoids polluting the program with global variables and using symbolic references.
How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles?
As of perl5.6, open() autovivifies file and directory handles as references if you pass it an uninitialized scalar variable. You can then pass these references just like any other scalar, and use them in the place of named handles.
open my $fh, $file_name; open local $fh, $file_name; print $fh "Hello World!\n"; process_file( $fh );
If you like, you can store these filehandles in an array or a hash. If you access them directly, they aren't simple scalars and you need to give "print" a little help by placing the filehandle reference in braces. Perl can only figure it out on its own when the filehandle reference is a simple scalar.
my @fhs = ( $fh1, $fh2, $fh3 ); for( $i = 0; $i <= $#fhs; $i++ ) { print {$fhs[$i]} "just another Perl answer, \n"; }
Before perl5.6, you had to deal with various typeglob idioms which you may see in older code.
open FILE, "> $filename"; process_typeglob( *FILE ); process_reference( \*FILE ); sub process_typeglob { local *FH = shift; print FH "Typeglob!" } sub process_reference { local $fh = shift; print $fh "Reference!" }
If you want to create many anonymous handles, you should check out the Symbol or IO::Handle modules.
How can I use a filehandle indirectly?
An indirect filehandle is using something other than a symbol in a place that a filehandle is expected. Here are ways to get indirect filehandles:
$fh = SOME_FH; # bareword is strict-subs hostile $fh = "SOME_FH"; # strict-refs hostile; same package only $fh = *SOME_FH; # typeglob $fh = \*SOME_FH; # ref to typeglob (bless-able) $fh = *SOME_FH{IO}; # blessed IO::Handle from *SOME_FH typeglob
Or, you can use the "new" method from one of the IO::* modules to create an anonymous filehandle, store that in a scalar variable, and use it as though it were a normal filehandle.
use IO::Handle; # 5.004 or higher $fh = IO::Handle->new();
Then use any of those as you would a normal filehandle. Anywhere that Perl is expecting a filehandle, an indirect filehandle may be used instead. An indirect filehandle is just a scalar variable that contains a filehandle. Functions like "print", "open", "seek", or the "<FH>" diamond operator will accept either a named filehandle or a scalar variable containing one:
($ifh, $ofh, $efh) = (*STDIN, *STDOUT, *STDERR); print $ofh "Type it: "; $got = <$ifh> print $efh "What was that: $got";
If you're passing a filehandle to a function, you can write the function in two ways:
sub accept_fh { my $fh = shift; print $fh "Sending to indirect filehandle\n"; }
Or it can localize a typeglob and use the filehandle directly:
sub accept_fh { local *FH = shift; print FH "Sending to localized filehandle\n"; }
Both styles work with either objects or typeglobs of real filehandles. (They might also work with strings under some circumstances, but this is risky.)
accept_fh(*STDOUT); accept_fh($handle);
In the examples above, we assigned the filehandle to a scalar variable before using it. That is because only simple scalar variables, not expressions or subscripts of hashes or arrays, can be used with built-ins like "print", "printf", or the diamond operator. Using something other than a simple scalar variable as a filehandle is illegal and won't even compile:
@fd = (*STDIN, *STDOUT, *STDERR); print $fd[1] "Type it: "; # WRONG $got = <$fd[0]> # WRONG print $fd[2] "What was that: $got"; # WRONG
With "print" and "printf", you get around this by using a block and an expression where you would place the filehandle:
print { $fd[1] } "funny stuff\n"; printf { $fd[1] } "Pity the poor %x.\n", 3_735_928_559; # Pity the poor deadbeef.
That block is a proper block like any other, so you can put more complicated code there. This sends the message out to one of two places:
$ok = -x "/bin/cat"; print { $ok ? $fd[1] : $fd[2] } "cat stat $ok\n"; print { $fd[ 1+ ($ok || 0) ] } "cat stat $ok\n";
This approach of treating "print" and "printf" like object methods calls doesn't work for the diamond operator. That's because it's a real operator, not just a function with a comma-less argument. Assuming you've been storing typeglobs in your structure as we did above, you can use the built-in function named "readline" to read a record just as "<>" does. Given the initialization shown above for @fd, this would work, but only because readline() requires a typeglob. It doesn't work with objects or strings, which might be a bug we haven't fixed yet.
$got = readline($fd[0]);
Let it be noted that the flakiness of indirect filehandles is not related to whether they're strings, typeglobs, objects, or anything else. It's the syntax of the fundamental operators. Playing the object game doesn't help you at all here.
How can I set up a footer format to be used with write()?
There's no builtin way to do this, but perlform has a couple of techniques to make it possible for the intrepid hacker.How can I write() into a string?
See ``Accessing Formatting Internals'' in perlform for an "swrite()" function.How can I open a filehandle to a string?
(contributed by Peter J. Holzer, hjp-usenet2@hjp.at)Since Perl 5.8.0 a file handle referring to a string can be created by calling open with a reference to that string instead of the filename. This file handle can then be used to read from or write to the string:
open(my $fh, '>', \$string) or die "Could not open string for writing"; print $fh "foo\n"; print $fh "bar\n"; # $string now contains "foo\nbar\n" open(my $fh, '<', \$string) or die "Could not open string for reading"; my $x = <$fh>; # $x now contains "foo\n"
With older versions of Perl, the "IO::String" module provides similar functionality.
How can I output my numbers with commas added?
(contributed by brian d foy and Benjamin Goldberg)You can use Number::Format to separate places in a number. It handles locale information for those of you who want to insert full stops instead (or anything else that they want to use, really).
This subroutine will add commas to your number:
sub commify { local $_ = shift; 1 while s/^([-+]?\d+)(\d{3})/$1,$2/; return $_; }
This regex from Benjamin Goldberg will add commas to numbers:
s/(^[-+]?\d+?(?=(?>(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g;
It is easier to see with comments:
s/( ^[-+]? # beginning of number. \d+? # first digits before first comma (?= # followed by, (but not included in the match) : (?>(?:\d{3})+) # some positive multiple of three digits. (?!\d) # an *exact* multiple, not x * 3 + 1 or whatever. ) | # or: \G\d{3} # after the last group, get three digits (?=\d) # but they have to have more digits after them. )/$1,/xg;
How can I translate tildes (~) in a filename?
Use the <> ("glob()") operator, documented in perlfunc. Versions of Perl older than 5.6 require that you have a shell installed that groks tildes. Later versions of Perl have this feature built in. The "File::KGlob" module (available from CPAN) gives more portable glob functionality.Within Perl, you may use this directly:
$filename =~ s{ ^ ~ # find a leading tilde ( # save this in $1 [^/] # a non-slash character * # repeated 0 or more times (0 means me) ) }{ $1 ? (getpwnam($1))[7] : ( $ENV{HOME} || $ENV{LOGDIR} ) }ex;
How come when I open a file read-write it wipes it out?
Because you're using something like this, which truncates the file and then gives you read-write access:
open(FH, "+> /path/name"); # WRONG (almost always)
Whoops. You should instead use this, which will fail if the file doesn't exist.
open(FH, "+< /path/name"); # open for update
Using ``>'' always clobbers or creates. Using ``<'' never does either. The ``+'' doesn't change this.
Here are examples of many kinds of file opens.

To open file for writing, create new file, file must not exist:
sysopen(FH, $path, O_WRONLY|O_EXCL|O_CREAT) || die $!; sysopen(FH, $path, O_WRONLY|O_EXCL|O_CREAT, 0666) || die $!;

To open file for appending, file must exist:
sysopen(FH, $path, O_WRONLY|O_APPEND) || die $!;

To open file for update, file must not exist:
sysopen(FH, $path, O_RDWR|O_EXCL|O_CREAT) || die $!; sysopen(FH, $path, O_RDWR|O_EXCL|O_CREAT, 0666) || die $!;
To open a file without blocking, creating if necessary:
sysopen(FH, "/foo/somefile", O_WRONLY|O_NDELAY|O_CREAT) or die "can't open /foo/somefile: $!":
Be warned that neither creation nor deletion of files is guaranteed to be an atomic operation over NFS. That is, two processes might both successfully create or unlink the same file! Therefore O_EXCL isn't as exclusive as you might wish.
See also the new perlopentut if you have it (new for 5.6).
Why do I sometimes get an Argument list too long when I use <*>?
The "<>" operator performs a globbing operation (see above). In Perl versions earlier than v5.6.0, the internal glob() operator forks csh(1) to do the actual glob expansion, but csh can't handle more than 127 items and so gives the error message "Argument list too long". People who installed tcsh as csh won't have this problem, but their users may be surprised by it.To get around this, either upgrade to Perl v5.6.0 or later, do the glob yourself with readdir() and patterns, or use a module like File::KGlob, one that doesn't use the shell to do globbing.
Is there a leak/bug in glob()?
Due to the current implementation on some operating systems, when you use the glob() function or its angle-bracket alias in a scalar context, you may cause a memory leak and/or unpredictable behavior. It's best therefore to use glob() only in list context.How can I open a file with a leading > or trailing blanks?
(contributed by Brian McCauley)The special two argument form of Perl's open() function ignores trailing blanks in filenames and infers the mode from certain leading characters (or a trailing ``|''). In older versions of Perl this was the only version of open() and so it is prevalent in old code and books.
Unless you have a particular reason to use the two argument form you should use the three argument form of open() which does not treat any characters in the filename as special.
open FILE, "<", " file "; # filename is " file " open FILE, ">", ">file"; # filename is ">file"
How can I reliably rename a file?
If your operating system supports a proper mv(1) utility or its functional equivalent, this works:
rename($old, $new) or system("mv", $old, $new);
It may be more portable to use the File::Copy module instead. You just copy to the new file to the new name (checking return values), then delete the old one. This isn't really the same semantically as a rename(), which preserves meta-information like permissions, timestamps, inode info, etc.
Newer versions of File::Copy export a move() function.
How can I lock a file?
Perl's builtin flock() function (see perlfunc for details) will call flock(2) if that exists, fcntl(2) if it doesn't (on perl version 5.004 and later), and lockf(3) if neither of the two previous system calls exists. On some systems, it may even use a different form of native locking. Here are some gotchas with Perl's flock():- 1.
- Produces a fatal error if none of the three system calls (or their close equivalent) exists.
- 2.
- lockf(3) does not provide shared locking, and requires that the filehandle be open for writing (or appending, or read/writing).
- 3.
-
Some versions of flock() can't lock files over a network (e.g. on NFS file
systems), so you'd need to force the use of fcntl(2) when you build Perl.
But even this is dubious at best. See the flock entry of perlfunc
and the INSTALL file in the source distribution for information on
building Perl to do this.
Two potentially non-obvious but traditional flock semantics are that it waits indefinitely until the lock is granted, and that its locks are merely advisory. Such discretionary locks are more flexible, but offer fewer guarantees. This means that files locked with flock() may be modified by programs that do not also use flock(). Cars that stop for red lights get on well with each other, but not with cars that don't stop for red lights. See the perlport manpage, your port's specific documentation, or your system-specific local manpages for details. It's best to assume traditional behavior if you're writing portable programs. (If you're not, you should as always feel perfectly free to write for your own system's idiosyncrasies (sometimes called ``features''). Slavish adherence to portability concerns shouldn't get in the way of your getting your job done.)
For more information on file locking, see also ``File Locking'' in perlopentut if you have it (new for 5.6).
Why can't I just open(FH, >file.lock)?
A common bit of code NOT TO USE is this:
sleep(3) while -e "file.lock"; # PLEASE DO NOT USE open(LCK, "> file.lock"); # THIS BROKEN CODE
This is a classic race condition: you take two steps to do something which must be done in one. That's why computer hardware provides an atomic test-and-set instruction. In theory, this ``ought'' to work:
sysopen(FH, "file.lock", O_WRONLY|O_EXCL|O_CREAT) or die "can't open file.lock: $!";
except that lamentably, file creation (and deletion) is not atomic over NFS, so this won't work (at least, not every time) over the net. Various schemes involving link() have been suggested, but these tend to involve busy-wait, which is also less than desirable.
I still don't get locking. I just want to increment the number in the file. How can I do this?
Didn't anyone ever tell you web-page hit counters were useless? They don't count number of hits, they're a waste of time, and they serve only to stroke the writer's vanity.
Here's a much better web-page hit counter:
$hits = int( (time() - 850_000_000) / rand(1_000) );
If the count doesn't impress your friends, then the code might. :-)
All I want to do is append a small amount of text to the end of a file. Do I still have to use locking?
If you are on a system that correctly implements "flock" and you use the example appending code from ``perldoc -f flock'' everything will be OK even if the OS you are on doesn't implement append mode correctly (if such a system exists.) So if you are happy to restrict yourself to OSs that implement "flock" (and that's not really much of a restriction) then that is what you should do.If you know you are only going to use a system that does correctly implement appending (i.e. not Win32) then you can omit the "seek" from the code in the previous answer.
If you know you are only writing code to run on an OS and filesystem that does implement append mode correctly (a local filesystem on a modern Unix for example), and you keep the file in block-buffered mode and you write less than one buffer-full of output between each manual flushing of the buffer then each bufferload is almost guaranteed to be written to the end of the file in one chunk without getting intermingled with anyone else's output. You can also use the "syswrite" function which is simply a wrapper around your system's write(2) system call.
There is still a small theoretical chance that a signal will interrupt the system level "write()" operation before completion. There is also a possibility that some STDIO implementations may call multiple system level "write()"s even if the buffer was empty to start. There may be some systems where this probability is reduced to zero, and this is not a concern when using ":perlio" instead of your system's STDIO.
How do I randomly update a binary file?
If you're just trying to patch a binary, in many cases something as simple as this works:
perl -i -pe 's{window manager}{window mangler}g' /usr/bin/emacs
However, if you have fixed sized records, then you might do something more like this:
$RECSIZE = 220; # size of record, in bytes $recno = 37; # which record to update open(FH, "+<somewhere") || die "can't update somewhere: $!"; seek(FH, $recno * $RECSIZE, 0); read(FH, $record, $RECSIZE) == $RECSIZE || die "can't read record $recno: $!"; # munge the record seek(FH, -$RECSIZE, 1); print FH $record; close FH;
Locking and error checking are left as an exercise for the reader. Don't forget them or you'll be quite sorry.
How do I get a file's timestamp in perl?
If you want to retrieve the time at which the file was last read, written, or had its meta-data (owner, etc) changed, you use the -A, -M, or -C file test operations as documented in perlfunc. These retrieve the age of the file (measured against the start-time of your program) in days as a floating point number. Some platforms may not have all of these times. See perlport for details. To retrieve the ``raw'' time in seconds since the epoch, you would call the stat function, then use localtime(), gmtime(), or POSIX::strftime() to convert this into human-readable form.Here's an example:
$write_secs = (stat($file))[9]; printf "file %s updated at %s\n", $file, scalar localtime($write_secs);
If you prefer something more legible, use the File::stat module (part of the standard distribution in version 5.004 and later):
# error checking left as an exercise for reader. use File::stat; use Time::localtime; $date_string = ctime(stat($file)->mtime); print "file $file updated at $date_string\n";
The POSIX::strftime() approach has the benefit of being, in theory, independent of the current locale. See perllocale for details.
How do I set a file's timestamp in perl?
You use the utime() function documented in ``utime'' in perlfunc. By way of example, here's a little program that copies the read and write times from its first argument to all the rest of them.
if (@ARGV < 2) { die "usage: cptimes timestamp_file other_files ...\n"; } $timestamp = shift; ($atime, $mtime) = (stat($timestamp))[8,9]; utime $atime, $mtime, @ARGV;
Error checking is, as usual, left as an exercise for the reader.
The perldoc for utime also has an example that has the same effect as touch(1) on files that already exist.
Certain file systems have a limited ability to store the times on a file at the expected level of precision. For example, the FAT and HPFS filesystem are unable to create dates on files with a finer granularity than two seconds. This is a limitation of the filesystems, not of utime().
How do I print to more than one file at once?
To connect one filehandle to several output filehandles, you can use the IO::Tee or Tie::FileHandle::Multiplex modules.If you only have to do this once, you can print individually to each filehandle.
for $fh (FH1, FH2, FH3) { print $fh "whatever\n" }
How can I read in an entire file all at once?
You can use the File::Slurp module to do it in one step.
use File::Slurp; $all_of_it = read_file($filename); # entire file in scalar @all_lines = read_file($filename); # one line per element
The customary Perl approach for processing all the lines in a file is to do so one line at a time:
open (INPUT, $file) || die "can't open $file: $!"; while (<INPUT>) { chomp; # do something with $_ } close(INPUT) || die "can't close $file: $!";
This is tremendously more efficient than reading the entire file into memory as an array of lines and then processing it one element at a time, which is often---if not almost always---the wrong approach. Whenever you see someone do this:
@lines = <INPUT>;
you should think long and hard about why you need everything loaded at once. It's just not a scalable solution. You might also find it more fun to use the standard Tie::File module, or the DB_File module's $DB_RECNO bindings, which allow you to tie an array to a file so that accessing an element the array actually accesses the corresponding line in the file.
You can read the entire filehandle contents into a scalar.
{ local(*INPUT, $/); open (INPUT, $file) || die "can't open $file: $!"; $var = <INPUT>; }
That temporarily undefs your record separator, and will automatically close the file at block exit. If the file is already open, just use this:
$var = do { local $/; <INPUT> };
For ordinary files you can also use the read function.
read( INPUT, $var, -s INPUT );
The third argument tests the byte size of the data on the INPUT filehandle and reads that many bytes into the buffer $var.
How can I read in a file by paragraphs?
Use the $/ variable (see perlvar for details). You can either set it to "" to eliminate empty paragraphs ("abc\n\n\n\ndef", for instance, gets treated as two paragraphs and not three), or "\n\n" to accept empty paragraphs.Note that a blank line must have no blanks in it. Thus "fred\n \nstuff\n\n" is one paragraph, but "fred\n\nstuff\n\n" is two.
How can I read a single character from a file? From the keyboard?
You can use the builtin "getc()" function for most filehandles, but it won't (easily) work on a terminal device. For STDIN, either use the Term::ReadKey module from CPAN or use the sample code in ``getc'' in perlfunc.If your system supports the portable operating system programming interface (POSIX), you can use the following code, which you'll note turns off echo processing as well.
#!/usr/bin/perl -w use strict; $| = 1; for (1..4) { my $got; print "gimme: "; $got = getone(); print "--> $got\n"; } exit; BEGIN { use POSIX qw(:termios_h); my ($term, $oterm, $echo, $noecho, $fd_stdin); $fd_stdin = fileno(STDIN); $term = POSIX::Termios->new(); $term->getattr($fd_stdin); $oterm = $term->getlflag(); $echo = ECHO | ECHOK | ICANON; $noecho = $oterm & ~$echo; sub cbreak { $term->setlflag($noecho); $term->setcc(VTIME, 1); $term->setattr($fd_stdin, TCSANOW); } sub cooked { $term->setlflag($oterm); $term->setcc(VTIME, 0); $term->setattr($fd_stdin, TCSANOW); } sub getone { my $key = ''; cbreak(); sysread(STDIN, $key, 1); cooked(); return $key; } } END { cooked() }
The Term::ReadKey module from CPAN may be easier to use. Recent versions include also support for non-portable systems as well.
use Term::ReadKey; open(TTY, "</dev/tty"); print "Gimme a char: "; ReadMode "raw"; $key = ReadKey 0, *TTY; ReadMode "normal"; printf "\nYou said %s, char number %03d\n", $key, ord $key;
How can I tell whether there's a character waiting on a filehandle?
The very first thing you should do is look into getting the Term::ReadKey extension from CPAN. As we mentioned earlier, it now even has limited support for non-portable (read: not open systems, closed, proprietary, not POSIX, not Unix, etc) systems.You should also check out the Frequently Asked Questions list in comp.unix.* for things like this: the answer is essentially the same. It's very system dependent. Here's one solution that works on BSD systems:
sub key_ready { my($rin, $nfd); vec($rin, fileno(STDIN), 1) = 1; return $nfd = select($rin,undef,undef,0); }
If you want to find out how many characters are waiting, there's also the FIONREAD ioctl call to be looked at. The h2ph tool that comes with Perl tries to convert C include files to Perl code, which can be "require"d. FIONREAD ends up defined as a function in the sys/ioctl.ph file:
require 'sys/ioctl.ph'; $size = pack("L", 0); ioctl(FH, FIONREAD(), $size) or die "Couldn't call ioctl: $!\n"; $size = unpack("L", $size);
If h2ph wasn't installed or doesn't work for you, you can grep the include files by hand:
% grep FIONREAD /usr/include/*/* /usr/include/asm/ioctls.h:#define FIONREAD 0x541B
Or write a small C program using the editor of champions:
% cat > fionread.c #include <sys/ioctl.h> main() { printf("%#08x\n", FIONREAD); } ^D % cc -o fionread fionread.c % ./fionread 0x4004667f
And then hard code it, leaving porting as an exercise to your successor.
$FIONREAD = 0x4004667f; # XXX: opsys dependent $size = pack("L", 0); ioctl(FH, $FIONREAD, $size) or die "Couldn't call ioctl: $!\n"; $size = unpack("L", $size);
FIONREAD requires a filehandle connected to a stream, meaning that sockets, pipes, and tty devices work, but not files.
How do I do a tail -f in perl?
First try
seek(GWFILE, 0, 1);
The statement "seek(GWFILE, 0, 1)" doesn't change the current position, but it does clear the end-of-file condition on the handle, so that the next "<GWFILE>" makes Perl try again to read something.
If that doesn't work (it relies on features of your stdio implementation), then you need something more like this:
for (;;) { for ($curpos = tell(GWFILE); <GWFILE>; $curpos = tell(GWFILE)) { # search for some stuff and put it into files } # sleep for a while seek(GWFILE, $curpos, 0); # seek to where we had been }
If this still doesn't work, look into the "clearerr" method from "IO::Handle", which resets the error and end-of-file states on the handle.
There's also a "File::Tail" module from CPAN.
How do I dup() a filehandle in Perl?
If you check ``open'' in perlfunc, you'll see that several of the ways to call open() should do the trick. For example:
open(LOG, ">>/foo/logfile"); open(STDERR, ">&LOG");
Or even with a literal numeric descriptor:
$fd = $ENV{MHCONTEXTFD}; open(MHCONTEXT, "<&=$fd"); # like fdopen(3S)
Note that ``<&STDIN'' makes a copy, but ``<&=STDIN'' make an alias. That means if you close an aliased handle, all aliases become inaccessible. This is not true with a copied one.
Error checking, as always, has been left as an exercise for the reader.
How do I close a file descriptor by number?
If, for some reason, you have a file descriptor instead of a filehandle (perhaps you used "POSIX::open"), you can use the "close()" function from the "POSIX" module:
use POSIX (); POSIX::close( $fd );
This should rarely be necessary, as the Perl "close()" function is to be used for things that Perl opened itself, even if it was a dup of a numeric descriptor as with "MHCONTEXT" above. But if you really have to, you may be able to do this:
require 'sys/syscall.ph'; $rc = syscall(&SYS_close, $fd + 0); # must force numeric die "can't sysclose $fd: $!" unless $rc == -1;
Or, just use the fdopen(3S) feature of "open()":
{ open my( $fh ), "<&=$fd" or die "Cannot reopen fd=$fd: $!"; close $fh; }
Why can't I use C:\temp\foo in DOS paths? Why doesn't `C:\temp\foo.exe` work?
Whoops! You just put a tab and a formfeed into that filename! Remember that within double quoted strings (``like\this''), the backslash is an escape character. The full list of these is in ``Quote and Quote-like Operators'' in perlop. Unsurprisingly, you don't have a file called ``c:(tab)emp(formfeed)oo'' or ``c:(tab)emp(formfeed)oo.exe'' on your legacy DOS filesystem.Either single-quote your strings, or (preferably) use forward slashes. Since all DOS and Windows versions since something like MS-DOS 2.0 or so have treated "/" and "\" the same in a path, you might as well use the one that doesn't clash with Perl---or the POSIX shell, ANSI C and C++, awk, Tcl, Java, or Python, just to mention a few. POSIX paths are more portable, too.
Why doesn't glob(*.*) get all the files?
Because even on non-Unix ports, Perl's glob function follows standard Unix globbing semantics. You'll need "glob("*")" to get all (non-hidden) files. This makes glob() portable even to legacy systems. Your port may include proprietary globbing functions as well. Check its documentation for details.Why does Perl let me delete read-only files? Why does -i clobber protected files? Isn't this a bug in Perl?
This is elaborately and painstakingly described in the file-dir-perms article in the ``Far More Than You Ever Wanted To Know'' collection in http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz .The executive summary: learn how your filesystem works. The permissions on a file say what can happen to the data in that file. The permissions on a directory say what can happen to the list of files in that directory. If you delete a file, you're removing its name from the directory (so the operation depends on the permissions of the directory, not of the file). If you try to write to the file, the permissions of the file govern whether you're allowed to.
How do I select a random line from a file?
Short of loading the file into a database or pre-indexing the lines in the file, there are a couple of things that you can do.Here's a reservoir-sampling algorithm from the Camel Book:
srand; rand($.) < 1 && ($line = $_) while <>;
This has a significant advantage in space over reading the whole file in. You can find a proof of this method in The Art of Computer Programming, Volume 2, Section 3.4.2, by Donald E. Knuth.
You can use the "File::Random" module which provides a function for that algorithm:
use File::Random qw/random_line/; my $line = random_line($filename);
Another way is to use the "Tie::File" module, which treats the entire file as an array. Simply access a random array element.
Why do I get weird spaces when I print an array of lines?
(contributed by brian d foy)If you are seeing spaces between the elements of your array when you print the array, you are probably interpolating the array in double quotes:
my @animals = qw(camel llama alpaca vicuna); print "animals are: @animals\n";
It's the double quotes, not the "print", doing this. Whenever you interpolate an array in a double quote context, Perl joins the elements with spaces (or whatever is in $", which is a space by default):
animals are: camel llama alpaca vicuna
This is different than printing the array without the interpolation:
my @animals = qw(camel llama alpaca vicuna); print "animals are: ", @animals, "\n";
Now the output doesn't have the spaces between the elements because the elements of @animals simply become part of the list to "print":
animals are: camelllamaalpacavicuna
You might notice this when each of the elements of @array end with a newline. You expect to print one element per line, but notice that every line after the first is indented:
this is a line this is another line this is the third line
That extra space comes from the interpolation of the array. If you don't want to put anything between your array elements, don't use the array in double quotes. You can send it to print without them:
print @lines;
How do I traverse a directory tree?
(contributed by brian d foy)The "File::Find" module, which comes with Perl, does all of the hard work to traverse a directory structure. It comes with Perl. You simply call the "find" subroutine with a callback subroutine and the directories you want to traverse:
use File::Find; find( \&wanted, @directories ); sub wanted { # full path in $File::Find::name # just filename in $_ ... do whatever you want to do ... }
The "File::Find::Closures", which you can download from CPAN, provides many ready-to-use subroutines that you can use with "File::Find".
The "File::Finder", which you can download from CPAN, can help you create the callback subroutine using something closer to the syntax of the "find" command-line utility:
use File::Find; use File::Finder; my $deep_dirs = File::Finder->depth->type('d')->ls->exec('rmdir','{}'); find( $deep_dirs->as_options, @places );
The "File::Find::Rule" module, which you can download from CPAN, has a similar interface, but does the traversal for you too:
use File::Find::Rule; my @files = File::Find::Rule->file() ->name( '*.pm' ) ->in( @INC );
How do I delete a directory tree?
(contributed by brian d foy)If you have an empty directory, you can use Perl's built-in "rmdir". If the directory is not empty (so, no files or subdirectories), you either have to empty it yourself (a lot of work) or use a module to help you.
The "File::Path" module, which comes with Perl, has a "rmtree" which can take care of all of the hard work for you:
use File::Path qw(rmtree); rmtree( \@directories, 0, 0 );
The first argument to "rmtree" is either a string representing a directory path or an array reference. The second argument controls progress messages, and the third argument controls the handling of files you don't have permissions to delete. See the "File::Path" module for the details.
How do I copy an entire directory?
(contributed by Shlomi Fish)To do the equivalent of "cp -R" (i.e. copy an entire directory tree recursively) in portable Perl, you'll either need to write something yourself or find a good CPAN module such as File::Copy::Recursive. =head1 REVISION
Revision: $Revision$
Date: $Date$
See perlfaq for source control details and availability.
AUTHOR AND COPYRIGHT
Copyright (c) 1997-2009 Tom Christiansen, Nathan Torkington, and other authors as noted. All rights reserved.This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself.
Irrespective of its distribution, all code examples here are in the public domain. You are permitted and encouraged to use this code and any derivatives thereof in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit to the FAQ would be courteous but is not required.
Index
- NAME
- DESCRIPTION
-
- How do I flush/unbuffer an output filehandle? Why must I do this?
- How do I change, delete, or insert a line in a file, or append to the beginning of a file?
- How do I count the number of lines in a file?
- How can I use Perl's -i option from within a program?
- How can I copy a file?
- How do I make a temporary file name?
- How can I manipulate fixed-record-length files?
- How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles?
- How can I use a filehandle indirectly?
- How can I set up a footer format to be used with write()?
- How can I write() into a string?
- How can I open a filehandle to a string?
- How can I output my numbers with commas added?
- How can I translate tildes (~) in a filename?
- How come when I open a file read-write it wipes it out?
- Why do I sometimes get an Argument list too long when I use <*>?
- Is there a leak/bug in glob()?
- How can I open a file with a leading > or trailing blanks?
- How can I reliably rename a file?
- How can I lock a file?
- Why can't I just open(FH, >file.lock)?
- I still don't get locking. I just want to increment the number in the file. How can I do this?
- All I want to do is append a small amount of text to the end of a file. Do I still have to use locking?
- How do I randomly update a binary file?
- How do I get a file's timestamp in perl?
- How do I set a file's timestamp in perl?
- How do I print to more than one file at once?
- How can I read in an entire file all at once?
- How can I read in a file by paragraphs?
- How can I read a single character from a file? From the keyboard?
- How can I tell whether there's a character waiting on a filehandle?
- How do I do a tail -f in perl?
- How do I dup() a filehandle in Perl?
- How do I close a file descriptor by number?
- Why can't I use C:\temp\foo in DOS paths? Why doesn't `C:\temp\foo.exe` work?
- Why doesn't glob(*.*) get all the files?
- Why does Perl let me delete read-only files? Why does -i clobber protected files? Isn't this a bug in Perl?
- How do I select a random line from a file?
- Why do I get weird spaces when I print an array of lines?
- How do I traverse a directory tree?
- How do I delete a directory tree?
- How do I copy an entire directory?
- AUTHOR AND COPYRIGHT
This document was created by man2html, using the manual pages.
Time: 05:29:08 GMT, December 24, 2015


{% extends 'template-lab-4a.html' %} {% set mainClasses = 'nhsuk-u-padding-top-0' %} {% block pageTitle %} Symptoms - NHS {% endblock %} {% block beforeContent %} {% endblock %} {% block content %}
Blood in urine (pee) is not usually caused by anything serious but you must get it checked out by a GP.
you have blood in your urine and:
Blood in your pee may be bright pink, red or dark brown.
Blood in pee must be checked out because it can be a sign of cancer. This is easier to treat if it's found early.
The GP will ask about your symptoms and may need to examine your bottom (rectum), or vagina if you're a woman.
They might also:
Blood in your pee could come from anywhere in the urinary tract – the bladder, kidneys or urethra (the tube that carries pee out of the body).
If you have other symptoms, this might give you an idea of the cause. Do not self-diagnose – see a GP if you think it's blood in your pee.
| Other symptoms | Possible cause |
|---|---|
| Burning pain when peeing, need to pee often, smelly or cloudy pee, high temperature, pain in sides or lower back | urinary tract infections (UTIs) |
| Bad pain in sides, lower back or groin that comes and goes, unable to lie still, feeling sick | kidney stones |
| Older men (common in over-50s) finding it difficult to pee, needing to pee suddenly and often, waking up to pee in middle of the night | enlarged prostate |
It may not be blood in your pee if:
The British Association of Urological Surgeons (BAUS) has more information about blood in urine (haematuria).
Page last reviewed: 02 August 2019
Next review due: 02 August 2022


BLUEPRINTS
Responsive Multi-Column Form
Previous Blueprint
Next Blueprint
Back to the Codrops Article
Blueprints archive
First Name
Last Name
Email Address
Country
Choose a country
United States
Japan
France
Biography
Phone Number
Affiliations
Occupation
Superhero
Scientist
Inventor
Cat's Name
Favorite Gadget
Type of Talent
Smashing things
Chemical reactions
Making things!
Favorite Drink
Special Power
Super strength
Flying
Invisibility
Mode of Transport
Car
Boat
Hovercraft
Let me hear you ROAR!
Submit!


Bar chart delivery test for Fifty Five March 2017
100 pts
200 pts
300 pts
400 pts
500 pts
600 pts
700 pts
800 pts
900 pts
1000 pts


HOME
About Us
LOG OUT
ADMIN
username
<EMAIL_ADDRESS>CUSTOMER
Change Profile Info
Close Account
523
All Parcels
1387
Delivered Parcels
146
Parcels in Transit
523
Pending Parcels
146
Cancelled Parcels
1387
Total amount spent
Cancel an order
Change destination


The aim of the PMO Portal, will serve as the single-entry point for our account project management office activity and information where our support and delivery teams can operate and collaborate daily including activities, consolidated feeds for real time data.


WITNESS LIST Higher Education Committee February 24, 2003-2:30P Community Colleges On: Garcia, Dr. Rey (Texas Association of Community Colleges) Higher Education Funding On: Francis, Patrick (Legislative Budget Board)


Home
Career
Bio
News Feed
Extras
Walk Like Vin, Talk Like Vin
....A Look at the Career of VIN DIESEL


Allan Asis is a student of Cognitive Science at the University of California, San Diego and part of the human-computer interaction class. He combines computation with crowds, designing systems that enable people to connect and coordinate online.


{% extends "base.html" %} {% block content %}
The ACME Workbench is currently under development. Please report any issues to the github issues page.
workbench


Harmonic Linguistics exists to help you discover which artists rap about similar subjects and explore their music in new and meaningful ways
Find Out MoreThis project is the result of a Data Science immersion program with Galvanize. For my capstone project I decided to analyze the content of hip hop lyrics through the lense of a Data Scientist. I hope you enjoy exploring what I've discovered so far!
Get Started!This is where you'd see their beautiful faces.
This is where you'd find some spotify statistics
This is where you'd see their most popular songs.
This is where you'd see other artists in the same "category".
This is where all the cool stuff will go
Harmonic Linguistics aims to provide engaging products that help people explore and discover the rich genre of Hip Hop. As a way to thank the community that has produced such an amazing culture, eventually I'd like to accept donations which would go directly to supporting African American students in STEM and Creative Arts programs. To learn more about this project or just discuss whoseour Top 5's feel free to reach out to me using the contact information below


Marketing copy that writes itself, powered by GPT-3
Our AI can generate more effective copy than your overworked
copywriter. We use artificial intelligence to do the copywriting
for you. From Facebook Ads to headlines, our AI comes up with text
that converts.
-
Powered by GPT-3 from
OpenAI
-
Generate effective copy
fast
-
Idea Generator and more
Read MoreComing Soon


JXSE is under its own license which cannot be changed. Modifications to it must be under that license. Any new code does not have to be under that license, and to keep things separate, should be committed to the JP2P repository, rather than JXSE. JP2P is under the Apache License, version 2.0.


public
toArray(bool $strict = false): array
Return all the public properties as named array.
__toArray(): array
Return all the public properties as named array when called as an array.


We Provide The Best Food
At The Right Price
Happy Hour
Party Time
Breakfast
Lunch
Dinner
Delicious meals are tasty, appetizing, scrumptious, yummy, luscious, delectable, mouth-watering, fit for a king, delightful, lovely, wonderful, pleasant, enjoyable, appealing, enchanting, charming. You wouldn't call delicious that what is tasteless or unpleasant.
As we welcome summers, let us refresh and replenish our body with some of the best summer beverages in order to beat the heat. We suggest a bunch of summer drinks that you must not miss out on.
Great food! Menu is awesome, their foods are not only great but also have great pricing. I'll highly recommend them.
Great food! Menu is awesome, their foods are not only great but also have great pricing. I'll highly recommend them.
Great food! Menu is awesome, their foods are not only great but also have great pricing. I'll highly recommend them.
Great food! Menu is awesome, their foods are not only great but also have great pricing. I'll highly recommend them.
 As well as welcoming guests, restaurant team members sell, prepare, and serve delicious menu items. They can have a specific position, such as cashier, server, host, bartender, waitress, cook, or line cook.
Get our daily food items delivered to your email


Class: Geom::Point2d
| Relationships | |
| Inherits: | Object |
Overview
The Point2d
class allows you to work with a point in 2D space. Point2d
is a series of values representing x and y coordinates.
The values are specified as [x, y]. For example [1, 1]. To create a point call Geom::Point2d.new
, where the creation method can take a variety of arguments:
Class Method Summary
-
.new ⇒ Geom::Point2d
constructor
The .new method creates a new
Point2d
.
Instance Attribute Summary
-
#x ⇒ Length
rw
The #x method returns the x value of the
Point2d
. -
#x=(x) ⇒ Numeric
rw
The #x= method sets the x value of the
Point2d
. -
#y ⇒ Length
rw
The #y method returns the y value of the
Point2d
. -
#y=(y) ⇒ Numeric
rw
The #y= method sets the y value of the
Point2d
.
Instance Method Summary
- #+(vector) ⇒ Geom::Point2d
-
#-(vector) ⇒ Geom::Point2d
The #- operator is a simple way to subtract from the current x and y values of the
Point2d
. -
#==(point) ⇒ Boolean
The #== method compares two points for equality.
-
#[](index) ⇒ Length
The #[] method returns the value of the
Point2d
at the specified index. -
#[]=(index, value) ⇒ Numeric
The #[]= method sets the x or y value of the
Point2d
based on the specific index of the value. -
#clone ⇒ Geom::Point2d
The #clone method creates another point identical to the
Point2d
being cloned. -
#distance(point) ⇒ Numeric
The #distance method computes the distance from the
Point2d
to anotherPoint2d
. -
#inspect ⇒ String
The #inspect method formats the
Point2d
as a string. - #offset(vector) ⇒ Geom::Point2d
- #offset!(vector) ⇒ Geom::Point2d
-
#set!(point) ⇒ Geom::Point2d
The #set! method sets the values of the
Point2d
. -
#to_a ⇒ Array(Numeric, Numeric)
The #to_a method converts the
Point2d
to an array of 2 numbers. -
#to_s ⇒ String
The #to_s method returns a string representation of the
Point2d
. -
#transform(transform) ⇒ Geom::Point2d
The #transform method applies a transformation to a point, returning a new point.
-
#transform!(transform) ⇒ Geom::Point2d
The #transform! method applies a transformation to a point.
-
#vector_to(point) ⇒ Geom::Vector2d
The #vector_to method returns the vector between points.
Constructor Details
.new ⇒ Point2d
.new(x, y) ⇒ Point2d
.new(point) ⇒ Point2d
Point2d
.new(x, y) ⇒ Point2d
.new(point) ⇒ Point2d
The .new
method creates a new Point2d
.
Instance Attribute Details
#x ⇒ Length (rw)
The #x
method returns the x value of the Point2d
.
#x=(x) ⇒ Numeric (rw)
The #x=
method sets the x value of the Point2d
.
#y ⇒ Length (rw)
The #y
method returns the y value of the Point2d
.
#y=(y) ⇒ Numeric (rw)
The #y=
method sets the y value of the Point2d
.
Instance Method Details
#+(vector) ⇒ Point2d
The #+
operator is a simple way to add to the current x and y values of the Point2d
, or to set the values of the Point2d
by adding a Vector2d
to the Point2d
.
#-(vector) ⇒ Point2d
#-(point) ⇒ Geom::Vector2d
Point2d
#-(point) ⇒ Geom::Vector2d
The #-
operator is a simple way to subtract from the current x and y values of the Point2d
.
#==(point) ⇒ Boolean
The #==
method compares two points for equality. This uses the standard SketchUp tolerance to determine if two points are the same.
#[](index) ⇒ Length
The #[]
method returns the value of the Point2d
at the specified index.
#[]=(index, value) ⇒ Numeric
The #[]=
method sets the x or y value of the Point2d
based on the specific index of the value.
#clone ⇒ Point2d
The #clone
method creates another point identical to the Point2d
being cloned.
#distance(point) ⇒ Numeric
The #distance
method computes the distance from the Point2d
to another Point2d
.
#inspect ⇒ String
The #inspect
method formats the Point2d
as a string.
#offset(vector) ⇒ Point2d
#offset(vector, distance) ⇒ Point2d
Point2d
#offset(vector, distance) ⇒ Point2d
The #offset
method offsets the Point2d
by a Vector2d
and returns a new Point2d
. If distance is provided, it must be non-zero.
#offset!(vector) ⇒ Point2d
#offset!(vector, distance) ⇒ Point2d
Point2d
#offset!(vector, distance) ⇒ Point2d
The #offset!
method offsets the Point2d
by a Vector2d
. The Point2d
itself is modified. The length of the vector must not be zero.
#set!(point) ⇒ Point2d
#set!(x, y) ⇒ Point2d
Point2d
#set!(x, y) ⇒ Point2d
The #set!
method sets the values of the Point2d
.
#to_a ⇒ Array(Numeric, Numeric)
The #to_a
method converts the Point2d
to an array of 2 numbers.
#to_s ⇒ String
The #to_s
method returns a string representation of the Point2d
.
#transform(transform) ⇒ Point2d
The #transform
method applies a transformation to a point, returning a new point. The original point is unchanged by this method.
#transform!(transform) ⇒ Point2d
The #transform!
method applies a transformation to a point. The point itself is modified.
#vector_to(point) ⇒ Geom::Vector2d
The #vector_to
method returns the vector between points.


Awnics Technologies Pvt Ltd.
Our Journey began when three different minds came together to build this unique experience
with one focus. Our driving force has been the need to innovate and to enhance Quality of Solution and User experience.
A map based medical service application that can request, map and monitor the status. An integrated application focused towards the healthcare sector. It will be a single channel for all the medical services that may be needed in case of emergency or regular consultations. Such a connected system will help the service providers to connect with the patients and respond pro-actively based on the level of emergency.


<QUOTE>Django itself doesn't serve static (media) files, such as images, style sheets, or video. It leaves that job to whichever Web server you choose. The reasoning here is that standard Web servers, such as Apache, lighttpd and Cherokee, are much more fine-tuned at serving static files than a Web application framework.</QUOTE>
...which is fine, but which doesn't actually help us when Django is being used to implement potentially hundreds of mini-websites with their own novel forms of authentication and where you don't want management overhead of keeping (documenting?) how to synchronise their authentication needs with [INSERT NAME OF PREFERRED WEBSERVER DU JOUR].
See also: http://code.djangoproject.com/ticket/2131#comment:2
<QUOTE>Django isn't meant to serve static files, so I'm marking this as a wontfix.</QUOTE>
So in the face of those wanting to nanny us into "proper behaviour", regrettably we have to roll our own.
We are allowed to take the performance hit, because the point is to have "one mine per user spattered all over the world" rather than "bazillion mines all at one hosting company which subsequently suffers performance issues".
| Function | cleanpath | Undocumented |
| Function | httpserve_error | Undocumented |
| Function | httpserve_file | Undocumented |
| Function | httpserve_directory | Undocumented |
| Function | httpserve_path | Undocumented |


TConvolver provides functionality for performing discrete convolution within a chain of nested samplers. It will collect samples from its associated nested sampler within the region defined by the Kernel property.
[See Also]


Singaporean boy drowns in pool on board Genting Dream cruise ship
LANGKAWI: A 10-year-old Singaporean boy was found dead in a swimming pool on board the Genting Dream cruise ship while docked in Langkawi on Monday (Nov 18) afternoon.
The victim, Alan Heng Kai Lun, was on vacation with his mother and a friend on the vessel that had just arrived from Singapore, said Langkawi district police chief Mohd Iqbal Ibrahim.
They were scheduled to leave for Phuket, Thailand, on Monday night.
“Padang Matsirat Police Station received an emergency call about 7.30pm regarding a drowning incident involving a child in the swimming pool of the cruise ship. Initial investigation found the victim was believed to have drowned.
“A pool attendant and many other visitors were bathing in the pool but failed to rescue the victim. Police have recorded statements of witnesses and pool attendants to facilitate the investigation,” he said in a statement.
On Tuesday, the Ministry of Foreign Affairs (MFA) told CNA that the Singapore High Commission in Kuala Lumpur is aware of the "unfortunate accident".
"We express our deepest sympathy to the family.
"We are in contact with the family, and will continue to provide the necessary consular assistance," said MFA.
Mohd Iqbal said the victim’s body has been sent to the Sultanah Maliha Langkawi Hospital.
He said the vessel, which was carrying 3,000 passengers, left for Phuket at 10.30pm.
Dream Cruises said in response to queries from CNA that passengers on the three-night cruise on Genting Dream had departed Singapore on Sunday.
"Dream Cruises is saddened to confirm that the boy has passed away," it said.
"Our thoughts and prayers are with the families of the deceased and we offer our sincerest condolences."
Dream Cruises said an on board medical team had provided medical and resuscitation assistance to Alan, including administering cardiopulmonary resuscitation.
"Dream Cruises is cooperating with the relevant authorities on the reported incident and providing all the necessary assistance to the family members in this time of difficulty."
According to Dream Cruises' website, the ship has a waterslide park as well as a main pool deck and a kids water park.


{% extends "boards/view.html" %} {% block page_title %}PHP code assessment of commit {{commit.commit}} of {{repository.name}} for {{board.name}}{% endblock %} {% block content %} {% include "repositories/commits/components/breadcrumbs.html" %}
{{phpmd_message.message}}


A rather common thing for British actors and those of other nationalities to do: decide that they could be better served in their career by going to Los Angeles.
It's the most influential and pervasive film industry in the world. If you want to be not just a national but an international star you pretty much have to spend at least some time there. In addition, you can always come back to the U.K. and use the money from the States for British TV, indies, and theater.
The popularity of British actors is also due to the fact that they are a) cheaper, b) less likely to be doing films (though that's less and less the case) and c) less likely to be barred from gay roles by their agents. And then there's this final selling point for the Hollywood studios, probably the most important: They speak English!
Oddly, Brits and Europeans seem to have an above average chance of playing villains or jerks... See Fake American for when they put on the accent as well.
Examples
Fictional
- On Extras, Andy tells his agent he want to get on "cool shows- American shows". In the Christmas special, Andy's agent tells him he's had an offer for a movie (Andy perks up)... a British movie (Andy wilts).
- In The TV Set Ioan Gruffudd plays Richard McCallister, a TV executive who moves from England to Los Angeles to take a job as second-in-command at a fictional TV network, which is headed by Lenny (Sigourney Weaver). Richard tries to counter-balance Lenny's fervent desire for high ratings by emphasizing the need for quality programming and preserving the writer's wishes. Richard's wife Chloe, played by Lucy Davis, hates Los Angeles and eventually leaves Richard to return to England.
- The dream of the titular (Irish) character from Badly Drawn Roy is to go to Hollywood and try to make it big. He's eventually able to go because of donations from the community and he's shown doing odd jobs at the Walk of Fame. Whether or not he actually becomes famous is left up in the air.
- The premise of Episodes is that of a husband-and-wife team of British television writers finding themselves living this trope, with all its attendant pitfalls.
- In Mostly Harmless, Tricia McMillan moves to New York since British accents being in demand on American television. (Ironically, in both the TV and movie adaptations [but not the original radio show] Tricia's played by an American actress as American.)
- S Club 7 managed to do this in fiction as well as Real Life (see below). Their first set of TV shows and specials were about a struggling band trying to make it in America. The first season Miami 7 was merely a Work Com involving them working at a hotel where they also got to perform, but the second and third seasons show them going to Los Angeles to try and make it.
Successful ones are listed below; in fact, thousands of non-American actors go over each pilot season hoping to make it big, to the point documentaries get made about it.
- Michelle Ryan (Bionic Woman)
- Jaime Murray (formerly of Hustle, she played Lila in Dexter)
- Hugh Laurie
- Writer Terry Nation, though he was more successful in England—he worked on shows in the US, but in the UK he created Blake's 7 and Survivors, and he put Doctor Who on the map.
- A number of British writers have also done this, some (like Brian Clemens and Leigh Vance) more successfully than others (like Dennis Spooner).
- Tim Roth did it so well there's people who forget he's English. Not in The Incredible Hulk, though!
"He trained with the ROYAL MARINES!"
- Christopher Eccleston did it after leaving Doctor Who,
- David Tennant tried with Rex Is Not Your Lawyer, an NBC pilot not ordered to series and succeeded with Gracepoint and Kilgrave in Jessica Jones (2015).
- Matthew Mac Fadyen did it after he left Spooks before giving up and came back to the UK.
- David Oyelowo, also of Spooks, did it and actually succeeded, starring as Martin Luther King Jr. in the critical darling Selma.
- Many Black Britons like Thandie Newton find themselves working in America given the lack of roles for non-white actors, especially on television where the majority of shows are period pieces or about the Royal Family - meaning they feature majority white casts.
- Patrick Stewart
- Two Older Than Television examples: Charlie Chaplin in the silent era and Boris Karloff in the early talkies.
- More or less mandatory in Professional Wrestling, although going to Japan is a common variant.
- Gordon Ramsay, of "Hell's Kitchen"
- Elizabeth Taylor, Roddy McDowall and other British child actors of the World War II era did this, overlapping with Blitz Evacuees. Taylor was born in the U.K. of U.S. parents.
- Peter Sellers divided his time between American and English productions from the 1960s onwards; the English films were generally "smaller" than the American ones.
- Clive Owen
- Cary Grant
- David Niven
- C. Aubrey Smith
- Claude Rains
- Gary Oldman
- Henry Cavill
- Jamie Bell
- Tom Holland
- Tom Hollander
- Gideon Emery, which he was teased for by the announcer at the MCM Expo in London during his Q&A panel.
- Stephen Moyer of True Blood, although his accent is VERY convincing.
- Anthony Hopkins, said he didn't fit in well in the theater world in England and lived in the States for a time in the Seventies, then moved back after his success after The Silence of the Lambs in 1990.
- He has since moved back to the U.S. and become an American citizen.
- The high income tax rates in the Britain forced Michael Caine to leave and move to Hollywood in the late Seventies. He moved back to the UK a decade later.
- Appropriately enough considering the aforementioned Extras example, Ricky Gervais himself has been getting in some American movies, like Night at the Museum and a starring role in Ghost Town. He has made repeated references to this trope in real life, like appearing by satellite when Stephen Merchant won a Bafta to congratulate him — and to casually point out that he himself has won bigger awards, "...American ones."
- A directing example is Christopher Nolan. He was born in London but spends a lot of his time in Chicago.
- Alfred Hitchcock
- Deborah Kerr made five films in her native UK before jumping ship to Hollywood in 1944. She stayed there for twenty years and didn't move back to the UK until she retired from movies.
- Jane Seymour has taken to it so well that she's now an American citizen.
- Tracey Ullman. She also became an American citizen.
- Emily Blunt. She also became an American citizen.
- It hasn't been lost on people that the three biggest American superheroes, for a while, were all played by Brits. The American-British Andrew Garfield is Spiderman, Henry Cavill is Superman, and Christian Bale used to be Batman. Sadly for Daily Mail readers, Israeli actress Gal Gadot thwarted hopes for a full house by being cast as Wonder Woman.
- Musical examples:
- David Bowie, but became disillusioned after only a few years and moved to West Berlin straight after.
- Albert Hammond, who sung of a less-than idealised experience in "It Never Rains in Southern California".
- Tom Jones
- Rod Stewart
- Keith Moon
- Jeff Lynne
- Sex Pistols members John Lydon and Steve Jones.
- S Club 7 with the result that they were pushed more as ballad singers than they had been in their native UK. In America their signature songs were the likes of "Two In A Million" and "Never Had A Dream Come True". In the UK it was the more up-tempo "S Club Party", "Bring It All Back" and "Reach".
- Atomic Kitten tried, their covers of "The Tide Is High," "Eternal Flame" and "Locomotion" getting attached to a few movie soundtracks. It didn't take and they remained in the UK for the rest of their time.
- Fleetwood Mac
- Video gaming example: Jeff Minter lived in Los Angeles for some years.
- Alex Kingston, who played a starring role on ER and guest starred on Private Practice. Confirmed to appear in Arrow with fellow former Doctor Who star John Barrowman (who is a dual national). She now divides her time between the UK and US.
- Inverted by Terry Gilliam. Gilliam is an American who moved to England and became a British citizen.
- The Defenders (2017): The two Brits amongst the four leads (Charlie Cox as Matt Murdock, and Finn Jones as Danny Rand) have now made New York City their home.
- Some major movie franchises like The Lord of the Rings, James Bond and Harry Potter, originate in British literature and have some of the finest British actors around in lead roles. The majority of their funding is American.


--- layout: base --- {% include header.html %}
Published {{ page.date | date_to_string }} by {{ page.author }}


* Sign up for 2.5 hours of volunteer time.
Snack Bar volunteers help by setting up and selling snacks to our 3rd-8th graders before class on Wednesday evenings. There are detailed notes for volunteers and will always be someone present to take the lead in directing volunteer support.
Lobby Greeters will sit at a desk in the Religious School Entrance, or the Main Entrance during Religious School hours. Greeters will welcome families as they enter and direct any questions as appropriate. Greeters will also alert a staff person if any suspicious person enters or if any inappropriate activity occurs.
Those covering the Front Desk will field questions from parents as appropriate and will take notes to deliver to staff on any items that need follow up. A detailed description of questions that may arise will be provided to volunteers.
Pick-Up volunteers will help ensure that students do not walk out into dangerous areas of the parking lot unless accompanied by a parent. This person may also be responsible for gathering students' names from each car and relaying them to the person at the front desk (who will then page students to come out at that time).


- B
- C
- F
- I
- M
- N
- P
- T
| [RW] | commits | |
| [RW] | days | |
| [RW] | ref_cache | |
| [RW] | repo |
Source: show
# File lib/gitlab/graph/json_builder.rb, line 8 def self.max_count @max_count ||= 650 end
Source: show
# File lib/gitlab/graph/json_builder.rb, line 12 def initialize project @project = project @repo = project.repo @ref_cache = {} @commits = collect_commits @days = index_commits end
Source: show
# File lib/gitlab/graph/json_builder.rb, line 21 def to_json(*args) { days: @days.compact.map { |d| [d.day, d.strftime("%b")] }, commits: @commits.map(&:to_graph_hash) }.to_json(*args) end
Source: show
# File lib/gitlab/graph/json_builder.rb, line 148 def base_space(leaves, map) parents = [] leaves.each do |l| parents.concat l.parents.collect.select{|p| map.include? p.id and map[p.id].space.nonzero?} end space = parents.map{|p| map[p.id].space}.max || 0 space += 1 end
Get commits from repository
Source: show
# File lib/gitlab/graph/json_builder.rb, line 32 def collect_commits @commits = Grit::Commit.find_all(repo, nil, {max_count: self.class.max_count}).dup # Decorate with app/models/commit.rb @commits.map! { |commit| ::Commit.new(commit) } # Decorate with lib/gitlab/graph/commit.rb @commits.map! { |commit| Gitlab::Graph::Commit.new(commit) } # add refs to each commit @commits.each { |commit| commit.add_refs(ref_cache, repo) } @commits end
Source: show
# File lib/gitlab/graph/json_builder.rb, line 135 def find_free_space(leaves, map) time_range = leaves.last.time..leaves.first.time reserved = [] for day in time_range reserved += @_reserved[day] end space = base_space(leaves, map) while reserved.include? space do space += 1 end space end
Method is adding time and space on the list of commits. As well as returns date list corelated with time set on commits.
@param [Array<Graph::Commit>] comits to index
@return [Array<TimeDate>] list of commit dates corelated with time on commits
Source: show
# File lib/gitlab/graph/json_builder.rb, line 54 def index_commits days, heads = [], [] map = {} commits.reverse.each_with_index do |c,i| c.time = i days[i] = c.committed_date map[c.id] = c heads += c.refs unless c.refs.nil? end heads.select!{|h| h.is_a? Grit::Head or h.is_a? Grit::Remote} # sort heads so the master is top and current branches are closer heads.sort! do |a,b| if a.name == "master" -1 elsif b.name == "master" 1 else b.commit.committed_date <=> a.commit.committed_date end end @_reserved = {} days.each_index do |i| @_reserved[i] = [] end heads.each do |h| if map.include? h.commit.id then place_chain(map[h.commit.id], map) end end days end
Source: show
# File lib/gitlab/graph/json_builder.rb, line 129 def mark_reserved(time_range, space) for day in time_range @_reserved[day].push(space) end end
Add space mark on commit and its parents
@param [Graph::Commit] the commit object. @param [Hash<String,Graph::Commit>] map of commits
Source: show
# File lib/gitlab/graph/json_builder.rb, line 95 def place_chain(commit, map, parent_time = nil) leaves = take_left_leaves(commit, map) if leaves.empty? return end space = find_free_space(leaves, map) leaves.each{|l| l.space = space} # and mark it as reserved min_time = leaves.last.time parents = leaves.last.parents.collect parents.each do |p| if map.include? p.id parent = map[p.id] if parent.time < min_time min_time = parent.time end end end if parent_time.nil? max_time = leaves.first.time else max_time = parent_time - 1 end mark_reserved(min_time..max_time, space) # Visit branching chains leaves.each do |l| parents = l.parents.collect.select{|p| map.include? p.id and map[p.id].space.zero?} for p in parents place_chain(map[p.id], map, l.time) end end end
Takes most left subtree branch of commits which don’t have space mark yet.
@param [Graph::Commit] the commit object. @param [Hash<String,Graph::Commit>] map of commits
@return [Array<Graph::Commit>] list of branch commits
Source: show
# File lib/gitlab/graph/json_builder.rb, line 165 def take_left_leaves(commit, map) leaves = [] leaves.push(commit) if commit.space.zero? while true return leaves if commit.parents.count.zero? return leaves unless map.include? commit.parents.first.id commit = map[commit.parents.first.id] return leaves unless commit.space.zero? leaves.push(commit) end end


Introduction to Computer Programming
Stage 0: Notes
5 Ways of Thinking Like a Programmer
Procedural Thinking
Abstract Thinking
Sytematic Debugging
Technological Empathy
Systems Thinking
HTML - Hypertext Markup Language
What components make up the the World Wide Web?
HTTP - Protocol for the web
Servers - Computers that have the files that makeup the web
Internet - The world's largest computer network
Browser - A program that runs on your computer to display files found on the web
The Internet uses HTTP to communicate with you, your browser, and servers.
Basic HTML Language
Tag - an HTML tag is always contained with brackets. Most have an opening and closing tag.
Void tags do not require a closing tag
Element - refers to everything within a set of opening and closing tags
Attibute - This is a property of an HTML element.
For example: Udacity.com


Get involved in the exciting sport of cycling! Road, Mountain, Cyclocross, Track, and more!
Find Out MoreFind a team to ride with - whether you're novice or former pro, junior or masters, roadie, dirt rider, or anything in between.
| Team Name | Disciplines | Contact |
|---|---|---|
| First Team | Masters, road and cyclocross, women | Person Person |
| Second Team | Women, Juniors, primarily track, some road, mtb, cross | Another Person |
| Third Team | Highly competitive road cyclists that dabble in other disciplines | Anony Mouse |
Bike racing unites the joy of riding a bike, the thrill of competition and pushing to be your best, the rewards of working together and sharing camaraderie with teammates, and combining fitness with skills and strategy. And there’s so much more. “What’s racing all about” is different for every woman. We have the top-flight women who best the field again and again, while also taking time to help guide and support others. We have back-of-the-packers who know they’ll never achieve glory in the traditional sense, but feel their own glory in getting out there and pushing through, and sharing that experience with women who become some of their closest friends. Some of us love the dirt, delighting in the unique (and often muddy) challenges of a cyclocross or mountain bike course. Some crave the speed and sun of the track. Some love the open road and the feel of the peloton. We share a willingness to work hard, and a strong desire to have fun at the same time. We also work together for the sake of the team -- particularly in road and track races, individual racers might have specific roles to play within a race to help boost those with the likeliest chances of winning. You may also find yourself working with women from other teams for parts of a road or track race -- that is, riding in a rotating paceline to share the burden of the pull and the benefits of the draft so that all have a better chance of advancing in the field. Many women who love their bikes but never thought of themselves as racers find great fulfillment once they’ve explored this world a little more.
Being on a racing team gives you a lot of benefits, and also carries some expectations of you. As a team member, you’re one of a consistent group of cyclists who can train together, usually with similar goals and timelines, and that makes the workouts more efficient and more fun. You can learn a lot from more experienced racers -- everything from bike handling skills to how to pin on race numbers or use rollers. Teams typically have at least one training ride per week during the fall and winter (and sometimes at other times of the year) and everyone needs to participate in many (not all) of those rides, as well as do additional training throughout the week. Teams may have clinics and workshops about topics such as hill climbing, nutrition and recovery and you’d be expected to attend as many of those as possible. Of course, teams are all about racing. You’ll be expected to race a certain number of times each year; the number varies by team. Some teams have racers in all four disciplines (road, mountain, cyclocross, track); others focus on one or two. Many teams engage in community involvement activities, and some sponsor races where you can either race or volunteer and learn more about the sport.
The WSBA sanctions and supports multiple programs aimed at developing new and experienced racers, from beginners to national and international competitors.
Find a team to ride with - whether you're novice or former pro, junior or masters.
| Team Name | Disciplines | Contact |
|---|---|---|
| First Team | Masters, road and cyclocross, women | Person Person |
| Second Team | Women, Juniors, primarily track, some road, mtb, cross | Another Person |
| Third Team | Highly competitive road cyclists that dabble in other disciplines | Anony Mouse |
Learn about some of the amazing competitive cycling events in Washington State! See course maps, photos of past events, and results from previous years.


We think our cat unplugged some cables from our side
Please come back in a few seconds after we clean up.


This came from a ajax call click me to edit
example markup:
<p simpltry_widget="inplace_editor" simpltry_options="ajaxOptions:{method:'get'}, url: 'inplace_editor_save.html'">This came from a ajax call click me to edit</p>


Sorry, but the page you were trying to view could not be displayed because an internal server error has occurred.


We're sorry but good-news doesn't work properly without JavaScript enabled. Please enable it to continue.


Copyright © 2013 W3C® (MIT, ERCIM, Keio, Beihang), All Rights Reserved. W3C liability, trademark and document use rules apply.
This specification defines a JavaScript interface that provides the current time in sub-millisecond resolution and such that it is not subject to system clock skew or adjustments.
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.
This is the First Public Working Draft and Last Call Working Draft for the High Resolution Time Level 2 specification.
Please send comments to<EMAIL_ADDRESS>(archived) with [HighResolutionTime2] at the start of the subject line by 8 January 2014.
This document is produced by the Web Performance Working Group. The Web Performance Working Group is part of the Rich Web Clients Activity in the W3C Interaction Domain.
High Resolution Time Level 2 builds on the first version of High Resolution Time and includes:
performance.now()
in Web Workers.Publication as a First Public and Last Call Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.
This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.
This section is non-normative.
The ECMAScript Language Specification defines the Date object as a time value representing time in milliseconds since 01 January, 1970 UTC. For most purposes, this definition of time is sufficient as these values represent time to millisecond precision for any instant that is within approximately 285,616 years from 01 January, 1970 UTC. The DOMTimeStamp is defined similarly.
In practice, these definitions of time are subject to both clock skew and adjustment of the system clock. The value of time may not always be monotonically increasing and subsequent values may either decrease or remain the same.
var mark_start = Date.now(); doTask(); // Some task if (window.console) window.console.log('Duration of task: ' + (Date.now() - mark_start));
For certain tasks this definition of time may not be sufficient as it does not allow for sub-millisecond resolution and is subject to system clock skew. For example,
This specification does not propose changing the behavior of Date.now()
as it is genuinely useful in determining the current value of the calendar time and has a long history of
usage. The DOMHighResTimeStamp
type and the now
method of the
Performance
interface resolve the issues summarized in this section by providing a monotonically increasing time value in sub-millisecond resolution.
This section is non-normative.
A developer may wish to construct a timeline of their entire application, including workers. With a dedicated
worker, this is easy. All
DOMHighResTimeStamps
recorded in the worker use the same
time origin as the document.
var mark_start = performance.now(); doTaskInWorker(); // Some task var mark_end = performance.now(); postMessage({'task': 'Some worker task', 'start_time': mark_start, 'end_time': mark_end});
var mark_start = performance.now(); doTaskInDocument(); // Some other task var mark_end = performance.now(); var document_entry = {'task': 'Some document task', 'start_time': mark_start, 'end_time': mark_end}; var worker = new Worker('js'); worker.onmessage = function (event) { var worker_entry = event.data; plotTimeline([worker_entry, document_entry]); }
Constructing a timeline with SharedWorkers
is slightly more difficult. The time origin is different,
because a worker may be shared across multiple documents. In that case, a developer must adjust
DOMHighResTimeStamps
before displaying them on
the same timeline. This can be done with the
workerStart attribute.
var mark_start = performance.now(); doTaskInDocument(); // Some other task var mark_end = performance.now(); var document_entry = {'task': 'Some document task', 'start_time': mark_start, 'end_time': mark_end}; var worker = new SharedWorker('js'); worker.port.onmessage = function (event) { var worker_entry = event.data; worker_entry.start_time -= worker.workerStart; worker_entry.end_time -= worker.workerStart; plotTimeline([worker_entry, document_entry]); }
Note that the SharedWorkerGlobalScope doesn't have access to its workers' workerStart values. If needed, the document can send a message to the worker containing its workerStart value.
All diagrams, examples, and notes in this specification are non-normative, as are all sections explicitly marked non-normative. Everything else in this specification is normative.
The key words "MUST", "MUST NOT", "REQUIRED", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this document are to be interpreted as described in RFC 2119. For readability, these words do not appear in all uppercase letters in this specification.
Some conformance requirements are phrased as requirements on attributes, methods or objects. Such requirements are to be interpreted as requirements on user agents.
The IDL fragments in this specification must be interpreted as required for conforming IDL fragments, as described in the Web IDL specification. [Web IDL]
The construction "a Foo
object", where Foo
is actually an interface, is sometimes used instead of
the more accurate "an object implementing the interface Foo
".
The term "JavaScript" is used to refer to ECMA-262, rather than the official term ECMAScript, since the term JavaScript is more widely known.
This section is non-normative.
This specification defines an interface that provides the current time in sub-millisecond resolution and such that it is not subject to system clock skew or adjustments.
The time origin is the time value from which time is measured. The time origin must be equal to the time of the start of navigation of the current document.
The time value of the start of navigation of the document in an attribute of type DOMHighResTimeStamp
is equal to 0.
The same time value described with an attribute of type DOMTimeStamp
is equal to the navigationStart
attribute of the PerformanceTiming
interface [NavigationTiming].
For a dedicated worker, the time origin must be equal to the time of the start of navigation of the document where it was created.
For a shared worker, the time origin must be equal to the time of creation of the shared worker.
DOMHighResTimeStamp
Type
The DOMHighResTimeStamp
type is used to store a time value measured relative from the
time origin or a time value that represents a duration
between two DOMHighResTimeStamps
.
A DOMHighResTimeStamp
SHOULD represent a time in milliseconds accurate to a microsecond.
If the User Agent is unable to provide a time value accurate to a microsecond due to hardware or software constraints, the User Agent
can represent a DOMHighResTimeStamp
as a time in milliseconds accurate to a millisecond.
typedef double DOMHighResTimeStamp;
performance.now()
methodpartial interface Performance { DOMHighResTimeStamp now(); }; interface WorkerPerformance { DOMHighResTimeStamp now(); }; partial interface WorkerGlobalScope { readonly attribute WorkerPerformance performance; };
now
methodThe now
method MUST
return a DOMHighResTimeStamp
representing the time in milliseconds
from the time origin to the occurrence of the call to the now
method.
workerStart
attributepartial interface SharedWorker { readonly attribute DOMHighResTimeStamp workerStart; };
workerStart
attributeThe workerStart
attribute MUST
return a DOMHighResTimeStamp
representing the difference between
the time origin of the
SharedWorkerGlobalScope
associated with the SharedWorker
and the time origin of the current document.
The value returned by workerStart may be negative if a SharedWorkerGlobalScope already existed for the SharedWorker prior to the document's time origin.
The time values returned when calling the now
method MUST be monotonically increasing and not subject to system clock
adjustments or system clock skew. The difference between any two chronologically recorded time values returned from the
now
method MUST never be negative.
Statistical fingerprinting is a privacy concern where a malicious web site may determine whether a user has visited a
third-party web site by measuring the timing of cache hits and misses of resources in the third-party web site.
Though the now
method of the Performance
interface
returns time data to a greater accuracy than before, it does not make this privacy concern significantly worse than it was already.
I would like to sincerely thank Karen Anderson, Nat Duca, Tony Gentilcore, Arvind Jain, and Jason Weber to acknowledge their contributions to this work.


MC Curtis
Home
The Intro EP
Contact
Spotify
MC Curtis
The Intro EP
All Toronto Playlist
SoundCloud
MC Curtis
The Intro EP
All Toronto Playlist


| < Day Day Up > |
8.3 Cluster PartitioningAs noted earlier, Figure 8-1 is a common setup for many web sites. While that architecture provides a good starting point, the time may come when you want to squeeze more performance out of your replication setup. Partitioning is often the next evolutionary step as the system grows. In this section, we'll look at several related partitioning schemes that can be applied to most load-balanced MySQL clusters. 8.3.1 Role-Based PartitioningMany applications using a MySQL backend do so in different roles. Let's consider a large community web site for which users register and then exchange messages and participate in discussions online. From the data storage angle, several features must be implemented for the site to function. For example, the system must store and retrieve records for individual users (their profiles) as well as messages and message-related metadata.  Over the past year, you've accumulated a ton of interesting data, and your users want to search it. So you add full-text indexes to the content and offer some basic search facilities. What you soon realize is that the search queries behave quite a bit differently from most of the other queries you run. They're really a whole new class of queries. Rather than retrieving a very small amount of data in a very specific way (fetching a message based on its ID or looking up a user based on username), search queries are more intensive; they take more CPU time to execute. And the full-text indexes are quite a bit larger than your typical MyISAM indexes. In a situation like this, it may make sense to split up the responsibility for the various classes of queries you're executing. Users often expect a search to take a second or two to execute, but pulling up a post or a user page should always happen instantly. To keep the longer-running search queries from interfering with the "must be fast" queries, you can break the slaves into logical subgroups. They'll all still be fed by the same master (for now), but they will be serving in more narrowly focused roles. Figure 8-2 shows a simple example of this with the top half of the diagram omitted. There need not be two physically different load balancers involved. Instead, think of those as logical boxes rather than physical. Most load-balancing hardware can handle dozens of backend clusters simultaneously. Figure 8-2. Partitioning based on roleWith this separation in place, it's much easier to match the hardware to the task at hand. Queries sent to the user cluster are likely to be I/O bound rather taxing the CPU.  So maybe it makes sense to spend less money on the CPUs and invest a bit more in the disks and memory (for caching). Perhaps RAID 0 is a good choice on these machines. The search cluster, on the other hand, spends far more CPU time looking through the full-text indexes to match search terms and ranking results based on their score. The machines in this group probably need faster (or dual) CPUs and a fair amount of memory. This architecture is versatile enough to handle workload splitting for a variety of applications. Anytime you notice an imbalance among the types of queries, consider whether it might be worthwhile to split your large cluster into a cluster made up of smaller groups based on a division of labor. 8.3.2 Data-Based PartitioningSome high-volume applications have surprisingly little variety in the types of queries they use. Partitioning across roles isn't effective in these cases, so the alternative is to partition the data itself and put a bit of additional logic into the application code. Figure 8-3 illustrates this. Figure 8-3. Partitioning based on dataIn an application that deals with fetching user data from MySQL, a simple partitioning scheme is to use the first character of the username. Those beginning with letters A-M reside in the first partition. The other partition handles the second half of the alphabet. The additional application logic is simply a matter of checking the username before deciding which database connection to use when fetching the data. The choice of splitting based on an alphabetic range is purely arbitrary. You can just as easily use a numeric representation of each username, sending all users with even numbers to one cluster and all odd numbers to the other. Volumes have been written on efficient and uniform hashing functions that can be used to group arbitrarily large volumes of data into a fixed number of buckets. Our goal isn't to recommend a particular method but to suggest that you look at the wealth of existing information and techniques before inventing something of your own. 8.3.3 Filtering and Multicluster PartitioningAssuming that the majority of activity is read-only (that is, on the slaves), the previous partitioning solutions scale well as the demand on a high-volume application increases. But what happens when a bottleneck develops on the master? The obvious solution is to upgrade the master. If it is CPU-bound, add more CPU power. If it's I/O bound, add faster disks and more of them. There's a flaw in that logic, however. If the master is having trouble keeping up with the load, the slaves will be under at least as much stress. Remember that MySQL's replication is query based. The volume of write queries handled by the slaves is usually identical to that handled by the master. If the master can no longer keep up, odds are that the slaves are struggling just as much. <IP_ADDRESS> FilteringAn easy solution to the problem is filtering. As described in Chapter 7, MySQL provides the ability to filter the replication stream selectively on both the master and the slave. The problem is that you can filter based only on database or table names. Filtering is therefore not an option if you use data-based partitioning. MySQL has no facility to filter based on the queries themselves, only the names of the databases and tables involved. Filtering may work well in a role-based partitioning setup in which the various slave clusters don't need full copies of the master's data (for instance, where a search cluster needs two particular tables, and the user cluster needs the other four). If you use role-based partitioning, it's probably worthwhile to set up each cluster to replicate only the tables or databases the cluster needs to do its job. The filtering must be on the slaves themselves, as opposed to the master, so the slaves' IO thread will still copy all the master's write queries. However, the SQL thread will read right past queries the slaves aren't interested in (those that are filtered out). <IP_ADDRESS> Separate clustersAside from Moore's Law, the only real solution to scaling the write side with this model is to use truly separate clusters. By going from a single master with many slaves to several independent masters with their own slaves, you eliminate the bottlenecks associated with a higher volume of write activity, and you can get away with using less expensive hardware. Figure 8-4 illustrates this logical progression. As before, there are two groups of slaves, one for search and one for user lookups, but this time each group is served by its own master. Figure 8-4. Multicluster partitioning |
| < Day Day Up > |


--- layout: post title: no title date: '2017-12-29T11:30:34+01:00' categories: - Storyboards - Sketches picture_url: https://film-Storyboards.tumblr.com/post/169079135553 --- Storyboards layout for TV series, Les Rivières Pourpres (Crimson Rivers)


ABOUT US
The Describers Dairy posts a new episode every week unwrapping all the reasons behind brain teasing realities and concepts.

CREATERS BEHIND SCENES
The Describers Dairy podcast is created and hosted by
Rasi
Yaswanth
Follow us on facebook and instagram to get notified about the upcoming episodes.
We at Describers Dairy, sometimes fall short on ideas, maybe your suggestion can help us spark some ideas.
Feel free to write us your suggestions and requests on our social media accounts.