hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringlengths
1
11
lang
stringlengths
1
21
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
112
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
sequence
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
113
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
sequence
max_issues_count
float64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
113
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
sequence
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
3
1.05M
avg_line_length
float64
1
966k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
ed5e7d04a6e928491afd8ba554400ea2634dfd67
393
pm
Perl
lib/VMOMI/SendSNMPAction.pm
restump/p5-vmomi
e2571d72a1f552ddd0258ad289ec229d8d12a147
[ "Apache-2.0" ]
1
2020-07-22T21:56:34.000Z
2020-07-22T21:56:34.000Z
lib/VMOMI/SendSNMPAction.pm
restump/p5-vmomi
e2571d72a1f552ddd0258ad289ec229d8d12a147
[ "Apache-2.0" ]
null
null
null
lib/VMOMI/SendSNMPAction.pm
restump/p5-vmomi
e2571d72a1f552ddd0258ad289ec229d8d12a147
[ "Apache-2.0" ]
1
2016-07-19T19:56:09.000Z
2016-07-19T19:56:09.000Z
package VMOMI::SendSNMPAction; use parent 'VMOMI::Action'; use strict; use warnings; our @class_ancestors = ( 'Action', 'DynamicData', ); our @class_members = ( ); sub get_class_ancestors { return @class_ancestors; } sub get_class_members { my $class = shift; my @super_members = $class->SUPER::get_class_members(); return (@super_members, @class_members); } 1;
15.72
59
0.679389
edebc71912f783ebd4cc19cc5f39d60443efa774
1,696
t
Perl
t/basics/super_and_override.t
exodist/Moose
fadfec9e315aa33fb22c96982704c8c0d15e84c6
[ "Artistic-1.0" ]
94
2015-01-04T18:17:36.000Z
2021-11-18T04:51:22.000Z
t/basics/super_and_override.t
moose-skaters/moose1
648aa02b38b313ca7697de7175f6ca540df16612
[ "Artistic-1.0" ]
82
2015-01-01T18:57:16.000Z
2021-04-13T17:58:38.000Z
t/basics/super_and_override.t
moose-skaters/moose1
648aa02b38b313ca7697de7175f6ca540df16612
[ "Artistic-1.0" ]
69
2015-01-06T00:59:52.000Z
2022-01-17T16:52:38.000Z
use strict; use warnings; use Test::More; use Test::Fatal; { package Foo; use Moose; sub foo { 'Foo::foo' } sub bar { 'Foo::bar' } sub baz { 'Foo::baz' } package Bar; use Moose; extends 'Foo'; override bar => sub { 'Bar::bar -> ' . super() }; package Baz; use Moose; extends 'Bar'; override bar => sub { 'Baz::bar -> ' . super() }; override baz => sub { 'Baz::baz -> ' . super() }; no Moose; # ensure super() still works after unimport } my $baz = Baz->new(); isa_ok($baz, 'Baz'); isa_ok($baz, 'Bar'); isa_ok($baz, 'Foo'); is($baz->foo(), 'Foo::foo', '... got the right value from &foo'); is($baz->bar(), 'Baz::bar -> Bar::bar -> Foo::bar', '... got the right value from &bar'); is($baz->baz(), 'Baz::baz -> Foo::baz', '... got the right value from &baz'); my $bar = Bar->new(); isa_ok($bar, 'Bar'); isa_ok($bar, 'Foo'); is($bar->foo(), 'Foo::foo', '... got the right value from &foo'); is($bar->bar(), 'Bar::bar -> Foo::bar', '... got the right value from &bar'); is($bar->baz(), 'Foo::baz', '... got the right value from &baz'); my $foo = Foo->new(); isa_ok($foo, 'Foo'); is($foo->foo(), 'Foo::foo', '... got the right value from &foo'); is($foo->bar(), 'Foo::bar', '... got the right value from &bar'); is($foo->baz(), 'Foo::baz', '... got the right value from &baz'); # some error cases { package Bling; use Moose; sub bling { 'Bling::bling' } package Bling::Bling; use Moose; extends 'Bling'; sub bling { 'Bling::bling' } ::isnt( ::exception { override 'bling' => sub {}; }, undef, '... cannot override a method which has a local equivalent' ); } done_testing;
21.2
89
0.547759
edb854190cfe97dabe8252fc342b856d073a81bb
443,080
pm
Perl
tools/scitools/bin/linux64/Perl/CPAN.pm
brucegua/moocos
575c161cfa35e220f10d042e2e5ca18773691695
[ "Apache-2.0" ]
1
2020-01-20T21:26:46.000Z
2020-01-20T21:26:46.000Z
tools/scitools/bin/linux64/Perl/CPAN.pm
brucegua/moocos
575c161cfa35e220f10d042e2e5ca18773691695
[ "Apache-2.0" ]
null
null
null
tools/scitools/bin/linux64/Perl/CPAN.pm
brucegua/moocos
575c161cfa35e220f10d042e2e5ca18773691695
[ "Apache-2.0" ]
null
null
null
# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- use strict; package CPAN; $CPAN::VERSION = '1.9205'; $CPAN::VERSION = eval $CPAN::VERSION if $CPAN::VERSION =~ /_/; use CPAN::HandleConfig; use CPAN::Version; use CPAN::Debug; use CPAN::Queue; use CPAN::Tarzip; use CPAN::DeferedCode; use Carp (); use Config (); use Cwd (); use DirHandle (); use Exporter (); use ExtUtils::MakeMaker qw(prompt); # for some unknown reason, # 5.005_04 does not work without # this use File::Basename (); use File::Copy (); use File::Find; use File::Path (); use File::Spec (); use FileHandle (); use Fcntl qw(:flock); use Safe (); use Sys::Hostname qw(hostname); use Text::ParseWords (); use Text::Wrap (); sub find_perl (); # we need to run chdir all over and we would get at wrong libraries # there BEGIN { if (File::Spec->can("rel2abs")) { for my $inc (@INC) { $inc = File::Spec->rel2abs($inc) unless ref $inc; } } } no lib "."; require Mac::BuildTools if $^O eq 'MacOS'; $ENV{PERL5_CPAN_IS_RUNNING}=$$; $ENV{PERL5_CPANPLUS_IS_RUNNING}=$$; # https://rt.cpan.org/Ticket/Display.html?id=23735 END { $CPAN::End++; &cleanup; } $CPAN::Signal ||= 0; $CPAN::Frontend ||= "CPAN::Shell"; unless (@CPAN::Defaultsites) { @CPAN::Defaultsites = map { CPAN::URL->new(TEXT => $_, FROM => "DEF") } "http://www.perl.org/CPAN/", "ftp://ftp.perl.org/pub/CPAN/"; } # $CPAN::iCwd (i for initial) is going to be initialized during find_perl $CPAN::Perl ||= CPAN::find_perl(); $CPAN::Defaultdocs ||= "http://search.cpan.org/perldoc?"; $CPAN::Defaultrecent ||= "http://search.cpan.org/uploads.rdf"; $CPAN::Defaultrecent ||= "http://cpan.uwinnipeg.ca/htdocs/cpan.xml"; # our globals are getting a mess use vars qw( $AUTOLOAD $Be_Silent $CONFIG_DIRTY $Defaultdocs $Echo_readline $Frontend $GOTOSHELL $HAS_USABLE $Have_warned $MAX_RECURSION $META $RUN_DEGRADED $Signal $SQLite $Suppress_readline $VERSION $autoload_recursion $term @Defaultsites @EXPORT ); $MAX_RECURSION = 32; @CPAN::ISA = qw(CPAN::Debug Exporter); # note that these functions live in CPAN::Shell and get executed via # AUTOLOAD when called directly @EXPORT = qw( autobundle bundle clean cvs_import expand force fforce get install install_tested is_tested make mkmyconfig notest perldoc readme recent recompile report shell smoke test upgrade ); sub soft_chdir_with_alternatives ($); { $autoload_recursion ||= 0; #-> sub CPAN::AUTOLOAD ; sub AUTOLOAD { $autoload_recursion++; my($l) = $AUTOLOAD; $l =~ s/.*:://; if ($CPAN::Signal) { warn "Refusing to autoload '$l' while signal pending"; $autoload_recursion--; return; } if ($autoload_recursion > 1) { my $fullcommand = join " ", map { "'$_'" } $l, @_; warn "Refusing to autoload $fullcommand in recursion\n"; $autoload_recursion--; return; } my(%export); @export{@EXPORT} = ''; CPAN::HandleConfig->load unless $CPAN::Config_loaded++; if (exists $export{$l}) { CPAN::Shell->$l(@_); } else { die(qq{Unknown CPAN command "$AUTOLOAD". }. qq{Type ? for help.\n}); } $autoload_recursion--; } } #-> sub CPAN::shell ; sub shell { my($self) = @_; $Suppress_readline = ! -t STDIN unless defined $Suppress_readline; CPAN::HandleConfig->load unless $CPAN::Config_loaded++; my $oprompt = shift || CPAN::Prompt->new; my $prompt = $oprompt; my $commandline = shift || ""; $CPAN::CurrentCommandId ||= 1; local($^W) = 1; unless ($Suppress_readline) { require Term::ReadLine; if (! $term or $term->ReadLine eq "Term::ReadLine::Stub" ) { $term = Term::ReadLine->new('CPAN Monitor'); } if ($term->ReadLine eq "Term::ReadLine::Gnu") { my $attribs = $term->Attribs; $attribs->{attempted_completion_function} = sub { &CPAN::Complete::gnu_cpl; } } else { $readline::rl_completion_function = $readline::rl_completion_function = 'CPAN::Complete::cpl'; } if (my $histfile = $CPAN::Config->{'histfile'}) {{ unless ($term->can("AddHistory")) { $CPAN::Frontend->mywarn("Terminal does not support AddHistory.\n"); last; } $META->readhist($term,$histfile); }} for ($CPAN::Config->{term_ornaments}) { # alias local $Term::ReadLine::termcap_nowarn = 1; $term->ornaments($_) if defined; } # $term->OUT is autoflushed anyway my $odef = select STDERR; $| = 1; select STDOUT; $| = 1; select $odef; } $META->checklock(); my @cwd = grep { defined $_ and length $_ } CPAN::anycwd(), File::Spec->can("tmpdir") ? File::Spec->tmpdir() : (), File::Spec->rootdir(); my $try_detect_readline; $try_detect_readline = $term->ReadLine eq "Term::ReadLine::Stub" if $term; unless ($CPAN::Config->{inhibit_startup_message}) { my $rl_avail = $Suppress_readline ? "suppressed" : ($term->ReadLine ne "Term::ReadLine::Stub") ? "enabled" : "available (maybe install Bundle::CPAN or Bundle::CPANxxl?)"; $CPAN::Frontend->myprint( sprintf qq{ cpan shell -- CPAN exploration and modules installation (v%s) ReadLine support %s }, $CPAN::VERSION, $rl_avail ) } my($continuation) = ""; my $last_term_ornaments; SHELLCOMMAND: while () { if ($Suppress_readline) { if ($Echo_readline) { $|=1; } print $prompt; last SHELLCOMMAND unless defined ($_ = <> ); if ($Echo_readline) { # backdoor: I could not find a way to record sessions print $_; } chomp; } else { last SHELLCOMMAND unless defined ($_ = $term->readline($prompt, $commandline)); } $_ = "$continuation$_" if $continuation; s/^\s+//; next SHELLCOMMAND if /^$/; s/^\s*\?\s*/help /; if (/^(?:q(?:uit)?|bye|exit)$/i) { last SHELLCOMMAND; } elsif (s/\\$//s) { chomp; $continuation = $_; $prompt = " > "; } elsif (/^\!/) { s/^\!//; my($eval) = $_; package CPAN::Eval; use strict; use vars qw($import_done); CPAN->import(':DEFAULT') unless $import_done++; CPAN->debug("eval[$eval]") if $CPAN::DEBUG; eval($eval); warn $@ if $@; $continuation = ""; $prompt = $oprompt; } elsif (/./) { my(@line); eval { @line = Text::ParseWords::shellwords($_) }; warn($@), next SHELLCOMMAND if $@; warn("Text::Parsewords could not parse the line [$_]"), next SHELLCOMMAND unless @line; $CPAN::META->debug("line[".join("|",@line)."]") if $CPAN::DEBUG; my $command = shift @line; eval { CPAN::Shell->$command(@line) }; if ($@) { my $err = "$@"; if ($err =~ /\S/) { require Carp; require Dumpvalue; my $dv = Dumpvalue->new(); Carp::cluck(sprintf "Catching error: %s", $dv->stringify($err)); } } if ($command =~ /^( # classic commands make |test |install |clean # pragmas for classic commands |ff?orce |notest # compounds |report |smoke |upgrade )$/x) { # only commands that tell us something about failed distros CPAN::Shell->failed($CPAN::CurrentCommandId,1); } soft_chdir_with_alternatives(\@cwd); $CPAN::Frontend->myprint("\n"); $continuation = ""; $CPAN::CurrentCommandId++; $prompt = $oprompt; } } continue { $commandline = ""; # I do want to be able to pass a default to # shell, but on the second command I see no # use in that $Signal=0; CPAN::Queue->nullify_queue; if ($try_detect_readline) { if ($CPAN::META->has_inst("Term::ReadLine::Gnu") || $CPAN::META->has_inst("Term::ReadLine::Perl") ) { delete $INC{"Term/ReadLine.pm"}; my $redef = 0; local($SIG{__WARN__}) = CPAN::Shell::paintdots_onreload(\$redef); require Term::ReadLine; $CPAN::Frontend->myprint("\n$redef subroutines in ". "Term::ReadLine redefined\n"); $GOTOSHELL = 1; } } if ($term and $term->can("ornaments")) { for ($CPAN::Config->{term_ornaments}) { # alias if (defined $_) { if (not defined $last_term_ornaments or $_ != $last_term_ornaments ) { local $Term::ReadLine::termcap_nowarn = 1; $term->ornaments($_); $last_term_ornaments = $_; } } else { undef $last_term_ornaments; } } } for my $class (qw(Module Distribution)) { # again unsafe meta access? for my $dm (keys %{$CPAN::META->{readwrite}{"CPAN::$class"}}) { next unless $CPAN::META->{readwrite}{"CPAN::$class"}{$dm}{incommandcolor}; CPAN->debug("BUG: $class '$dm' was in command state, resetting"); delete $CPAN::META->{readwrite}{"CPAN::$class"}{$dm}{incommandcolor}; } } if ($GOTOSHELL) { $GOTOSHELL = 0; # not too often $META->savehist if $CPAN::term && $CPAN::term->can("GetHistory"); @_ = ($oprompt,""); goto &shell; } } soft_chdir_with_alternatives(\@cwd); } #-> CPAN::soft_chdir_with_alternatives ; sub soft_chdir_with_alternatives ($) { my($cwd) = @_; unless (@$cwd) { my $root = File::Spec->rootdir(); $CPAN::Frontend->mywarn(qq{Warning: no good directory to chdir to! Trying '$root' as temporary haven. }); push @$cwd, $root; } while () { if (chdir $cwd->[0]) { return; } else { if (@$cwd>1) { $CPAN::Frontend->mywarn(qq{Could not chdir to "$cwd->[0]": $! Trying to chdir to "$cwd->[1]" instead. }); shift @$cwd; } else { $CPAN::Frontend->mydie(qq{Could not chdir to "$cwd->[0]": $!}); } } } } sub _flock { my($fh,$mode) = @_; if ($Config::Config{d_flock}) { return flock $fh, $mode; } elsif (!$Have_warned->{"d_flock"}++) { $CPAN::Frontend->mywarn("Your OS does not support locking; continuing and ignoring all locking issues\n"); $CPAN::Frontend->mysleep(5); return 1; } else { return 1; } } sub _yaml_module () { my $yaml_module = $CPAN::Config->{yaml_module} || "YAML"; if ( $yaml_module ne "YAML" && !$CPAN::META->has_inst($yaml_module) ) { # $CPAN::Frontend->mywarn("'$yaml_module' not installed, falling back to 'YAML'\n"); $yaml_module = "YAML"; } if ($yaml_module eq "YAML" && $CPAN::META->has_inst($yaml_module) && $YAML::VERSION < 0.60 && !$Have_warned->{"YAML"}++ ) { $CPAN::Frontend->mywarn("Warning: YAML version '$YAML::VERSION' is too low, please upgrade!\n". "I'll continue but problems are *very* likely to happen.\n" ); $CPAN::Frontend->mysleep(5); } return $yaml_module; } # CPAN::_yaml_loadfile sub _yaml_loadfile { my($self,$local_file) = @_; return +[] unless -s $local_file; my $yaml_module = _yaml_module; if ($CPAN::META->has_inst($yaml_module)) { # temporarly enable yaml code deserialisation no strict 'refs'; # 5.6.2 could not do the local() with the reference local $YAML::LoadCode; local $YAML::Syck::LoadCode; ${ "$yaml_module\::LoadCode" } = $CPAN::Config->{yaml_load_code} || 0; my $code; if ($code = UNIVERSAL::can($yaml_module, "LoadFile")) { my @yaml; eval { @yaml = $code->($local_file); }; if ($@) { # this shall not be done by the frontend die CPAN::Exception::yaml_process_error->new($yaml_module,$local_file,"parse",$@); } return \@yaml; } elsif ($code = UNIVERSAL::can($yaml_module, "Load")) { local *FH; open FH, $local_file or die "Could not open '$local_file': $!"; local $/; my $ystream = <FH>; my @yaml; eval { @yaml = $code->($ystream); }; if ($@) { # this shall not be done by the frontend die CPAN::Exception::yaml_process_error->new($yaml_module,$local_file,"parse",$@); } return \@yaml; } } else { # this shall not be done by the frontend die CPAN::Exception::yaml_not_installed->new($yaml_module, $local_file, "parse"); } return +[]; } # CPAN::_yaml_dumpfile sub _yaml_dumpfile { my($self,$local_file,@what) = @_; my $yaml_module = _yaml_module; if ($CPAN::META->has_inst($yaml_module)) { my $code; if (UNIVERSAL::isa($local_file, "FileHandle")) { $code = UNIVERSAL::can($yaml_module, "Dump"); eval { print $local_file $code->(@what) }; } elsif ($code = UNIVERSAL::can($yaml_module, "DumpFile")) { eval { $code->($local_file,@what); }; } elsif ($code = UNIVERSAL::can($yaml_module, "Dump")) { local *FH; open FH, ">$local_file" or die "Could not open '$local_file': $!"; print FH $code->(@what); } if ($@) { die CPAN::Exception::yaml_process_error->new($yaml_module,$local_file,"dump",$@); } } else { if (UNIVERSAL::isa($local_file, "FileHandle")) { # I think this case does not justify a warning at all } else { die CPAN::Exception::yaml_not_installed->new($yaml_module, $local_file, "dump"); } } } sub _init_sqlite () { unless ($CPAN::META->has_inst("CPAN::SQLite")) { $CPAN::Frontend->mywarn(qq{CPAN::SQLite not installed, trying to work without\n}) unless $Have_warned->{"CPAN::SQLite"}++; return; } require CPAN::SQLite::META; # not needed since CVS version of 2006-12-17 $CPAN::SQLite ||= CPAN::SQLite::META->new($CPAN::META); } { my $negative_cache = {}; sub _sqlite_running { if ($negative_cache->{time} && time < $negative_cache->{time} + 60) { # need to cache the result, otherwise too slow return $negative_cache->{fact}; } else { $negative_cache = {}; # reset } my $ret = $CPAN::Config->{use_sqlite} && ($CPAN::SQLite || _init_sqlite()); return $ret if $ret; # fast anyway $negative_cache->{time} = time; return $negative_cache->{fact} = $ret; } } package CPAN::CacheMgr; use strict; @CPAN::CacheMgr::ISA = qw(CPAN::InfoObj CPAN); use File::Find; package CPAN::FTP; use strict; use Fcntl qw(:flock); use vars qw($connect_to_internet_ok $Ua $Thesite $ThesiteURL $Themethod); @CPAN::FTP::ISA = qw(CPAN::Debug); package CPAN::LWP::UserAgent; use strict; use vars qw(@ISA $USER $PASSWD $SETUPDONE); # we delay requiring LWP::UserAgent and setting up inheritance until we need it package CPAN::Complete; use strict; @CPAN::Complete::ISA = qw(CPAN::Debug); # Q: where is the "How do I add a new command" HOWTO? # A: svn diff -r 1048:1049 where andk added the report command @CPAN::Complete::COMMANDS = sort qw( ? ! a b d h i m o q r u autobundle bye clean cvs_import dump exit failed force fforce hosts install install_tested is_tested look ls make mkmyconfig notest perldoc quit readme recent recompile reload report reports scripts smoke test upgrade ); package CPAN::Index; use strict; use vars qw($LAST_TIME $DATE_OF_02 $DATE_OF_03 $HAVE_REANIMATED); @CPAN::Index::ISA = qw(CPAN::Debug); $LAST_TIME ||= 0; $DATE_OF_03 ||= 0; # use constant PROTOCOL => "2.0"; # outcommented to avoid warning on upgrade from 1.57 sub PROTOCOL { 2.0 } package CPAN::InfoObj; use strict; @CPAN::InfoObj::ISA = qw(CPAN::Debug); package CPAN::Author; use strict; @CPAN::Author::ISA = qw(CPAN::InfoObj); package CPAN::Distribution; use strict; @CPAN::Distribution::ISA = qw(CPAN::InfoObj); package CPAN::Bundle; use strict; @CPAN::Bundle::ISA = qw(CPAN::Module); package CPAN::Module; use strict; @CPAN::Module::ISA = qw(CPAN::InfoObj); package CPAN::Exception::RecursiveDependency; use strict; use overload '""' => "as_string"; # a module sees its distribution (no version) # a distribution sees its prereqs (which are module names) (usually with versions) # a bundle sees its module names and/or its distributions (no version) sub new { my($class) = shift; my($deps) = shift; my (@deps,%seen,$loop_starts_with); DCHAIN: for my $dep (@$deps) { push @deps, {name => $dep, display_as => $dep}; if ($seen{$dep}++) { $loop_starts_with = $dep; last DCHAIN; } } my $in_loop = 0; for my $i (0..$#deps) { my $x = $deps[$i]{name}; $in_loop ||= $x eq $loop_starts_with; my $xo = CPAN::Shell->expandany($x) or next; if ($xo->isa("CPAN::Module")) { my $have = $xo->inst_version || "N/A"; my($want,$d,$want_type); if ($i>0 and $d = $deps[$i-1]{name}) { my $do = CPAN::Shell->expandany($d); $want = $do->{prereq_pm}{requires}{$x}; if (defined $want) { $want_type = "requires: "; } else { $want = $do->{prereq_pm}{build_requires}{$x}; if (defined $want) { $want_type = "build_requires: "; } else { $want_type = "unknown status"; $want = "???"; } } } else { $want = $xo->cpan_version; $want_type = "want: "; } $deps[$i]{have} = $have; $deps[$i]{want_type} = $want_type; $deps[$i]{want} = $want; $deps[$i]{display_as} = "$x (have: $have; $want_type$want)"; } elsif ($xo->isa("CPAN::Distribution")) { $deps[$i]{display_as} = $xo->pretty_id; if ($in_loop) { $xo->{make} = CPAN::Distrostatus->new("NO cannot resolve circular dependency"); } else { $xo->{make} = CPAN::Distrostatus->new("NO one dependency ($loop_starts_with) is a circular dependency"); } $xo->store_persistent_state; # otherwise I will not reach # all involved parties for # the next session } } bless { deps => \@deps }, $class; } sub as_string { my($self) = shift; my $ret = "\nRecursive dependency detected:\n "; $ret .= join("\n => ", map {$_->{display_as}} @{$self->{deps}}); $ret .= ".\nCannot resolve.\n"; $ret; } package CPAN::Exception::yaml_not_installed; use strict; use overload '""' => "as_string"; sub new { my($class,$module,$file,$during) = @_; bless { module => $module, file => $file, during => $during }, $class; } sub as_string { my($self) = shift; "'$self->{module}' not installed, cannot $self->{during} '$self->{file}'\n"; } package CPAN::Exception::yaml_process_error; use strict; use overload '""' => "as_string"; sub new { my($class,$module,$file,$during,$error) = @_; bless { module => $module, file => $file, during => $during, error => $error }, $class; } sub as_string { my($self) = shift; if ($self->{during}) { if ($self->{file}) { if ($self->{module}) { if ($self->{error}) { return "Alert: While trying to '$self->{during}' YAML file\n". " '$self->{file}'\n". "with '$self->{module}' the following error was encountered:\n". " $self->{error}\n"; } else { return "Alert: While trying to '$self->{during}' YAML file\n". " '$self->{file}'\n". "with '$self->{module}' some unknown error was encountered\n"; } } else { return "Alert: While trying to '$self->{during}' YAML file\n". " '$self->{file}'\n". "some unknown error was encountered\n"; } } else { return "Alert: While trying to '$self->{during}' some YAML file\n". "some unknown error was encountered\n"; } } else { return "Alert: unknown error encountered\n"; } } package CPAN::Prompt; use overload '""' => "as_string"; use vars qw($prompt); $prompt = "cpan> "; $CPAN::CurrentCommandId ||= 0; sub new { bless {}, shift; } sub as_string { my $word = "cpan"; unless ($CPAN::META->{LOCK}) { $word = "nolock_cpan"; } if ($CPAN::Config->{commandnumber_in_prompt}) { sprintf "$word\[%d]> ", $CPAN::CurrentCommandId; } else { "$word> "; } } package CPAN::URL; use overload '""' => "as_string", fallback => 1; # accessors: TEXT(the url string), FROM(DEF=>defaultlist,USER=>urllist), # planned are things like age or quality sub new { my($class,%args) = @_; bless { %args }, $class; } sub as_string { my($self) = @_; $self->text; } sub text { my($self,$set) = @_; if (defined $set) { $self->{TEXT} = $set; } $self->{TEXT}; } package CPAN::Distrostatus; use overload '""' => "as_string", fallback => 1; sub new { my($class,$arg) = @_; bless { TEXT => $arg, FAILED => substr($arg,0,2) eq "NO", COMMANDID => $CPAN::CurrentCommandId, TIME => time, }, $class; } sub commandid { shift->{COMMANDID} } sub failed { shift->{FAILED} } sub text { my($self,$set) = @_; if (defined $set) { $self->{TEXT} = $set; } $self->{TEXT}; } sub as_string { my($self) = @_; $self->text; } package CPAN::Shell; use strict; use vars qw( $ADVANCED_QUERY $AUTOLOAD $COLOR_REGISTERED $Help $autoload_recursion $reload @ISA ); @CPAN::Shell::ISA = qw(CPAN::Debug); $COLOR_REGISTERED ||= 0; $Help = { '?' => \"help", '!' => "eval the rest of the line as perl", a => "whois author", autobundle => "wtite inventory into a bundle file", b => "info about bundle", bye => \"quit", clean => "clean up a distribution's build directory", # cvs_import d => "info about a distribution", # dump exit => \"quit", failed => "list all failed actions within current session", fforce => "redo a command from scratch", force => "redo a command", h => \"help", help => "overview over commands; 'help ...' explains specific commands", hosts => "statistics about recently used hosts", i => "info about authors/bundles/distributions/modules", install => "install a distribution", install_tested => "install all distributions tested OK", is_tested => "list all distributions tested OK", look => "open a subshell in a distribution's directory", ls => "list distributions according to a glob", m => "info about a module", make => "make/build a distribution", mkmyconfig => "write current config into a CPAN/MyConfig.pm file", notest => "run a (usually install) command but leave out the test phase", o => "'o conf ...' for config stuff; 'o debug ...' for debugging", perldoc => "try to get a manpage for a module", q => \"quit", quit => "leave the cpan shell", r => "review over upgradeable modules", readme => "display the README of a distro woth a pager", recent => "show recent uploads to the CPAN", # recompile reload => "'reload cpan' or 'reload index'", report => "test a distribution and send a test report to cpantesters", reports => "info about reported tests from cpantesters", # scripts # smoke test => "test a distribution", u => "display uninstalled modules", upgrade => "combine 'r' command with immediate installation", }; { $autoload_recursion ||= 0; #-> sub CPAN::Shell::AUTOLOAD ; sub AUTOLOAD { $autoload_recursion++; my($l) = $AUTOLOAD; my $class = shift(@_); # warn "autoload[$l] class[$class]"; $l =~ s/.*:://; if ($CPAN::Signal) { warn "Refusing to autoload '$l' while signal pending"; $autoload_recursion--; return; } if ($autoload_recursion > 1) { my $fullcommand = join " ", map { "'$_'" } $l, @_; warn "Refusing to autoload $fullcommand in recursion\n"; $autoload_recursion--; return; } if ($l =~ /^w/) { # XXX needs to be reconsidered if ($CPAN::META->has_inst('CPAN::WAIT')) { CPAN::WAIT->$l(@_); } else { $CPAN::Frontend->mywarn(qq{ Commands starting with "w" require CPAN::WAIT to be installed. Please consider installing CPAN::WAIT to use the fulltext index. For this you just need to type install CPAN::WAIT }); } } else { $CPAN::Frontend->mywarn(qq{Unknown shell command '$l'. }. qq{Type ? for help. }); } $autoload_recursion--; } } package CPAN; use strict; $META ||= CPAN->new; # In case we re-eval ourselves we need the || # from here on only subs. ################################################################################ sub _perl_fingerprint { my($self,$other_fingerprint) = @_; my $dll = eval {OS2::DLLname()}; my $mtime_dll = 0; if (defined $dll) { $mtime_dll = (-f $dll ? (stat(_))[9] : '-1'); } my $mtime_perl = (-f CPAN::find_perl ? (stat(_))[9] : '-1'); my $this_fingerprint = { '$^X' => CPAN::find_perl, sitearchexp => $Config::Config{sitearchexp}, 'mtime_$^X' => $mtime_perl, 'mtime_dll' => $mtime_dll, }; if ($other_fingerprint) { if (exists $other_fingerprint->{'stat($^X)'}) { # repair fp from rev. 1.88_57 $other_fingerprint->{'mtime_$^X'} = $other_fingerprint->{'stat($^X)'}[9]; } # mandatory keys since 1.88_57 for my $key (qw($^X sitearchexp mtime_dll mtime_$^X)) { return unless $other_fingerprint->{$key} eq $this_fingerprint->{$key}; } return 1; } else { return $this_fingerprint; } } sub suggest_myconfig () { SUGGEST_MYCONFIG: if(!$INC{'CPAN/MyConfig.pm'}) { $CPAN::Frontend->myprint("You don't seem to have a user ". "configuration (MyConfig.pm) yet.\n"); my $new = CPAN::Shell::colorable_makemaker_prompt("Do you want to create a ". "user configuration now? (Y/n)", "yes"); if($new =~ m{^y}i) { CPAN::Shell->mkmyconfig(); return &checklock; } else { $CPAN::Frontend->mydie("OK, giving up."); } } } #-> sub CPAN::all_objects ; sub all_objects { my($mgr,$class) = @_; CPAN::HandleConfig->load unless $CPAN::Config_loaded++; CPAN->debug("mgr[$mgr] class[$class]") if $CPAN::DEBUG; CPAN::Index->reload; values %{ $META->{readwrite}{$class} }; # unsafe meta access, ok } # Called by shell, not in batch mode. In batch mode I see no risk in # having many processes updating something as installations are # continually checked at runtime. In shell mode I suspect it is # unintentional to open more than one shell at a time #-> sub CPAN::checklock ; sub checklock { my($self) = @_; my $lockfile = File::Spec->catfile($CPAN::Config->{cpan_home},".lock"); if (-f $lockfile && -M _ > 0) { my $fh = FileHandle->new($lockfile) or $CPAN::Frontend->mydie("Could not open lockfile '$lockfile': $!"); my $otherpid = <$fh>; my $otherhost = <$fh>; $fh->close; if (defined $otherpid && $otherpid) { chomp $otherpid; } if (defined $otherhost && $otherhost) { chomp $otherhost; } my $thishost = hostname(); if (defined $otherhost && defined $thishost && $otherhost ne '' && $thishost ne '' && $otherhost ne $thishost) { $CPAN::Frontend->mydie(sprintf("CPAN.pm panic: Lockfile '$lockfile'\n". "reports other host $otherhost and other ". "process $otherpid.\n". "Cannot proceed.\n")); } elsif ($RUN_DEGRADED) { $CPAN::Frontend->mywarn("Running in degraded mode (experimental)\n"); } elsif (defined $otherpid && $otherpid) { return if $$ == $otherpid; # should never happen $CPAN::Frontend->mywarn( qq{ There seems to be running another CPAN process (pid $otherpid). Contacting... }); if (kill 0, $otherpid) { $CPAN::Frontend->mywarn(qq{Other job is running.\n}); my($ans) = CPAN::Shell::colorable_makemaker_prompt (qq{Shall I try to run in degraded }. qq{mode? (Y/n)},"y"); if ($ans =~ /^y/i) { $CPAN::Frontend->mywarn("Running in degraded mode (experimental). Please report if something unexpected happens\n"); $RUN_DEGRADED = 1; for ($CPAN::Config) { # XXX # $_->{build_dir_reuse} = 0; # 2006-11-17 akoenig Why was that? $_->{commandnumber_in_prompt} = 0; # visibility $_->{histfile} = ""; # who should win otherwise? $_->{cache_metadata} = 0; # better would be a lock? $_->{use_sqlite} = 0; # better would be a write lock! } } else { $CPAN::Frontend->mydie(" You may want to kill the other job and delete the lockfile. On UNIX try: kill $otherpid rm $lockfile "); } } elsif (-w $lockfile) { my($ans) = CPAN::Shell::colorable_makemaker_prompt (qq{Other job not responding. Shall I overwrite }. qq{the lockfile '$lockfile'? (Y/n)},"y"); $CPAN::Frontend->myexit("Ok, bye\n") unless $ans =~ /^y/i; } else { Carp::croak( qq{Lockfile '$lockfile' not writeable by you. }. qq{Cannot proceed.\n}. qq{ On UNIX try:\n}. qq{ rm '$lockfile'\n}. qq{ and then rerun us.\n} ); } } else { $CPAN::Frontend->mydie(sprintf("CPAN.pm panic: Found invalid lockfile ". "'$lockfile', please remove. Cannot proceed.\n")); } } my $dotcpan = $CPAN::Config->{cpan_home}; eval { File::Path::mkpath($dotcpan);}; if ($@) { # A special case at least for Jarkko. my $firsterror = $@; my $seconderror; my $symlinkcpan; if (-l $dotcpan) { $symlinkcpan = readlink $dotcpan; die "readlink $dotcpan failed: $!" unless defined $symlinkcpan; eval { File::Path::mkpath($symlinkcpan); }; if ($@) { $seconderror = $@; } else { $CPAN::Frontend->mywarn(qq{ Working directory $symlinkcpan created. }); } } unless (-d $dotcpan) { my $mess = qq{ Your configuration suggests "$dotcpan" as your CPAN.pm working directory. I could not create this directory due to this error: $firsterror\n}; $mess .= qq{ As "$dotcpan" is a symlink to "$symlinkcpan", I tried to create that, but I failed with this error: $seconderror } if $seconderror; $mess .= qq{ Please make sure the directory exists and is writable. }; $CPAN::Frontend->mywarn($mess); return suggest_myconfig; } } # $@ after eval mkpath $dotcpan if (0) { # to test what happens when a race condition occurs for (reverse 1..10) { print $_, "\n"; sleep 1; } } # locking if (!$RUN_DEGRADED && !$self->{LOCKFH}) { my $fh; unless ($fh = FileHandle->new("+>>$lockfile")) { if ($! =~ /Permission/) { $CPAN::Frontend->mywarn(qq{ Your configuration suggests that CPAN.pm should use a working directory of $CPAN::Config->{cpan_home} Unfortunately we could not create the lock file $lockfile due to permission problems. Please make sure that the configuration variable \$CPAN::Config->{cpan_home} points to a directory where you can write a .lock file. You can set this variable in either a CPAN/MyConfig.pm or a CPAN/Config.pm in your \@INC path; }); return suggest_myconfig; } } my $sleep = 1; while (!CPAN::_flock($fh, LOCK_EX|LOCK_NB)) { if ($sleep>10) { $CPAN::Frontend->mydie("Giving up\n"); } $CPAN::Frontend->mysleep($sleep++); $CPAN::Frontend->mywarn("Could not lock lockfile with flock: $!; retrying\n"); } seek $fh, 0, 0; truncate $fh, 0; $fh->autoflush(1); $fh->print($$, "\n"); $fh->print(hostname(), "\n"); $self->{LOCK} = $lockfile; $self->{LOCKFH} = $fh; } $SIG{TERM} = sub { my $sig = shift; &cleanup; $CPAN::Frontend->mydie("Got SIG$sig, leaving"); }; $SIG{INT} = sub { # no blocks!!! my $sig = shift; &cleanup if $Signal; die "Got yet another signal" if $Signal > 1; $CPAN::Frontend->mydie("Got another SIG$sig") if $Signal; $CPAN::Frontend->mywarn("Caught SIG$sig, trying to continue\n"); $Signal++; }; # From: Larry Wall <larry@wall.org> # Subject: Re: deprecating SIGDIE # To: perl5-porters@perl.org # Date: Thu, 30 Sep 1999 14:58:40 -0700 (PDT) # # The original intent of __DIE__ was only to allow you to substitute one # kind of death for another on an application-wide basis without respect # to whether you were in an eval or not. As a global backstop, it should # not be used any more lightly (or any more heavily :-) than class # UNIVERSAL. Any attempt to build a general exception model on it should # be politely squashed. Any bug that causes every eval {} to have to be # modified should be not so politely squashed. # # Those are my current opinions. It is also my optinion that polite # arguments degenerate to personal arguments far too frequently, and that # when they do, it's because both people wanted it to, or at least didn't # sufficiently want it not to. # # Larry # global backstop to cleanup if we should really die $SIG{__DIE__} = \&cleanup; $self->debug("Signal handler set.") if $CPAN::DEBUG; } #-> sub CPAN::DESTROY ; sub DESTROY { &cleanup; # need an eval? } #-> sub CPAN::anycwd ; sub anycwd () { my $getcwd; $getcwd = $CPAN::Config->{'getcwd'} || 'cwd'; CPAN->$getcwd(); } #-> sub CPAN::cwd ; sub cwd {Cwd::cwd();} #-> sub CPAN::getcwd ; sub getcwd {Cwd::getcwd();} #-> sub CPAN::fastcwd ; sub fastcwd {Cwd::fastcwd();} #-> sub CPAN::backtickcwd ; sub backtickcwd {my $cwd = `cwd`; chomp $cwd; $cwd} #-> sub CPAN::find_perl ; sub find_perl () { my($perl) = File::Spec->file_name_is_absolute($^X) ? $^X : ""; my $pwd = $CPAN::iCwd = CPAN::anycwd(); my $candidate = File::Spec->catfile($pwd,$^X); $perl ||= $candidate if MM->maybe_command($candidate); unless ($perl) { my ($component,$perl_name); DIST_PERLNAME: foreach $perl_name ($^X, 'perl', 'perl5', "perl$]") { PATH_COMPONENT: foreach $component (File::Spec->path(), $Config::Config{'binexp'}) { next unless defined($component) && $component; my($abs) = File::Spec->catfile($component,$perl_name); if (MM->maybe_command($abs)) { $perl = $abs; last DIST_PERLNAME; } } } } return $perl; } #-> sub CPAN::exists ; sub exists { my($mgr,$class,$id) = @_; CPAN::HandleConfig->load unless $CPAN::Config_loaded++; CPAN::Index->reload; ### Carp::croak "exists called without class argument" unless $class; $id ||= ""; $id =~ s/:+/::/g if $class eq "CPAN::Module"; my $exists; if (CPAN::_sqlite_running) { $exists = (exists $META->{readonly}{$class}{$id} or $CPAN::SQLite->set($class, $id)); } else { $exists = exists $META->{readonly}{$class}{$id}; } $exists ||= exists $META->{readwrite}{$class}{$id}; # unsafe meta access, ok } #-> sub CPAN::delete ; sub delete { my($mgr,$class,$id) = @_; delete $META->{readonly}{$class}{$id}; # unsafe meta access, ok delete $META->{readwrite}{$class}{$id}; # unsafe meta access, ok } #-> sub CPAN::has_usable # has_inst is sometimes too optimistic, we should replace it with this # has_usable whenever a case is given sub has_usable { my($self,$mod,$message) = @_; return 1 if $HAS_USABLE->{$mod}; my $has_inst = $self->has_inst($mod,$message); return unless $has_inst; my $usable; $usable = { LWP => [ # we frequently had "Can't locate object # method "new" via package "LWP::UserAgent" at # (eval 69) line 2006 sub {require LWP}, sub {require LWP::UserAgent}, sub {require HTTP::Request}, sub {require URI::URL}, ], 'Net::FTP' => [ sub {require Net::FTP}, sub {require Net::Config}, ], 'File::HomeDir' => [ sub {require File::HomeDir; unless (CPAN::Version->vge(File::HomeDir::->VERSION, 0.52)) { for ("Will not use File::HomeDir, need 0.52\n") { $CPAN::Frontend->mywarn($_); die $_; } } }, ], 'Archive::Tar' => [ sub {require Archive::Tar; unless (CPAN::Version->vge(Archive::Tar::->VERSION, 1.00)) { for ("Will not use Archive::Tar, need 1.00\n") { $CPAN::Frontend->mywarn($_); die $_; } } }, ], 'File::Temp' => [ # XXX we should probably delete from # %INC too so we can load after we # installed a new enough version -- # I'm not sure. sub {require File::Temp; unless (CPAN::Version->vge(File::Temp::->VERSION,0.16)) { for ("Will not use File::Temp, need 0.16\n") { $CPAN::Frontend->mywarn($_); die $_; } } }, ] }; if ($usable->{$mod}) { for my $c (0..$#{$usable->{$mod}}) { my $code = $usable->{$mod}[$c]; my $ret = eval { &$code() }; $ret = "" unless defined $ret; if ($@) { # warn "DEBUG: c[$c]\$\@[$@]ret[$ret]"; return; } } } return $HAS_USABLE->{$mod} = 1; } #-> sub CPAN::has_inst sub has_inst { my($self,$mod,$message) = @_; Carp::croak("CPAN->has_inst() called without an argument") unless defined $mod; my %dont = map { $_ => 1 } keys %{$CPAN::META->{dontload_hash}||{}}, keys %{$CPAN::Config->{dontload_hash}||{}}, @{$CPAN::Config->{dontload_list}||[]}; if (defined $message && $message eq "no" # afair only used by Nox || $dont{$mod} ) { $CPAN::META->{dontload_hash}{$mod}||=1; # unsafe meta access, ok return 0; } my $file = $mod; my $obj; $file =~ s|::|/|g; $file .= ".pm"; if ($INC{$file}) { # checking %INC is wrong, because $INC{LWP} may be true # although $INC{"URI/URL.pm"} may have failed. But as # I really want to say "bla loaded OK", I have to somehow # cache results. ### warn "$file in %INC"; #debug return 1; } elsif (eval { require $file }) { # eval is good: if we haven't yet read the database it's # perfect and if we have installed the module in the meantime, # it tries again. The second require is only a NOOP returning # 1 if we had success, otherwise it's retrying my $mtime = (stat $INC{$file})[9]; # privileged files loaded by has_inst; Note: we use $mtime # as a proxy for a checksum. $CPAN::Shell::reload->{$file} = $mtime; my $v = eval "\$$mod\::VERSION"; $v = $v ? " (v$v)" : ""; CPAN::Shell->optprint("load_module","CPAN: $mod loaded ok$v\n"); if ($mod eq "CPAN::WAIT") { push @CPAN::Shell::ISA, 'CPAN::WAIT'; } return 1; } elsif ($mod eq "Net::FTP") { $CPAN::Frontend->mywarn(qq{ Please, install Net::FTP as soon as possible. CPAN.pm installs it for you if you just type install Bundle::libnet }) unless $Have_warned->{"Net::FTP"}++; $CPAN::Frontend->mysleep(3); } elsif ($mod eq "Digest::SHA") { if ($Have_warned->{"Digest::SHA"}++) { $CPAN::Frontend->mywarn(qq{CPAN: checksum security checks disabled }. qq{because Digest::SHA not installed.\n}); } else { $CPAN::Frontend->mywarn(qq{ CPAN: checksum security checks disabled because Digest::SHA not installed. Please consider installing the Digest::SHA module. }); $CPAN::Frontend->mysleep(2); } } elsif ($mod eq "Module::Signature") { # NOT prefs_lookup, we are not a distro my $check_sigs = $CPAN::Config->{check_sigs}; if (not $check_sigs) { # they do not want us:-( } elsif (not $Have_warned->{"Module::Signature"}++) { # No point in complaining unless the user can # reasonably install and use it. if (eval { require Crypt::OpenPGP; 1 } || ( defined $CPAN::Config->{'gpg'} && $CPAN::Config->{'gpg'} =~ /\S/ ) ) { $CPAN::Frontend->mywarn(qq{ CPAN: Module::Signature security checks disabled because Module::Signature not installed. Please consider installing the Module::Signature module. You may also need to be able to connect over the Internet to the public keyservers like pgp.mit.edu (port 11371). }); $CPAN::Frontend->mysleep(2); } } } else { delete $INC{$file}; # if it inc'd LWP but failed during, say, URI } return 0; } #-> sub CPAN::instance ; sub instance { my($mgr,$class,$id) = @_; CPAN::Index->reload; $id ||= ""; # unsafe meta access, ok? return $META->{readwrite}{$class}{$id} if exists $META->{readwrite}{$class}{$id}; $META->{readwrite}{$class}{$id} ||= $class->new(ID => $id); } #-> sub CPAN::new ; sub new { bless {}, shift; } #-> sub CPAN::cleanup ; sub cleanup { # warn "cleanup called with arg[@_] End[$CPAN::End] Signal[$Signal]"; local $SIG{__DIE__} = ''; my($message) = @_; my $i = 0; my $ineval = 0; my($subroutine); while ((undef,undef,undef,$subroutine) = caller(++$i)) { $ineval = 1, last if $subroutine eq '(eval)'; } return if $ineval && !$CPAN::End; return unless defined $META->{LOCK}; return unless -f $META->{LOCK}; $META->savehist; close $META->{LOCKFH}; unlink $META->{LOCK}; # require Carp; # Carp::cluck("DEBUGGING"); if ( $CPAN::CONFIG_DIRTY ) { $CPAN::Frontend->mywarn("Warning: Configuration not saved.\n"); } $CPAN::Frontend->myprint("Lockfile removed.\n"); } #-> sub CPAN::readhist sub readhist { my($self,$term,$histfile) = @_; my($fh) = FileHandle->new; open $fh, "<$histfile" or last; local $/ = "\n"; while (<$fh>) { chomp; $term->AddHistory($_); } close $fh; } #-> sub CPAN::savehist sub savehist { my($self) = @_; my($histfile,$histsize); unless ($histfile = $CPAN::Config->{'histfile'}) { $CPAN::Frontend->mywarn("No history written (no histfile specified).\n"); return; } $histsize = $CPAN::Config->{'histsize'} || 100; if ($CPAN::term) { unless ($CPAN::term->can("GetHistory")) { $CPAN::Frontend->mywarn("Terminal does not support GetHistory.\n"); return; } } else { return; } my @h = $CPAN::term->GetHistory; splice @h, 0, @h-$histsize if @h>$histsize; my($fh) = FileHandle->new; open $fh, ">$histfile" or $CPAN::Frontend->mydie("Couldn't open >$histfile: $!"); local $\ = local $, = "\n"; print $fh @h; close $fh; } #-> sub CPAN::is_tested sub is_tested { my($self,$what,$when) = @_; unless ($what) { Carp::cluck("DEBUG: empty what"); return; } $self->{is_tested}{$what} = $when; } #-> sub CPAN::is_installed # unsets the is_tested flag: as soon as the thing is installed, it is # not needed in set_perl5lib anymore sub is_installed { my($self,$what) = @_; delete $self->{is_tested}{$what}; } sub _list_sorted_descending_is_tested { my($self) = @_; sort { ($self->{is_tested}{$b}||0) <=> ($self->{is_tested}{$a}||0) } keys %{$self->{is_tested}} } #-> sub CPAN::set_perl5lib sub set_perl5lib { my($self,$for) = @_; unless ($for) { (undef,undef,undef,$for) = caller(1); $for =~ s/.*://; } $self->{is_tested} ||= {}; return unless %{$self->{is_tested}}; my $env = $ENV{PERL5LIB}; $env = $ENV{PERLLIB} unless defined $env; my @env; push @env, $env if defined $env and length $env; #my @dirs = map {("$_/blib/arch", "$_/blib/lib")} keys %{$self->{is_tested}}; #$CPAN::Frontend->myprint("Prepending @dirs to PERL5LIB.\n"); my @dirs = map {("$_/blib/arch", "$_/blib/lib")} $self->_list_sorted_descending_is_tested; if (@dirs < 12) { $CPAN::Frontend->myprint("Prepending @dirs to PERL5LIB for '$for'\n"); } elsif (@dirs < 24) { my @d = map {my $cp = $_; $cp =~ s/^\Q$CPAN::Config->{build_dir}\E/%BUILDDIR%/; $cp } @dirs; $CPAN::Frontend->myprint("Prepending @d to PERL5LIB; ". "%BUILDDIR%=$CPAN::Config->{build_dir} ". "for '$for'\n" ); } else { my $cnt = keys %{$self->{is_tested}}; $CPAN::Frontend->myprint("Prepending blib/arch and blib/lib of ". "$cnt build dirs to PERL5LIB; ". "for '$for'\n" ); } $ENV{PERL5LIB} = join $Config::Config{path_sep}, @dirs, @env; } package CPAN::CacheMgr; use strict; #-> sub CPAN::CacheMgr::as_string ; sub as_string { eval { require Data::Dumper }; if ($@) { return shift->SUPER::as_string; } else { return Data::Dumper::Dumper(shift); } } #-> sub CPAN::CacheMgr::cachesize ; sub cachesize { shift->{DU}; } #-> sub CPAN::CacheMgr::tidyup ; sub tidyup { my($self) = @_; return unless $CPAN::META->{LOCK}; return unless -d $self->{ID}; my @toremove = grep { $self->{SIZE}{$_}==0 } @{$self->{FIFO}}; for my $current (0..$#toremove) { my $toremove = $toremove[$current]; $CPAN::Frontend->myprint(sprintf( "DEL(%d/%d): %s \n", $current+1, scalar @toremove, $toremove, ) ); return if $CPAN::Signal; $self->_clean_cache($toremove); return if $CPAN::Signal; } } #-> sub CPAN::CacheMgr::dir ; sub dir { shift->{ID}; } #-> sub CPAN::CacheMgr::entries ; sub entries { my($self,$dir) = @_; return unless defined $dir; $self->debug("reading dir[$dir]") if $CPAN::DEBUG; $dir ||= $self->{ID}; my($cwd) = CPAN::anycwd(); chdir $dir or Carp::croak("Can't chdir to $dir: $!"); my $dh = DirHandle->new(File::Spec->curdir) or Carp::croak("Couldn't opendir $dir: $!"); my(@entries); for ($dh->read) { next if $_ eq "." || $_ eq ".."; if (-f $_) { push @entries, File::Spec->catfile($dir,$_); } elsif (-d _) { push @entries, File::Spec->catdir($dir,$_); } else { $CPAN::Frontend->mywarn("Warning: weird direntry in $dir: $_\n"); } } chdir $cwd or Carp::croak("Can't chdir to $cwd: $!"); sort { -M $a <=> -M $b} @entries; } #-> sub CPAN::CacheMgr::disk_usage ; sub disk_usage { my($self,$dir,$fast) = @_; return if exists $self->{SIZE}{$dir}; return if $CPAN::Signal; my($Du) = 0; if (-e $dir) { if (-d $dir) { unless (-x $dir) { unless (chmod 0755, $dir) { $CPAN::Frontend->mywarn("I have neither the -x permission nor the ". "permission to change the permission; cannot ". "estimate disk usage of '$dir'\n"); $CPAN::Frontend->mysleep(5); return; } } } elsif (-f $dir) { # nothing to say, no matter what the permissions } } else { $CPAN::Frontend->mywarn("File or directory '$dir' has gone, ignoring\n"); return; } if ($fast) { $Du = 0; # placeholder } else { find( sub { $File::Find::prune++ if $CPAN::Signal; return if -l $_; if ($^O eq 'MacOS') { require Mac::Files; my $cat = Mac::Files::FSpGetCatInfo($_); $Du += $cat->ioFlLgLen() + $cat->ioFlRLgLen() if $cat; } else { if (-d _) { unless (-x _) { unless (chmod 0755, $_) { $CPAN::Frontend->mywarn("I have neither the -x permission nor ". "the permission to change the permission; ". "can only partially estimate disk usage ". "of '$_'\n"); $CPAN::Frontend->mysleep(5); return; } } } else { $Du += (-s _); } } }, $dir ); } return if $CPAN::Signal; $self->{SIZE}{$dir} = $Du/1024/1024; unshift @{$self->{FIFO}}, $dir; $self->debug("measured $dir is $Du") if $CPAN::DEBUG; $self->{DU} += $Du/1024/1024; $self->{DU}; } #-> sub CPAN::CacheMgr::_clean_cache ; sub _clean_cache { my($self,$dir) = @_; return unless -e $dir; unless (File::Spec->canonpath(File::Basename::dirname($dir)) eq File::Spec->canonpath($CPAN::Config->{build_dir})) { $CPAN::Frontend->mywarn("Directory '$dir' not below $CPAN::Config->{build_dir}, ". "will not remove\n"); $CPAN::Frontend->mysleep(5); return; } $self->debug("have to rmtree $dir, will free $self->{SIZE}{$dir}") if $CPAN::DEBUG; File::Path::rmtree($dir); my $id_deleted = 0; if ($dir !~ /\.yml$/ && -f "$dir.yml") { my $yaml_module = CPAN::_yaml_module; if ($CPAN::META->has_inst($yaml_module)) { my($peek_yaml) = eval { CPAN->_yaml_loadfile("$dir.yml"); }; if ($@) { $CPAN::Frontend->mywarn("(parse error on '$dir.yml' removing anyway)"); unlink "$dir.yml" or $CPAN::Frontend->mywarn("(Could not unlink '$dir.yml': $!)"); return; } elsif (my $id = $peek_yaml->[0]{distribution}{ID}) { $CPAN::META->delete("CPAN::Distribution", $id); # XXX we should restore the state NOW, otherise this # distro does not exist until we read an index. BUG ALERT(?) # $CPAN::Frontend->mywarn (" +++\n"); $id_deleted++; } } unlink "$dir.yml"; # may fail unless ($id_deleted) { CPAN->debug("no distro found associated with '$dir'"); } } $self->{DU} -= $self->{SIZE}{$dir}; delete $self->{SIZE}{$dir}; } #-> sub CPAN::CacheMgr::new ; sub new { my $class = shift; my $time = time; my($debug,$t2); $debug = ""; my $self = { ID => $CPAN::Config->{build_dir}, MAX => $CPAN::Config->{'build_cache'}, SCAN => $CPAN::Config->{'scan_cache'} || 'atstart', DU => 0 }; File::Path::mkpath($self->{ID}); my $dh = DirHandle->new($self->{ID}); bless $self, $class; $self->scan_cache; $t2 = time; $debug .= "timing of CacheMgr->new: ".($t2 - $time); $time = $t2; CPAN->debug($debug) if $CPAN::DEBUG; $self; } #-> sub CPAN::CacheMgr::scan_cache ; sub scan_cache { my $self = shift; return if $self->{SCAN} eq 'never'; $CPAN::Frontend->mydie("Unknown scan_cache argument: $self->{SCAN}") unless $self->{SCAN} eq 'atstart'; return unless $CPAN::META->{LOCK}; $CPAN::Frontend->myprint( sprintf("Scanning cache %s for sizes\n", $self->{ID})); my $e; my @entries = $self->entries($self->{ID}); my $i = 0; my $painted = 0; for $e (@entries) { my $symbol = "."; if ($self->{DU} > $self->{MAX}) { $symbol = "-"; $self->disk_usage($e,1); } else { $self->disk_usage($e); } $i++; while (($painted/76) < ($i/@entries)) { $CPAN::Frontend->myprint($symbol); $painted++; } return if $CPAN::Signal; } $CPAN::Frontend->myprint("DONE\n"); $self->tidyup; } package CPAN::Shell; use strict; #-> sub CPAN::Shell::h ; sub h { my($class,$about) = @_; if (defined $about) { my $help; if (exists $Help->{$about}) { if (ref $Help->{$about}) { # aliases $about = ${$Help->{$about}}; } $help = $Help->{$about}; } else { $help = "No help available"; } $CPAN::Frontend->myprint("$about\: $help\n"); } else { my $filler = " " x (80 - 28 - length($CPAN::VERSION)); $CPAN::Frontend->myprint(qq{ Display Information $filler (ver $CPAN::VERSION) command argument description a,b,d,m WORD or /REGEXP/ about authors, bundles, distributions, modules i WORD or /REGEXP/ about any of the above ls AUTHOR or GLOB about files in the author's directory (with WORD being a module, bundle or author name or a distribution name of the form AUTHOR/DISTRIBUTION) Download, Test, Make, Install... get download clean make clean make make (implies get) look open subshell in dist directory test make test (implies make) readme display these README files install make install (implies test) perldoc display POD documentation Upgrade r WORDs or /REGEXP/ or NONE report updates for some/matching/all modules upgrade WORDs or /REGEXP/ or NONE upgrade some/matching/all modules Pragmas force CMD try hard to do command fforce CMD try harder notest CMD skip testing Other h,? display this menu ! perl-code eval a perl command o conf [opt] set and query options q quit the cpan shell reload cpan load CPAN.pm again reload index load newer indices autobundle Snapshot recent latest CPAN uploads}); } } *help = \&h; #-> sub CPAN::Shell::a ; sub a { my($self,@arg) = @_; # authors are always UPPERCASE for (@arg) { $_ = uc $_ unless /=/; } $CPAN::Frontend->myprint($self->format_result('Author',@arg)); } #-> sub CPAN::Shell::globls ; sub globls { my($self,$s,$pragmas) = @_; # ls is really very different, but we had it once as an ordinary # command in the Shell (upto rev. 321) and we could not handle # force well then my(@accept,@preexpand); if ($s =~ /[\*\?\/]/) { if ($CPAN::META->has_inst("Text::Glob")) { if (my($au,$pathglob) = $s =~ m|(.*?)/(.*)|) { my $rau = Text::Glob::glob_to_regex(uc $au); CPAN::Shell->debug("au[$au]pathglob[$pathglob]rau[$rau]") if $CPAN::DEBUG; push @preexpand, map { $_->id . "/" . $pathglob } CPAN::Shell->expand_by_method('CPAN::Author',['id'],"/$rau/"); } else { my $rau = Text::Glob::glob_to_regex(uc $s); push @preexpand, map { $_->id } CPAN::Shell->expand_by_method('CPAN::Author', ['id'], "/$rau/"); } } else { $CPAN::Frontend->mydie("Text::Glob not installed, cannot proceed"); } } else { push @preexpand, uc $s; } for (@preexpand) { unless (/^[A-Z0-9\-]+(\/|$)/i) { $CPAN::Frontend->mywarn("ls command rejects argument $_: not an author\n"); next; } push @accept, $_; } my $silent = @accept>1; my $last_alpha = ""; my @results; for my $a (@accept) { my($author,$pathglob); if ($a =~ m|(.*?)/(.*)|) { my $a2 = $1; $pathglob = $2; $author = CPAN::Shell->expand_by_method('CPAN::Author', ['id'], $a2) or $CPAN::Frontend->mydie("No author found for $a2\n"); } else { $author = CPAN::Shell->expand_by_method('CPAN::Author', ['id'], $a) or $CPAN::Frontend->mydie("No author found for $a\n"); } if ($silent) { my $alpha = substr $author->id, 0, 1; my $ad; if ($alpha eq $last_alpha) { $ad = ""; } else { $ad = "[$alpha]"; $last_alpha = $alpha; } $CPAN::Frontend->myprint($ad); } for my $pragma (@$pragmas) { if ($author->can($pragma)) { $author->$pragma(); } } push @results, $author->ls($pathglob,$silent); # silent if # more than one # author for my $pragma (@$pragmas) { my $unpragma = "un$pragma"; if ($author->can($unpragma)) { $author->$unpragma(); } } } @results; } #-> sub CPAN::Shell::local_bundles ; sub local_bundles { my($self,@which) = @_; my($incdir,$bdir,$dh); foreach $incdir ($CPAN::Config->{'cpan_home'},@INC) { my @bbase = "Bundle"; while (my $bbase = shift @bbase) { $bdir = File::Spec->catdir($incdir,split /::/, $bbase); CPAN->debug("bdir[$bdir]\@bbase[@bbase]") if $CPAN::DEBUG; if ($dh = DirHandle->new($bdir)) { # may fail my($entry); for $entry ($dh->read) { next if $entry =~ /^\./; next unless $entry =~ /^\w+(\.pm)?(?!\n)\Z/; if (-d File::Spec->catdir($bdir,$entry)) { push @bbase, "$bbase\::$entry"; } else { next unless $entry =~ s/\.pm(?!\n)\Z//; $CPAN::META->instance('CPAN::Bundle',"$bbase\::$entry"); } } } } } } #-> sub CPAN::Shell::b ; sub b { my($self,@which) = @_; CPAN->debug("which[@which]") if $CPAN::DEBUG; $self->local_bundles; $CPAN::Frontend->myprint($self->format_result('Bundle',@which)); } #-> sub CPAN::Shell::d ; sub d { $CPAN::Frontend->myprint(shift->format_result('Distribution',@_));} #-> sub CPAN::Shell::m ; sub m { # emacs confused here }; sub mimimimimi { # emacs in sync here my $self = shift; $CPAN::Frontend->myprint($self->format_result('Module',@_)); } #-> sub CPAN::Shell::i ; sub i { my($self) = shift; my(@args) = @_; @args = '/./' unless @args; my(@result); for my $type (qw/Bundle Distribution Module/) { push @result, $self->expand($type,@args); } # Authors are always uppercase. push @result, $self->expand("Author", map { uc $_ } @args); my $result = @result == 1 ? $result[0]->as_string : @result == 0 ? "No objects found of any type for argument @args\n" : join("", (map {$_->as_glimpse} @result), scalar @result, " items found\n", ); $CPAN::Frontend->myprint($result); } #-> sub CPAN::Shell::o ; # CPAN::Shell::o and CPAN::HandleConfig::edit are closely related. 'o # conf' calls through to CPAN::HandleConfig::edit. 'o conf' should # probably have been called 'set' and 'o debug' maybe 'set debug' or # 'debug'; 'o conf ARGS' calls ->edit in CPAN/HandleConfig.pm sub o { my($self,$o_type,@o_what) = @_; $o_type ||= ""; CPAN->debug("o_type[$o_type] o_what[".join(" | ",@o_what)."]\n"); if ($o_type eq 'conf') { my($cfilter); ($cfilter) = $o_what[0] =~ m|^/(.*)/$| if @o_what; if (!@o_what or $cfilter) { # print all things, "o conf" $cfilter ||= ""; my $qrfilter = eval 'qr/$cfilter/'; my($k,$v); $CPAN::Frontend->myprint("\$CPAN::Config options from "); my @from; if (exists $INC{'CPAN/Config.pm'}) { push @from, $INC{'CPAN/Config.pm'}; } if (exists $INC{'CPAN/MyConfig.pm'}) { push @from, $INC{'CPAN/MyConfig.pm'}; } $CPAN::Frontend->myprint(join " and ", map {"'$_'"} @from); $CPAN::Frontend->myprint(":\n"); for $k (sort keys %CPAN::HandleConfig::can) { next unless $k =~ /$qrfilter/; $v = $CPAN::HandleConfig::can{$k}; $CPAN::Frontend->myprint(sprintf " %-18s [%s]\n", $k, $v); } $CPAN::Frontend->myprint("\n"); for $k (sort keys %CPAN::HandleConfig::keys) { next unless $k =~ /$qrfilter/; CPAN::HandleConfig->prettyprint($k); } $CPAN::Frontend->myprint("\n"); } else { if (CPAN::HandleConfig->edit(@o_what)) { } else { $CPAN::Frontend->myprint(qq{Type 'o conf' to view all configuration }. qq{items\n\n}); } } } elsif ($o_type eq 'debug') { my(%valid); @o_what = () if defined $o_what[0] && $o_what[0] =~ /help/i; if (@o_what) { while (@o_what) { my($what) = shift @o_what; if ($what =~ s/^-// && exists $CPAN::DEBUG{$what}) { $CPAN::DEBUG &= $CPAN::DEBUG ^ $CPAN::DEBUG{$what}; next; } if ( exists $CPAN::DEBUG{$what} ) { $CPAN::DEBUG |= $CPAN::DEBUG{$what}; } elsif ($what =~ /^\d/) { $CPAN::DEBUG = $what; } elsif (lc $what eq 'all') { my($max) = 0; for (values %CPAN::DEBUG) { $max += $_; } $CPAN::DEBUG = $max; } else { my($known) = 0; for (keys %CPAN::DEBUG) { next unless lc($_) eq lc($what); $CPAN::DEBUG |= $CPAN::DEBUG{$_}; $known = 1; } $CPAN::Frontend->myprint("unknown argument [$what]\n") unless $known; } } } else { my $raw = "Valid options for debug are ". join(", ",sort(keys %CPAN::DEBUG), 'all'). qq{ or a number. Completion works on the options. }. qq{Case is ignored.}; require Text::Wrap; $CPAN::Frontend->myprint(Text::Wrap::fill("","",$raw)); $CPAN::Frontend->myprint("\n\n"); } if ($CPAN::DEBUG) { $CPAN::Frontend->myprint("Options set for debugging ($CPAN::DEBUG):\n"); my($k,$v); for $k (sort {$CPAN::DEBUG{$a} <=> $CPAN::DEBUG{$b}} keys %CPAN::DEBUG) { $v = $CPAN::DEBUG{$k}; $CPAN::Frontend->myprint(sprintf " %-14s(%s)\n", $k, $v) if $v & $CPAN::DEBUG; } } else { $CPAN::Frontend->myprint("Debugging turned off completely.\n"); } } else { $CPAN::Frontend->myprint(qq{ Known options: conf set or get configuration variables debug set or get debugging options }); } } # CPAN::Shell::paintdots_onreload sub paintdots_onreload { my($ref) = shift; sub { if ( $_[0] =~ /[Ss]ubroutine ([\w:]+) redefined/ ) { my($subr) = $1; ++$$ref; local($|) = 1; # $CPAN::Frontend->myprint(".($subr)"); $CPAN::Frontend->myprint("."); if ($subr =~ /\bshell\b/i) { # warn "debug[$_[0]]"; # It would be nice if we could detect that a # subroutine has actually changed, but for now we # practically always set the GOTOSHELL global $CPAN::GOTOSHELL=1; } return; } warn @_; }; } #-> sub CPAN::Shell::hosts ; sub hosts { my($self) = @_; my $fullstats = CPAN::FTP->_ftp_statistics(); my $history = $fullstats->{history} || []; my %S; # statistics while (my $last = pop @$history) { my $attempts = $last->{attempts} or next; my $start; if (@$attempts) { $start = $attempts->[-1]{start}; if ($#$attempts > 0) { for my $i (0..$#$attempts-1) { my $url = $attempts->[$i]{url} or next; $S{no}{$url}++; } } } else { $start = $last->{start}; } next unless $last->{thesiteurl}; # C-C? bad filenames? $S{start} = $start; $S{end} ||= $last->{end}; my $dltime = $last->{end} - $start; my $dlsize = $last->{filesize} || 0; my $url = ref $last->{thesiteurl} ? $last->{thesiteurl}->text : $last->{thesiteurl}; my $s = $S{ok}{$url} ||= {}; $s->{n}++; $s->{dlsize} ||= 0; $s->{dlsize} += $dlsize/1024; $s->{dltime} ||= 0; $s->{dltime} += $dltime; } my $res; for my $url (keys %{$S{ok}}) { next if $S{ok}{$url}{dltime} == 0; # div by zero push @{$res->{ok}}, [@{$S{ok}{$url}}{qw(n dlsize dltime)}, $S{ok}{$url}{dlsize}/$S{ok}{$url}{dltime}, $url, ]; } for my $url (keys %{$S{no}}) { push @{$res->{no}}, [$S{no}{$url}, $url, ]; } my $R = ""; # report if ($S{start} && $S{end}) { $R .= sprintf "Log starts: %s\n", $S{start} ? scalar(localtime $S{start}) : "unknown"; $R .= sprintf "Log ends : %s\n", $S{end} ? scalar(localtime $S{end}) : "unknown"; } if ($res->{ok} && @{$res->{ok}}) { $R .= sprintf "\nSuccessful downloads: N kB secs kB/s url\n"; my $i = 20; for (sort { $b->[3] <=> $a->[3] } @{$res->{ok}}) { $R .= sprintf "%4d %8d %5d %9.1f %s\n", @$_; last if --$i<=0; } } if ($res->{no} && @{$res->{no}}) { $R .= sprintf "\nUnsuccessful downloads:\n"; my $i = 20; for (sort { $b->[0] <=> $a->[0] } @{$res->{no}}) { $R .= sprintf "%4d %s\n", @$_; last if --$i<=0; } } $CPAN::Frontend->myprint($R); } #-> sub CPAN::Shell::reload ; sub reload { my($self,$command,@arg) = @_; $command ||= ""; $self->debug("self[$self]command[$command]arg[@arg]") if $CPAN::DEBUG; if ($command =~ /^cpan$/i) { my $redef = 0; chdir $CPAN::iCwd if $CPAN::iCwd; # may fail my $failed; my @relo = ( "CPAN.pm", "CPAN/Debug.pm", "CPAN/FirstTime.pm", "CPAN/HandleConfig.pm", "CPAN/Kwalify.pm", "CPAN/Queue.pm", "CPAN/Reporter/Config.pm", "CPAN/Reporter/History.pm", "CPAN/Reporter.pm", "CPAN/SQLite.pm", "CPAN/Tarzip.pm", "CPAN/Version.pm", ); MFILE: for my $f (@relo) { next unless exists $INC{$f}; my $p = $f; $p =~ s/\.pm$//; $p =~ s|/|::|g; $CPAN::Frontend->myprint("($p"); local($SIG{__WARN__}) = paintdots_onreload(\$redef); $self->_reload_this($f) or $failed++; my $v = eval "$p\::->VERSION"; $CPAN::Frontend->myprint("v$v)"); } $CPAN::Frontend->myprint("\n$redef subroutines redefined\n"); if ($failed) { my $errors = $failed == 1 ? "error" : "errors"; $CPAN::Frontend->mywarn("\n$failed $errors during reload. You better quit ". "this session.\n"); } } elsif ($command =~ /^index$/i) { CPAN::Index->force_reload; } else { $CPAN::Frontend->myprint(qq{cpan re-evals the CPAN modules index re-reads the index files\n}); } } # reload means only load again what we have loaded before #-> sub CPAN::Shell::_reload_this ; sub _reload_this { my($self,$f,$args) = @_; CPAN->debug("f[$f]") if $CPAN::DEBUG; return 1 unless $INC{$f}; # we never loaded this, so we do not # reload but say OK my $pwd = CPAN::anycwd(); CPAN->debug("pwd[$pwd]") if $CPAN::DEBUG; my($file); for my $inc (@INC) { $file = File::Spec->catfile($inc,split /\//, $f); last if -f $file; $file = ""; } CPAN->debug("file[$file]") if $CPAN::DEBUG; my @inc = @INC; unless ($file && -f $file) { # this thingie is not in the INC path, maybe CPAN/MyConfig.pm? $file = $INC{$f}; unless (CPAN->has_inst("File::Basename")) { @inc = File::Basename::dirname($file); } else { # do we ever need this? @inc = substr($file,0,-length($f)-1); # bring in back to me! } } CPAN->debug("file[$file]inc[@inc]") if $CPAN::DEBUG; unless (-f $file) { $CPAN::Frontend->mywarn("Found no file to reload for '$f'\n"); return; } my $mtime = (stat $file)[9]; if ($reload->{$f}) { } elsif ($^T < $mtime) { # since we started the file has changed, force it to be reloaded $reload->{$f} = -1; } else { $reload->{$f} = $mtime; } my $must_reload = $mtime != $reload->{$f}; $args ||= {}; $must_reload ||= $args->{reloforce}; # o conf defaults needs this if ($must_reload) { my $fh = FileHandle->new($file) or $CPAN::Frontend->mydie("Could not open $file: $!"); local($/); local $^W = 1; my $content = <$fh>; CPAN->debug(sprintf("reload file[%s] content[%s...]",$file,substr($content,0,128))) if $CPAN::DEBUG; delete $INC{$f}; local @INC = @inc; eval "require '$f'"; if ($@) { warn $@; return; } $reload->{$f} = $mtime; } else { $CPAN::Frontend->myprint("__unchanged__"); } return 1; } #-> sub CPAN::Shell::mkmyconfig ; sub mkmyconfig { my($self, $cpanpm, %args) = @_; require CPAN::FirstTime; my $home = CPAN::HandleConfig::home; $cpanpm = $INC{'CPAN/MyConfig.pm'} || File::Spec->catfile(split /\//, "$home/.cpan/CPAN/MyConfig.pm"); File::Path::mkpath(File::Basename::dirname($cpanpm)) unless -e $cpanpm; CPAN::HandleConfig::require_myconfig_or_config; $CPAN::Config ||= {}; $CPAN::Config = { %$CPAN::Config, build_dir => undef, cpan_home => undef, keep_source_where => undef, histfile => undef, }; CPAN::FirstTime::init($cpanpm, %args); } #-> sub CPAN::Shell::_binary_extensions ; sub _binary_extensions { my($self) = shift @_; my(@result,$module,%seen,%need,$headerdone); for $module ($self->expand('Module','/./')) { my $file = $module->cpan_file; next if $file eq "N/A"; next if $file =~ /^Contact Author/; my $dist = $CPAN::META->instance('CPAN::Distribution',$file); next if $dist->isa_perl; next unless $module->xs_file; local($|) = 1; $CPAN::Frontend->myprint("."); push @result, $module; } # print join " | ", @result; $CPAN::Frontend->myprint("\n"); return @result; } #-> sub CPAN::Shell::recompile ; sub recompile { my($self) = shift @_; my($module,@module,$cpan_file,%dist); @module = $self->_binary_extensions(); for $module (@module) { # we force now and compile later, so we # don't do it twice $cpan_file = $module->cpan_file; my $pack = $CPAN::META->instance('CPAN::Distribution',$cpan_file); $pack->force; $dist{$cpan_file}++; } for $cpan_file (sort keys %dist) { $CPAN::Frontend->myprint(" CPAN: Recompiling $cpan_file\n\n"); my $pack = $CPAN::META->instance('CPAN::Distribution',$cpan_file); $pack->install; $CPAN::Signal = 0; # it's tempting to reset Signal, so we can # stop a package from recompiling, # e.g. IO-1.12 when we have perl5.003_10 } } #-> sub CPAN::Shell::scripts ; sub scripts { my($self, $arg) = @_; $CPAN::Frontend->mywarn(">>>> experimental command, currently unsupported <<<<\n\n"); for my $req (qw( HTML::LinkExtor Sort::Versions List::Util )) { unless ($CPAN::META->has_inst($req)) { $CPAN::Frontend->mywarn(" $req not available\n"); } } my $p = HTML::LinkExtor->new(); my $indexfile = "/home/ftp/pub/PAUSE/scripts/new/index.html"; unless (-f $indexfile) { $CPAN::Frontend->mydie("found no indexfile[$indexfile]\n"); } $p->parse_file($indexfile); my @hrefs; my $qrarg; if ($arg =~ s|^/(.+)/$|$1|) { $qrarg = eval 'qr/$arg/'; # hide construct from 5.004 } for my $l ($p->links) { my $tag = shift @$l; next unless $tag eq "a"; my %att = @$l; my $href = $att{href}; next unless $href =~ s|^\.\./authors/id/./../||; if ($arg) { if ($qrarg) { if ($href =~ $qrarg) { push @hrefs, $href; } } else { if ($href =~ /\Q$arg\E/) { push @hrefs, $href; } } } else { push @hrefs, $href; } } # now filter for the latest version if there is more than one of a name my %stems; for (sort @hrefs) { my $href = $_; s/-v?\d.*//; my $stem = $_; $stems{$stem} ||= []; push @{$stems{$stem}}, $href; } for (sort keys %stems) { my $highest; if (@{$stems{$_}} > 1) { $highest = List::Util::reduce { Sort::Versions::versioncmp($a,$b) > 0 ? $a : $b } @{$stems{$_}}; } else { $highest = $stems{$_}[0]; } $CPAN::Frontend->myprint("$highest\n"); } } #-> sub CPAN::Shell::report ; sub report { my($self,@args) = @_; unless ($CPAN::META->has_inst("CPAN::Reporter")) { $CPAN::Frontend->mydie("CPAN::Reporter not installed; cannot continue"); } local $CPAN::Config->{test_report} = 1; $self->force("test",@args); # force is there so that the test be # re-run (as documented) } # compare with is_tested #-> sub CPAN::Shell::install_tested sub install_tested { my($self,@some) = @_; $CPAN::Frontend->mywarn("install_tested() must not be called with arguments.\n"), return if @some; CPAN::Index->reload; for my $b (reverse $CPAN::META->_list_sorted_descending_is_tested) { my $yaml = "$b.yml"; unless (-f $yaml) { $CPAN::Frontend->mywarn("No YAML file for $b available, skipping\n"); next; } my $yaml_content = CPAN->_yaml_loadfile($yaml); my $id = $yaml_content->[0]{distribution}{ID}; unless ($id) { $CPAN::Frontend->mywarn("No ID found in '$yaml', skipping\n"); next; } my $do = CPAN::Shell->expandany($id); unless ($do) { $CPAN::Frontend->mywarn("Could not expand ID '$id', skipping\n"); next; } unless ($do->{build_dir}) { $CPAN::Frontend->mywarn("Distro '$id' has no build_dir, skipping\n"); next; } unless ($do->{build_dir} eq $b) { $CPAN::Frontend->mywarn("Distro '$id' has build_dir '$do->{build_dir}' but expected '$b', skipping\n"); next; } push @some, $do; } $CPAN::Frontend->mywarn("No tested distributions found.\n"), return unless @some; @some = grep { $_->{make_test} && ! $_->{make_test}->failed } @some; $CPAN::Frontend->mywarn("No distributions tested with this build of perl found.\n"), return unless @some; # @some = grep { not $_->uptodate } @some; # $CPAN::Frontend->mywarn("No non-uptodate distributions tested with this build of perl found.\n"), # return unless @some; CPAN->debug("some[@some]"); for my $d (@some) { my $id = $d->can("pretty_id") ? $d->pretty_id : $d->id; $CPAN::Frontend->myprint("install_tested: Running for $id\n"); $CPAN::Frontend->mysleep(1); $self->install($d); } } #-> sub CPAN::Shell::upgrade ; sub upgrade { my($self,@args) = @_; $self->install($self->r(@args)); } #-> sub CPAN::Shell::_u_r_common ; sub _u_r_common { my($self) = shift @_; my($what) = shift @_; CPAN->debug("self[$self] what[$what] args[@_]") if $CPAN::DEBUG; Carp::croak "Usage: \$obj->_u_r_common(a|r|u)" unless $what && $what =~ /^[aru]$/; my(@args) = @_; @args = '/./' unless @args; my(@result,$module,%seen,%need,$headerdone, $version_undefs,$version_zeroes, @version_undefs,@version_zeroes); $version_undefs = $version_zeroes = 0; my $sprintf = "%s%-25s%s %9s %9s %s\n"; my @expand = $self->expand('Module',@args); my $expand = scalar @expand; if (0) { # Looks like noise to me, was very useful for debugging # for metadata cache $CPAN::Frontend->myprint(sprintf "%d matches in the database\n", $expand); } MODULE: for $module (@expand) { my $file = $module->cpan_file; next MODULE unless defined $file; # ?? $file =~ s!^./../!!; my($latest) = $module->cpan_version; my($inst_file) = $module->inst_file; my($have); return if $CPAN::Signal; if ($inst_file) { if ($what eq "a") { $have = $module->inst_version; } elsif ($what eq "r") { $have = $module->inst_version; local($^W) = 0; if ($have eq "undef") { $version_undefs++; push @version_undefs, $module->as_glimpse; } elsif (CPAN::Version->vcmp($have,0)==0) { $version_zeroes++; push @version_zeroes, $module->as_glimpse; } next MODULE unless CPAN::Version->vgt($latest, $have); # to be pedantic we should probably say: # && !($have eq "undef" && $latest ne "undef" && $latest gt ""); # to catch the case where CPAN has a version 0 and we have a version undef } elsif ($what eq "u") { next MODULE; } } else { if ($what eq "a") { next MODULE; } elsif ($what eq "r") { next MODULE; } elsif ($what eq "u") { $have = "-"; } } return if $CPAN::Signal; # this is sometimes lengthy $seen{$file} ||= 0; if ($what eq "a") { push @result, sprintf "%s %s\n", $module->id, $have; } elsif ($what eq "r") { push @result, $module->id; next MODULE if $seen{$file}++; } elsif ($what eq "u") { push @result, $module->id; next MODULE if $seen{$file}++; next MODULE if $file =~ /^Contact/; } unless ($headerdone++) { $CPAN::Frontend->myprint("\n"); $CPAN::Frontend->myprint(sprintf( $sprintf, "", "Package namespace", "", "installed", "latest", "in CPAN file" )); } my $color_on = ""; my $color_off = ""; if ( $COLOR_REGISTERED && $CPAN::META->has_inst("Term::ANSIColor") && $module->description ) { $color_on = Term::ANSIColor::color("green"); $color_off = Term::ANSIColor::color("reset"); } $CPAN::Frontend->myprint(sprintf $sprintf, $color_on, $module->id, $color_off, $have, $latest, $file); $need{$module->id}++; } unless (%need) { if ($what eq "u") { $CPAN::Frontend->myprint("No modules found for @args\n"); } elsif ($what eq "r") { $CPAN::Frontend->myprint("All modules are up to date for @args\n"); } } if ($what eq "r") { if ($version_zeroes) { my $s_has = $version_zeroes > 1 ? "s have" : " has"; $CPAN::Frontend->myprint(qq{$version_zeroes installed module$s_has }. qq{a version number of 0\n}); if ($CPAN::Config->{show_zero_versions}) { local $" = "\t"; $CPAN::Frontend->myprint(qq{ they are\n\t@version_zeroes\n}); $CPAN::Frontend->myprint(qq{(use 'o conf show_zero_versions 0' }. qq{to hide them)\n}); } else { $CPAN::Frontend->myprint(qq{(use 'o conf show_zero_versions 1' }. qq{to show them)\n}); } } if ($version_undefs) { my $s_has = $version_undefs > 1 ? "s have" : " has"; $CPAN::Frontend->myprint(qq{$version_undefs installed module$s_has no }. qq{parseable version number\n}); if ($CPAN::Config->{show_unparsable_versions}) { local $" = "\t"; $CPAN::Frontend->myprint(qq{ they are\n\t@version_undefs\n}); $CPAN::Frontend->myprint(qq{(use 'o conf show_unparsable_versions 0' }. qq{to hide them)\n}); } else { $CPAN::Frontend->myprint(qq{(use 'o conf show_unparsable_versions 1' }. qq{to show them)\n}); } } } @result; } #-> sub CPAN::Shell::r ; sub r { shift->_u_r_common("r",@_); } #-> sub CPAN::Shell::u ; sub u { shift->_u_r_common("u",@_); } #-> sub CPAN::Shell::failed ; sub failed { my($self,$only_id,$silent) = @_; my @failed; DIST: for my $d ($CPAN::META->all_objects("CPAN::Distribution")) { my $failed = ""; NAY: for my $nosayer ( # order matters! "unwrapped", "writemakefile", "signature_verify", "make", "make_test", "install", "make_clean", ) { next unless exists $d->{$nosayer}; next unless defined $d->{$nosayer}; next unless ( UNIVERSAL::can($d->{$nosayer},"failed") ? $d->{$nosayer}->failed : $d->{$nosayer} =~ /^NO/ ); next NAY if $only_id && $only_id != ( UNIVERSAL::can($d->{$nosayer},"commandid") ? $d->{$nosayer}->commandid : $CPAN::CurrentCommandId ); $failed = $nosayer; last; } next DIST unless $failed; my $id = $d->id; $id =~ s|^./../||; #$print .= sprintf( # " %-45s: %s %s\n", push @failed, ( UNIVERSAL::can($d->{$failed},"failed") ? [ $d->{$failed}->commandid, $id, $failed, $d->{$failed}->text, $d->{$failed}{TIME}||0, ] : [ 1, $id, $failed, $d->{$failed}, 0, ] ); } my $scope; if ($only_id) { $scope = "this command"; } elsif ($CPAN::Index::HAVE_REANIMATED) { $scope = "this or a previous session"; # it might be nice to have a section for previous session and # a second for this } else { $scope = "this session"; } if (@failed) { my $print; my $debug = 0; if ($debug) { $print = join "", map { sprintf "%5d %-45s: %s %s\n", @$_ } sort { $a->[0] <=> $b->[0] } @failed; } else { $print = join "", map { sprintf " %-45s: %s %s\n", @$_[1..3] } sort { $a->[0] <=> $b->[0] || $a->[4] <=> $b->[4] } @failed; } $CPAN::Frontend->myprint("Failed during $scope:\n$print"); } elsif (!$only_id || !$silent) { $CPAN::Frontend->myprint("Nothing failed in $scope\n"); } } # XXX intentionally undocumented because completely bogus, unportable, # useless, etc. #-> sub CPAN::Shell::status ; sub status { my($self) = @_; require Devel::Size; my $ps = FileHandle->new; open $ps, "/proc/$$/status"; my $vm = 0; while (<$ps>) { next unless /VmSize:\s+(\d+)/; $vm = $1; last; } $CPAN::Frontend->mywarn(sprintf( "%-27s %6d\n%-27s %6d\n", "vm", $vm, "CPAN::META", Devel::Size::total_size($CPAN::META)/1024, )); for my $k (sort keys %$CPAN::META) { next unless substr($k,0,4) eq "read"; warn sprintf " %-26s %6d\n", $k, Devel::Size::total_size($CPAN::META->{$k})/1024; for my $k2 (sort keys %{$CPAN::META->{$k}}) { warn sprintf " %-25s %6d (keys: %6d)\n", $k2, Devel::Size::total_size($CPAN::META->{$k}{$k2})/1024, scalar keys %{$CPAN::META->{$k}{$k2}}; } } } # compare with install_tested #-> sub CPAN::Shell::is_tested sub is_tested { my($self) = @_; CPAN::Index->reload; for my $b (reverse $CPAN::META->_list_sorted_descending_is_tested) { my $time; if ($CPAN::META->{is_tested}{$b}) { $time = scalar(localtime $CPAN::META->{is_tested}{$b}); } else { $time = scalar localtime; $time =~ s/\S/?/g; } $CPAN::Frontend->myprint(sprintf "%s %s\n", $time, $b); } } #-> sub CPAN::Shell::autobundle ; sub autobundle { my($self) = shift; CPAN::HandleConfig->load unless $CPAN::Config_loaded++; my(@bundle) = $self->_u_r_common("a",@_); my($todir) = File::Spec->catdir($CPAN::Config->{'cpan_home'},"Bundle"); File::Path::mkpath($todir); unless (-d $todir) { $CPAN::Frontend->myprint("Couldn't mkdir $todir for some reason\n"); return; } my($y,$m,$d) = (localtime)[5,4,3]; $y+=1900; $m++; my($c) = 0; my($me) = sprintf "Snapshot_%04d_%02d_%02d_%02d", $y, $m, $d, $c; my($to) = File::Spec->catfile($todir,"$me.pm"); while (-f $to) { $me = sprintf "Snapshot_%04d_%02d_%02d_%02d", $y, $m, $d, ++$c; $to = File::Spec->catfile($todir,"$me.pm"); } my($fh) = FileHandle->new(">$to") or Carp::croak "Can't open >$to: $!"; $fh->print( "package Bundle::$me;\n\n", "\$VERSION = '0.01';\n\n", "1;\n\n", "__END__\n\n", "=head1 NAME\n\n", "Bundle::$me - Snapshot of installation on ", $Config::Config{'myhostname'}, " on ", scalar(localtime), "\n\n=head1 SYNOPSIS\n\n", "perl -MCPAN -e 'install Bundle::$me'\n\n", "=head1 CONTENTS\n\n", join("\n", @bundle), "\n\n=head1 CONFIGURATION\n\n", Config->myconfig, "\n\n=head1 AUTHOR\n\n", "This Bundle has been generated automatically ", "by the autobundle routine in CPAN.pm.\n", ); $fh->close; $CPAN::Frontend->myprint("\nWrote bundle file $to\n\n"); } #-> sub CPAN::Shell::expandany ; sub expandany { my($self,$s) = @_; CPAN->debug("s[$s]") if $CPAN::DEBUG; if ($s =~ m|/| or substr($s,-1,1) eq ".") { # looks like a file or a directory $s = CPAN::Distribution->normalize($s); return $CPAN::META->instance('CPAN::Distribution',$s); # Distributions spring into existence, not expand } elsif ($s =~ m|^Bundle::|) { $self->local_bundles; # scanning so late for bundles seems # both attractive and crumpy: always # current state but easy to forget # somewhere return $self->expand('Bundle',$s); } else { return $self->expand('Module',$s) if $CPAN::META->exists('CPAN::Module',$s); } return; } #-> sub CPAN::Shell::expand ; sub expand { my $self = shift; my($type,@args) = @_; CPAN->debug("type[$type]args[@args]") if $CPAN::DEBUG; my $class = "CPAN::$type"; my $methods = ['id']; for my $meth (qw(name)) { next unless $class->can($meth); push @$methods, $meth; } $self->expand_by_method($class,$methods,@args); } #-> sub CPAN::Shell::expand_by_method ; sub expand_by_method { my $self = shift; my($class,$methods,@args) = @_; my($arg,@m); for $arg (@args) { my($regex,$command); if ($arg =~ m|^/(.*)/$|) { $regex = $1; # FIXME: there seem to be some ='s in the author data, which trigger # a failure here. This needs to be contemplated. # } elsif ($arg =~ m/=/) { # $command = 1; } my $obj; CPAN->debug(sprintf "class[%s]regex[%s]command[%s]", $class, defined $regex ? $regex : "UNDEFINED", defined $command ? $command : "UNDEFINED", ) if $CPAN::DEBUG; if (defined $regex) { if (CPAN::_sqlite_running) { $CPAN::SQLite->search($class, $regex); } for $obj ( $CPAN::META->all_objects($class) ) { unless ($obj && UNIVERSAL::can($obj,"id") && $obj->id) { # BUG, we got an empty object somewhere require Data::Dumper; CPAN->debug(sprintf( "Bug in CPAN: Empty id on obj[%s][%s]", $obj, Data::Dumper::Dumper($obj) )) if $CPAN::DEBUG; next; } for my $method (@$methods) { my $match = eval {$obj->$method() =~ /$regex/i}; if ($@) { my($err) = $@ =~ /^(.+) at .+? line \d+\.$/; $err ||= $@; # if we were too restrictive above $CPAN::Frontend->mydie("$err\n"); } elsif ($match) { push @m, $obj; last; } } } } elsif ($command) { die "equal sign in command disabled (immature interface), ". "you can set ! \$CPAN::Shell::ADVANCED_QUERY=1 to enable it. But please note, this is HIGHLY EXPERIMENTAL code that may go away anytime.\n" unless $ADVANCED_QUERY; my($method,$criterion) = $arg =~ /(.+?)=(.+)/; my($matchcrit) = $criterion =~ m/^~(.+)/; for my $self ( sort {$a->id cmp $b->id} $CPAN::META->all_objects($class) ) { my $lhs = $self->$method() or next; # () for 5.00503 if ($matchcrit) { push @m, $self if $lhs =~ m/$matchcrit/; } else { push @m, $self if $lhs eq $criterion; } } } else { my($xarg) = $arg; if ( $class eq 'CPAN::Bundle' ) { $xarg =~ s/^(Bundle::)?(.*)/Bundle::$2/; } elsif ($class eq "CPAN::Distribution") { $xarg = CPAN::Distribution->normalize($arg); } else { $xarg =~ s/:+/::/g; } if ($CPAN::META->exists($class,$xarg)) { $obj = $CPAN::META->instance($class,$xarg); } elsif ($CPAN::META->exists($class,$arg)) { $obj = $CPAN::META->instance($class,$arg); } else { next; } push @m, $obj; } } @m = sort {$a->id cmp $b->id} @m; if ( $CPAN::DEBUG ) { my $wantarray = wantarray; my $join_m = join ",", map {$_->id} @m; $self->debug("wantarray[$wantarray]join_m[$join_m]"); } return wantarray ? @m : $m[0]; } #-> sub CPAN::Shell::format_result ; sub format_result { my($self) = shift; my($type,@args) = @_; @args = '/./' unless @args; my(@result) = $self->expand($type,@args); my $result = @result == 1 ? $result[0]->as_string : @result == 0 ? "No objects of type $type found for argument @args\n" : join("", (map {$_->as_glimpse} @result), scalar @result, " items found\n", ); $result; } #-> sub CPAN::Shell::report_fh ; { my $installation_report_fh; my $previously_noticed = 0; sub report_fh { return $installation_report_fh if $installation_report_fh; if ($CPAN::META->has_usable("File::Temp")) { $installation_report_fh = File::Temp->new( dir => File::Spec->tmpdir, template => 'cpan_install_XXXX', suffix => '.txt', unlink => 0, ); } unless ( $installation_report_fh ) { warn("Couldn't open installation report file; " . "no report file will be generated." ) unless $previously_noticed++; } } } # The only reason for this method is currently to have a reliable # debugging utility that reveals which output is going through which # channel. No, I don't like the colors ;-) # to turn colordebugging on, write # cpan> o conf colorize_output 1 #-> sub CPAN::Shell::print_ornamented ; { my $print_ornamented_have_warned = 0; sub colorize_output { my $colorize_output = $CPAN::Config->{colorize_output}; if ($colorize_output && !$CPAN::META->has_inst("Term::ANSIColor")) { unless ($print_ornamented_have_warned++) { # no myprint/mywarn within myprint/mywarn! warn "Colorize_output is set to true but Term::ANSIColor is not installed. To activate colorized output, please install Term::ANSIColor.\n\n"; } $colorize_output = 0; } return $colorize_output; } } #-> sub CPAN::Shell::print_ornamented ; sub print_ornamented { my($self,$what,$ornament) = @_; return unless defined $what; local $| = 1; # Flush immediately if ( $CPAN::Be_Silent ) { print {report_fh()} $what; return; } my $swhat = "$what"; # stringify if it is an object if ($CPAN::Config->{term_is_latin}) { # note: deprecated, need to switch to $LANG and $LC_* # courtesy jhi: $swhat =~ s{([\xC0-\xDF])([\x80-\xBF])}{chr(ord($1)<<6&0xC0|ord($2)&0x3F)}eg; #}; } if ($self->colorize_output) { if ( $CPAN::DEBUG && $swhat =~ /^Debug\(/ ) { # if you want to have this configurable, please file a bugreport $ornament = $CPAN::Config->{colorize_debug} || "black on_cyan"; } my $color_on = eval { Term::ANSIColor::color($ornament) } || ""; if ($@) { print "Term::ANSIColor rejects color[$ornament]: $@\n Please choose a different color (Hint: try 'o conf init /color/')\n"; } # GGOLDBACH/Test-GreaterVersion-0.008 broke wthout this # $trailer construct. We want the newline be the last thing if # there is a newline at the end ensuring that the next line is # empty for other players my $trailer = ""; $trailer = $1 if $swhat =~ s/([\r\n]+)\z//; print $color_on, $swhat, Term::ANSIColor::color("reset"), $trailer; } else { print $swhat; } } #-> sub CPAN::Shell::myprint ; # where is myprint/mywarn/Frontend/etc. documented? Where to use what? # I think, we send everything to STDOUT and use print for normal/good # news and warn for news that need more attention. Yes, this is our # working contract for now. sub myprint { my($self,$what) = @_; $self->print_ornamented($what, $CPAN::Config->{colorize_print}||'bold blue on_white', ); } sub optprint { my($self,$category,$what) = @_; my $vname = $category . "_verbosity"; CPAN::HandleConfig->load unless $CPAN::Config_loaded++; if (!$CPAN::Config->{$vname} || $CPAN::Config->{$vname} =~ /^v/ ) { $CPAN::Frontend->myprint($what); } } #-> sub CPAN::Shell::myexit ; sub myexit { my($self,$what) = @_; $self->myprint($what); exit; } #-> sub CPAN::Shell::mywarn ; sub mywarn { my($self,$what) = @_; $self->print_ornamented($what, $CPAN::Config->{colorize_warn}||'bold red on_white'); } # only to be used for shell commands #-> sub CPAN::Shell::mydie ; sub mydie { my($self,$what) = @_; $self->mywarn($what); # If it is the shell, we want the following die to be silent, # but if it is not the shell, we would need a 'die $what'. We need # to take care that only shell commands use mydie. Is this # possible? die "\n"; } # sub CPAN::Shell::colorable_makemaker_prompt ; sub colorable_makemaker_prompt { my($foo,$bar) = @_; if (CPAN::Shell->colorize_output) { my $ornament = $CPAN::Config->{colorize_print}||'bold blue on_white'; my $color_on = eval { Term::ANSIColor::color($ornament); } || ""; print $color_on; } my $ans = ExtUtils::MakeMaker::prompt($foo,$bar); if (CPAN::Shell->colorize_output) { print Term::ANSIColor::color('reset'); } return $ans; } # use this only for unrecoverable errors! #-> sub CPAN::Shell::unrecoverable_error ; sub unrecoverable_error { my($self,$what) = @_; my @lines = split /\n/, $what; my $longest = 0; for my $l (@lines) { $longest = length $l if length $l > $longest; } $longest = 62 if $longest > 62; for my $l (@lines) { if ($l =~ /^\s*$/) { $l = "\n"; next; } $l = "==> $l"; if (length $l < 66) { $l = pack "A66 A*", $l, "<=="; } $l .= "\n"; } unshift @lines, "\n"; $self->mydie(join "", @lines); } #-> sub CPAN::Shell::mysleep ; sub mysleep { my($self, $sleep) = @_; if (CPAN->has_inst("Time::HiRes")) { Time::HiRes::sleep($sleep); } else { sleep($sleep < 1 ? 1 : int($sleep + 0.5)); } } #-> sub CPAN::Shell::setup_output ; sub setup_output { return if -t STDOUT; my $odef = select STDERR; $| = 1; select STDOUT; $| = 1; select $odef; } #-> sub CPAN::Shell::rematein ; # RE-adme||MA-ke||TE-st||IN-stall : nearly everything runs through here sub rematein { my $self = shift; my($meth,@some) = @_; my @pragma; while($meth =~ /^(ff?orce|notest)$/) { push @pragma, $meth; $meth = shift @some or $CPAN::Frontend->mydie("Pragma $pragma[-1] used without method: ". "cannot continue"); } setup_output(); CPAN->debug("pragma[@pragma]meth[$meth]some[@some]") if $CPAN::DEBUG; # Here is the place to set "test_count" on all involved parties to # 0. We then can pass this counter on to the involved # distributions and those can refuse to test if test_count > X. In # the first stab at it we could use a 1 for "X". # But when do I reset the distributions to start with 0 again? # Jost suggested to have a random or cycling interaction ID that # we pass through. But the ID is something that is just left lying # around in addition to the counter, so I'd prefer to set the # counter to 0 now, and repeat at the end of the loop. But what # about dependencies? They appear later and are not reset, they # enter the queue but not its copy. How do they get a sensible # test_count? # With configure_requires, "get" is vulnerable in recursion. my $needs_recursion_protection = "get|make|test|install"; # construct the queue my($s,@s,@qcopy); STHING: foreach $s (@some) { my $obj; if (ref $s) { CPAN->debug("s is an object[$s]") if $CPAN::DEBUG; $obj = $s; } elsif ($s =~ m|[\$\@\%]|) { # looks like a perl variable } elsif ($s =~ m|^/|) { # looks like a regexp if (substr($s,-1,1) eq ".") { $obj = CPAN::Shell->expandany($s); } else { $CPAN::Frontend->mywarn("Sorry, $meth with a regular expression is ". "not supported.\nRejecting argument '$s'\n"); $CPAN::Frontend->mysleep(2); next; } } elsif ($meth eq "ls") { $self->globls($s,\@pragma); next STHING; } else { CPAN->debug("calling expandany [$s]") if $CPAN::DEBUG; $obj = CPAN::Shell->expandany($s); } if (0) { } elsif (ref $obj) { if ($meth =~ /^($needs_recursion_protection)$/) { # it would be silly to check for recursion for look or dump # (we are in CPAN::Shell::rematein) CPAN->debug("Going to test against recursion") if $CPAN::DEBUG; eval { $obj->color_cmd_tmps(0,1); }; if ($@) { if (ref $@ and $@->isa("CPAN::Exception::RecursiveDependency")) { $CPAN::Frontend->mywarn($@); } else { if (0) { require Carp; Carp::confess(sprintf "DEBUG: \$\@[%s]ref[%s]", $@, ref $@); } die; } } } CPAN::Queue->queue_item(qmod => $obj->id, reqtype => "c"); push @qcopy, $obj; } elsif ($CPAN::META->exists('CPAN::Author',uc($s))) { $obj = $CPAN::META->instance('CPAN::Author',uc($s)); if ($meth =~ /^(dump|ls|reports)$/) { $obj->$meth(); } else { $CPAN::Frontend->mywarn( join "", "Don't be silly, you can't $meth ", $obj->fullname, " ;-)\n" ); $CPAN::Frontend->mysleep(2); } } elsif ($s =~ m|[\$\@\%]| && $meth eq "dump") { CPAN::InfoObj->dump($s); } else { $CPAN::Frontend ->mywarn(qq{Warning: Cannot $meth $s, }. qq{don't know what it is. Try the command i /$s/ to find objects with matching identifiers. }); $CPAN::Frontend->mysleep(2); } } # queuerunner (please be warned: when I started to change the # queue to hold objects instead of names, I made one or two # mistakes and never found which. I reverted back instead) while (my $q = CPAN::Queue->first) { my $obj; my $s = $q->as_string; my $reqtype = $q->reqtype || ""; $obj = CPAN::Shell->expandany($s); unless ($obj) { # don't know how this can happen, maybe we should panic, # but maybe we get a solution from the first user who hits # this unfortunate exception? $CPAN::Frontend->mywarn("Warning: Could not expand string '$s' ". "to an object. Skipping.\n"); $CPAN::Frontend->mysleep(5); CPAN::Queue->delete_first($s); next; } $obj->{reqtype} ||= ""; { # force debugging because CPAN::SQLite somehow delivers us # an empty object; # local $CPAN::DEBUG = 1024; # Shell; probably fixed now CPAN->debug("s[$s]obj-reqtype[$obj->{reqtype}]". "q-reqtype[$reqtype]") if $CPAN::DEBUG; } if ($obj->{reqtype}) { if ($obj->{reqtype} eq "b" && $reqtype =~ /^[rc]$/) { $obj->{reqtype} = $reqtype; if ( exists $obj->{install} && ( UNIVERSAL::can($obj->{install},"failed") ? $obj->{install}->failed : $obj->{install} =~ /^NO/ ) ) { delete $obj->{install}; $CPAN::Frontend->mywarn ("Promoting $obj->{ID} from 'build_requires' to 'requires'"); } } } else { $obj->{reqtype} = $reqtype; } for my $pragma (@pragma) { if ($pragma && $obj->can($pragma)) { $obj->$pragma($meth); } } if (UNIVERSAL::can($obj, 'called_for')) { $obj->called_for($s); } CPAN->debug(qq{pragma[@pragma]meth[$meth]}. qq{ID[$obj->{ID}]}) if $CPAN::DEBUG; push @qcopy, $obj; if ($meth =~ /^(report)$/) { # they came here with a pragma? $self->$meth($obj); } elsif (! UNIVERSAL::can($obj,$meth)) { # Must never happen my $serialized = ""; if (0) { } elsif ($CPAN::META->has_inst("YAML::Syck")) { $serialized = YAML::Syck::Dump($obj); } elsif ($CPAN::META->has_inst("YAML")) { $serialized = YAML::Dump($obj); } elsif ($CPAN::META->has_inst("Data::Dumper")) { $serialized = Data::Dumper::Dumper($obj); } else { require overload; $serialized = overload::StrVal($obj); } CPAN->debug("Going to panic. meth[$meth]s[$s]") if $CPAN::DEBUG; $CPAN::Frontend->mydie("Panic: obj[$serialized] cannot meth[$meth]"); } elsif ($obj->$meth()) { CPAN::Queue->delete($s); CPAN->debug("From queue deleted. meth[$meth]s[$s]") if $CPAN::DEBUG; } else { CPAN->debug("Failed. pragma[@pragma]meth[$meth]") if $CPAN::DEBUG; } $obj->undelay; for my $pragma (@pragma) { my $unpragma = "un$pragma"; if ($obj->can($unpragma)) { $obj->$unpragma(); } } CPAN::Queue->delete_first($s); } if ($meth =~ /^($needs_recursion_protection)$/) { for my $obj (@qcopy) { $obj->color_cmd_tmps(0,0); } } } #-> sub CPAN::Shell::recent ; sub recent { my($self) = @_; if ($CPAN::META->has_inst("XML::LibXML")) { my $url = $CPAN::Defaultrecent; $CPAN::Frontend->myprint("Going to fetch '$url'\n"); unless ($CPAN::META->has_usable("LWP")) { $CPAN::Frontend->mydie("LWP not installed; cannot continue"); } CPAN::LWP::UserAgent->config; my $Ua; eval { $Ua = CPAN::LWP::UserAgent->new; }; if ($@) { $CPAN::Frontend->mydie("CPAN::LWP::UserAgent->new dies with $@\n"); } my $resp = $Ua->get($url); unless ($resp->is_success) { $CPAN::Frontend->mydie(sprintf "Could not download '%s': %s\n", $url, $resp->code); } $CPAN::Frontend->myprint("DONE\n\n"); my $xml = XML::LibXML->new->parse_string($resp->content); if (0) { my $s = $xml->serialize(2); $s =~ s/\n\s*\n/\n/g; $CPAN::Frontend->myprint($s); return; } my @distros; if ($url =~ /winnipeg/) { my $pubdate = $xml->findvalue("/rss/channel/pubDate"); $CPAN::Frontend->myprint(" pubDate: $pubdate\n\n"); for my $eitem ($xml->findnodes("/rss/channel/item")) { my $distro = $eitem->findvalue("enclosure/\@url"); $distro =~ s|.*?/authors/id/./../||; my $size = $eitem->findvalue("enclosure/\@length"); my $desc = $eitem->findvalue("description"); $desc =~ s/.+? - //; $CPAN::Frontend->myprint("$distro [$size b]\n $desc\n"); push @distros, $distro; } } elsif ($url =~ /search.*uploads.rdf/) { # xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" # xmlns="http://purl.org/rss/1.0/" # xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" # xmlns:dc="http://purl.org/dc/elements/1.1/" # xmlns:syn="http://purl.org/rss/1.0/modules/syndication/" # xmlns:admin="http://webns.net/mvcb/" my $dc_date = $xml->findvalue("//*[local-name(.) = 'RDF']/*[local-name(.) = 'channel']/*[local-name(.) = 'date']"); $CPAN::Frontend->myprint(" dc:date: $dc_date\n\n"); my $finish_eitem = 0; local $SIG{INT} = sub { $finish_eitem = 1 }; EITEM: for my $eitem ($xml->findnodes("//*[local-name(.) = 'RDF']/*[local-name(.) = 'item']")) { my $distro = $eitem->findvalue("\@rdf:about"); $distro =~ s|.*~||; # remove up to the tilde before the name $distro =~ s|/$||; # remove trailing slash $distro =~ s|([^/]+)|\U$1\E|; # upcase the name my $author = uc $1 or die "distro[$distro] without author, cannot continue"; my $desc = $eitem->findvalue("*[local-name(.) = 'description']"); my $i = 0; SUBDIRTEST: while () { last SUBDIRTEST if ++$i >= 6; # half a dozen must do! if (my @ret = $self->globls("$distro*")) { @ret = grep {$_->[2] !~ /meta/} @ret; @ret = grep {length $_->[2]} @ret; if (@ret) { $distro = "$author/$ret[0][2]"; last SUBDIRTEST; } } $distro =~ s|/|/*/|; # allow it to reside in a subdirectory } next EITEM if $distro =~ m|\*|; # did not find the thing $CPAN::Frontend->myprint("____$desc\n"); push @distros, $distro; last EITEM if $finish_eitem; } } return \@distros; } else { # deprecated old version $CPAN::Frontend->mydie("no XML::LibXML installed, cannot continue\n"); } } #-> sub CPAN::Shell::smoke ; sub smoke { my($self) = @_; my $distros = $self->recent; DISTRO: for my $distro (@$distros) { $CPAN::Frontend->myprint(sprintf "Going to download and test '$distro'\n"); { my $skip = 0; local $SIG{INT} = sub { $skip = 1 }; for (0..9) { $CPAN::Frontend->myprint(sprintf "\r%2d (Hit ^C to skip)", 10-$_); sleep 1; if ($skip) { $CPAN::Frontend->myprint(" skipped\n"); next DISTRO; } } } $CPAN::Frontend->myprint("\r \n"); # leave the dirty line with a newline $self->test($distro); } } { # set up the dispatching methods no strict "refs"; for my $command (qw( clean cvs_import dump force fforce get install look ls make notest perldoc readme reports test )) { *$command = sub { shift->rematein($command, @_); }; } } package CPAN::LWP::UserAgent; use strict; sub config { return if $SETUPDONE; if ($CPAN::META->has_usable('LWP::UserAgent')) { require LWP::UserAgent; @ISA = qw(Exporter LWP::UserAgent); $SETUPDONE++; } else { $CPAN::Frontend->mywarn(" LWP::UserAgent not available\n"); } } sub get_basic_credentials { my($self, $realm, $uri, $proxy) = @_; if ($USER && $PASSWD) { return ($USER, $PASSWD); } if ( $proxy ) { ($USER,$PASSWD) = $self->get_proxy_credentials(); } else { ($USER,$PASSWD) = $self->get_non_proxy_credentials(); } return($USER,$PASSWD); } sub get_proxy_credentials { my $self = shift; my ($user, $password); if ( defined $CPAN::Config->{proxy_user} && defined $CPAN::Config->{proxy_pass}) { $user = $CPAN::Config->{proxy_user}; $password = $CPAN::Config->{proxy_pass}; return ($user, $password); } my $username_prompt = "\nProxy authentication needed! (Note: to permanently configure username and password run o conf proxy_user your_username o conf proxy_pass your_password )\nUsername:"; ($user, $password) = _get_username_and_password_from_user($username_prompt); return ($user,$password); } sub get_non_proxy_credentials { my $self = shift; my ($user,$password); if ( defined $CPAN::Config->{username} && defined $CPAN::Config->{password}) { $user = $CPAN::Config->{username}; $password = $CPAN::Config->{password}; return ($user, $password); } my $username_prompt = "\nAuthentication needed! (Note: to permanently configure username and password run o conf username your_username o conf password your_password )\nUsername:"; ($user, $password) = _get_username_and_password_from_user($username_prompt); return ($user,$password); } sub _get_username_and_password_from_user { my $username_message = shift; my ($username,$password); ExtUtils::MakeMaker->import(qw(prompt)); $username = prompt($username_message); if ($CPAN::META->has_inst("Term::ReadKey")) { Term::ReadKey::ReadMode("noecho"); } else { $CPAN::Frontend->mywarn( "Warning: Term::ReadKey seems not to be available, your password will be echoed to the terminal!\n" ); } $password = prompt("Password:"); if ($CPAN::META->has_inst("Term::ReadKey")) { Term::ReadKey::ReadMode("restore"); } $CPAN::Frontend->myprint("\n\n"); return ($username,$password); } # mirror(): Its purpose is to deal with proxy authentication. When we # call SUPER::mirror, we relly call the mirror method in # LWP::UserAgent. LWP::UserAgent will then call # $self->get_basic_credentials or some equivalent and this will be # $self->dispatched to our own get_basic_credentials method. # Our own get_basic_credentials sets $USER and $PASSWD, two globals. # 407 stands for HTTP_PROXY_AUTHENTICATION_REQUIRED. Which means # although we have gone through our get_basic_credentials, the proxy # server refuses to connect. This could be a case where the username or # password has changed in the meantime, so I'm trying once again without # $USER and $PASSWD to give the get_basic_credentials routine another # chance to set $USER and $PASSWD. # mirror(): Its purpose is to deal with proxy authentication. When we # call SUPER::mirror, we relly call the mirror method in # LWP::UserAgent. LWP::UserAgent will then call # $self->get_basic_credentials or some equivalent and this will be # $self->dispatched to our own get_basic_credentials method. # Our own get_basic_credentials sets $USER and $PASSWD, two globals. # 407 stands for HTTP_PROXY_AUTHENTICATION_REQUIRED. Which means # although we have gone through our get_basic_credentials, the proxy # server refuses to connect. This could be a case where the username or # password has changed in the meantime, so I'm trying once again without # $USER and $PASSWD to give the get_basic_credentials routine another # chance to set $USER and $PASSWD. sub mirror { my($self,$url,$aslocal) = @_; my $result = $self->SUPER::mirror($url,$aslocal); if ($result->code == 407) { undef $USER; undef $PASSWD; $result = $self->SUPER::mirror($url,$aslocal); } $result; } package CPAN::FTP; use strict; #-> sub CPAN::FTP::ftp_statistics # if they want to rewrite, they need to pass in a filehandle sub _ftp_statistics { my($self,$fh) = @_; my $locktype = $fh ? LOCK_EX : LOCK_SH; $fh ||= FileHandle->new; my $file = File::Spec->catfile($CPAN::Config->{cpan_home},"FTPstats.yml"); open $fh, "+>>$file" or $CPAN::Frontend->mydie("Could not open '$file': $!"); my $sleep = 1; my $waitstart; while (!CPAN::_flock($fh, $locktype|LOCK_NB)) { $waitstart ||= localtime(); if ($sleep>3) { $CPAN::Frontend->mywarn("Waiting for a read lock on '$file' (since $waitstart)\n"); } $CPAN::Frontend->mysleep($sleep); if ($sleep <= 3) { $sleep+=0.33; } elsif ($sleep <=6) { $sleep+=0.11; } } my $stats = eval { CPAN->_yaml_loadfile($file); }; if ($@) { if (ref $@) { if (ref $@ eq "CPAN::Exception::yaml_not_installed") { $CPAN::Frontend->myprint("Warning (usually harmless): $@"); return; } elsif (ref $@ eq "CPAN::Exception::yaml_process_error") { $CPAN::Frontend->mydie($@); } } else { $CPAN::Frontend->mydie($@); } } return $stats->[0]; } #-> sub CPAN::FTP::_mytime sub _mytime () { if (CPAN->has_inst("Time::HiRes")) { return Time::HiRes::time(); } else { return time; } } #-> sub CPAN::FTP::_new_stats sub _new_stats { my($self,$file) = @_; my $ret = { file => $file, attempts => [], start => _mytime, }; $ret; } #-> sub CPAN::FTP::_add_to_statistics sub _add_to_statistics { my($self,$stats) = @_; my $yaml_module = CPAN::_yaml_module; $self->debug("yaml_module[$yaml_module]") if $CPAN::DEBUG; if ($CPAN::META->has_inst($yaml_module)) { $stats->{thesiteurl} = $ThesiteURL; if (CPAN->has_inst("Time::HiRes")) { $stats->{end} = Time::HiRes::time(); } else { $stats->{end} = time; } my $fh = FileHandle->new; my $time = time; my $sdebug = 0; my @debug; @debug = $time if $sdebug; my $fullstats = $self->_ftp_statistics($fh); close $fh; $fullstats->{history} ||= []; push @debug, scalar @{$fullstats->{history}} if $sdebug; push @debug, time if $sdebug; push @{$fullstats->{history}}, $stats; # arbitrary hardcoded constants until somebody demands to have # them settable; YAML.pm 0.62 is unacceptably slow with 999; # YAML::Syck 0.82 has no noticable performance problem with 999; while ( @{$fullstats->{history}} > 99 || $time - $fullstats->{history}[0]{start} > 14*86400 ) { shift @{$fullstats->{history}} } push @debug, scalar @{$fullstats->{history}} if $sdebug; push @debug, time if $sdebug; push @debug, scalar localtime($fullstats->{history}[0]{start}) if $sdebug; # need no eval because if this fails, it is serious my $sfile = File::Spec->catfile($CPAN::Config->{cpan_home},"FTPstats.yml"); CPAN->_yaml_dumpfile("$sfile.$$",$fullstats); if ( $sdebug ) { local $CPAN::DEBUG = 512; # FTP push @debug, time; CPAN->debug(sprintf("DEBUG history: before_read[%d]before[%d]at[%d]". "after[%d]at[%d]oldest[%s]dumped backat[%d]", @debug, )); } # Win32 cannot rename a file to an existing filename unlink($sfile) if ($^O eq 'MSWin32'); rename "$sfile.$$", $sfile or $CPAN::Frontend->mydie("Could not rename '$sfile.$$' to '$sfile': $!\n"); } } # if file is CHECKSUMS, suggest the place where we got the file to be # checked from, maybe only for young files? #-> sub CPAN::FTP::_recommend_url_for sub _recommend_url_for { my($self, $file) = @_; my $urllist = $self->_get_urllist; if ($file =~ s|/CHECKSUMS(.gz)?$||) { my $fullstats = $self->_ftp_statistics(); my $history = $fullstats->{history} || []; while (my $last = pop @$history) { last if $last->{end} - time > 3600; # only young results are interesting next unless $last->{file}; # dirname of nothing dies! next unless $file eq File::Basename::dirname($last->{file}); return $last->{thesiteurl}; } } if ($CPAN::Config->{randomize_urllist} && rand(1) < $CPAN::Config->{randomize_urllist} ) { $urllist->[int rand scalar @$urllist]; } else { return (); } } #-> sub CPAN::FTP::_get_urllist sub _get_urllist { my($self) = @_; $CPAN::Config->{urllist} ||= []; unless (ref $CPAN::Config->{urllist} eq 'ARRAY') { $CPAN::Frontend->mywarn("Malformed urllist; ignoring. Configuration file corrupt?\n"); $CPAN::Config->{urllist} = []; } my @urllist = grep { defined $_ and length $_ } @{$CPAN::Config->{urllist}}; for my $u (@urllist) { CPAN->debug("u[$u]") if $CPAN::DEBUG; if (UNIVERSAL::can($u,"text")) { $u->{TEXT} .= "/" unless substr($u->{TEXT},-1) eq "/"; } else { $u .= "/" unless substr($u,-1) eq "/"; $u = CPAN::URL->new(TEXT => $u, FROM => "USER"); } } \@urllist; } #-> sub CPAN::FTP::ftp_get ; sub ftp_get { my($class,$host,$dir,$file,$target) = @_; $class->debug( qq[Going to fetch file [$file] from dir [$dir] on host [$host] as local [$target]\n] ) if $CPAN::DEBUG; my $ftp = Net::FTP->new($host); unless ($ftp) { $CPAN::Frontend->mywarn(" Could not connect to host '$host' with Net::FTP\n"); return; } return 0 unless defined $ftp; $ftp->debug(1) if $CPAN::DEBUG{'FTP'} & $CPAN::DEBUG; $class->debug(qq[Going to login("anonymous","$Config::Config{cf_email}")]); unless ( $ftp->login("anonymous",$Config::Config{'cf_email'}) ) { my $msg = $ftp->message; $CPAN::Frontend->mywarn(" Couldn't login on $host: $msg"); return; } unless ( $ftp->cwd($dir) ) { my $msg = $ftp->message; $CPAN::Frontend->mywarn(" Couldn't cwd $dir: $msg"); return; } $ftp->binary; $class->debug(qq[Going to ->get("$file","$target")\n]) if $CPAN::DEBUG; unless ( $ftp->get($file,$target) ) { my $msg = $ftp->message; $CPAN::Frontend->mywarn(" Couldn't fetch $file from $host: $msg"); return; } $ftp->quit; # it's ok if this fails return 1; } # If more accuracy is wanted/needed, Chris Leach sent me this patch... # > *** /install/perl/live/lib/CPAN.pm- Wed Sep 24 13:08:48 1997 # > --- /tmp/cp Wed Sep 24 13:26:40 1997 # > *************** # > *** 1562,1567 **** # > --- 1562,1580 ---- # > return 1 if substr($url,0,4) eq "file"; # > return 1 unless $url =~ m|://([^/]+)|; # > my $host = $1; # > + my $proxy = $CPAN::Config->{'http_proxy'} || $ENV{'http_proxy'}; # > + if ($proxy) { # > + $proxy =~ m|://([^/:]+)|; # > + $proxy = $1; # > + my $noproxy = $CPAN::Config->{'no_proxy'} || $ENV{'no_proxy'}; # > + if ($noproxy) { # > + if ($host !~ /$noproxy$/) { # > + $host = $proxy; # > + } # > + } else { # > + $host = $proxy; # > + } # > + } # > require Net::Ping; # > return 1 unless $Net::Ping::VERSION >= 2; # > my $p; #-> sub CPAN::FTP::localize ; sub localize { my($self,$file,$aslocal,$force) = @_; $force ||= 0; Carp::croak "Usage: ->localize(cpan_file,as_local_file[,$force])" unless defined $aslocal; $self->debug("file[$file] aslocal[$aslocal] force[$force]") if $CPAN::DEBUG; if ($^O eq 'MacOS') { # Comment by AK on 2000-09-03: Uniq short filenames would be # available in CHECKSUMS file my($name, $path) = File::Basename::fileparse($aslocal, ''); if (length($name) > 31) { $name =~ s/( \.( readme(\.(gz|Z))? | (tar\.)?(gz|Z) | tgz | zip | pm\.(gz|Z) ) )$//x; my $suf = $1; my $size = 31 - length($suf); while (length($name) > $size) { chop $name; } $name .= $suf; $aslocal = File::Spec->catfile($path, $name); } } if (-f $aslocal && -r _ && !($force & 1)) { my $size; if ($size = -s $aslocal) { $self->debug("aslocal[$aslocal]size[$size]") if $CPAN::DEBUG; return $aslocal; } else { # empty file from a previous unsuccessful attempt to download it unlink $aslocal or $CPAN::Frontend->mydie("Found a zero-length '$aslocal' that I ". "could not remove."); } } my($maybe_restore) = 0; if (-f $aslocal) { rename $aslocal, "$aslocal.bak$$"; $maybe_restore++; } my($aslocal_dir) = File::Basename::dirname($aslocal); $self->mymkpath($aslocal_dir); # too early for file URLs / RT #28438 # Inheritance is not easier to manage than a few if/else branches if ($CPAN::META->has_usable('LWP::UserAgent')) { unless ($Ua) { CPAN::LWP::UserAgent->config; eval {$Ua = CPAN::LWP::UserAgent->new;}; # Why is has_usable still not fit enough? if ($@) { $CPAN::Frontend->mywarn("CPAN::LWP::UserAgent->new dies with $@\n") if $CPAN::DEBUG; } else { my($var); $Ua->proxy('ftp', $var) if $var = $CPAN::Config->{ftp_proxy} || $ENV{ftp_proxy}; $Ua->proxy('http', $var) if $var = $CPAN::Config->{http_proxy} || $ENV{http_proxy}; $Ua->no_proxy($var) if $var = $CPAN::Config->{no_proxy} || $ENV{no_proxy}; } } } for my $prx (qw(ftp_proxy http_proxy no_proxy)) { $ENV{$prx} = $CPAN::Config->{$prx} if $CPAN::Config->{$prx}; } # Try the list of urls for each single object. We keep a record # where we did get a file from my(@reordered,$last); my $ccurllist = $self->_get_urllist; $last = $#$ccurllist; if ($force & 2) { # local cpans probably out of date, don't reorder @reordered = (0..$last); } else { @reordered = sort { (substr($ccurllist->[$b],0,4) eq "file") <=> (substr($ccurllist->[$a],0,4) eq "file") or defined($ThesiteURL) and ($ccurllist->[$b] eq $ThesiteURL) <=> ($ccurllist->[$a] eq $ThesiteURL) } 0..$last; } my(@levels); $Themethod ||= ""; $self->debug("Themethod[$Themethod]reordered[@reordered]") if $CPAN::DEBUG; my @all_levels = ( ["dleasy", "file"], ["dleasy"], ["dlhard"], ["dlhardest"], ["dleasy", "http","defaultsites"], ["dlhard", "http","defaultsites"], ["dleasy", "ftp", "defaultsites"], ["dlhard", "ftp", "defaultsites"], ["dlhardest","", "defaultsites"], ); if ($Themethod) { @levels = grep {$_->[0] eq $Themethod} @all_levels; push @levels, grep {$_->[0] ne $Themethod} @all_levels; } else { @levels = @all_levels; } @levels = qw/dleasy/ if $^O eq 'MacOS'; my($levelno); local $ENV{FTP_PASSIVE} = exists $CPAN::Config->{ftp_passive} ? $CPAN::Config->{ftp_passive} : 1; my $ret; my $stats = $self->_new_stats($file); LEVEL: for $levelno (0..$#levels) { my $level_tuple = $levels[$levelno]; my($level,$scheme,$sitetag) = @$level_tuple; my $defaultsites = $sitetag && $sitetag eq "defaultsites"; my @urllist; if ($defaultsites) { unless (defined $connect_to_internet_ok) { $CPAN::Frontend->myprint(sprintf qq{ I would like to connect to one of the following sites to get '%s': %s }, $file, join("",map { " ".$_->text."\n" } @CPAN::Defaultsites), ); my $answer = CPAN::Shell::colorable_makemaker_prompt("Is it OK to try to connect to the Internet?", "yes"); if ($answer =~ /^y/i) { $connect_to_internet_ok = 1; } else { $connect_to_internet_ok = 0; } } if ($connect_to_internet_ok) { @urllist = @CPAN::Defaultsites; } else { @urllist = (); } } else { my @host_seq = $level =~ /dleasy/ ? @reordered : 0..$last; # reordered has file and $Thesiteurl first @urllist = map { $ccurllist->[$_] } @host_seq; } $self->debug("synth. urllist[@urllist]") if $CPAN::DEBUG; my $aslocal_tempfile = $aslocal . ".tmp" . $$; if (my $recommend = $self->_recommend_url_for($file)) { @urllist = grep { $_ ne $recommend } @urllist; unshift @urllist, $recommend; } $self->debug("synth. urllist[@urllist]") if $CPAN::DEBUG; $ret = $self->hostdlxxx($level,$scheme,\@urllist,$file,$aslocal_tempfile,$stats); if ($ret) { CPAN->debug("ret[$ret]aslocal[$aslocal]") if $CPAN::DEBUG; if ($ret eq $aslocal_tempfile) { # if we got it exactly as we asked for, only then we # want to rename rename $aslocal_tempfile, $aslocal or $CPAN::Frontend->mydie("Error while trying to rename ". "'$ret' to '$aslocal': $!"); $ret = $aslocal; } $Themethod = $level; my $now = time; # utime $now, $now, $aslocal; # too bad, if we do that, we # might alter a local mirror $self->debug("level[$level]") if $CPAN::DEBUG; last LEVEL; } else { unlink $aslocal_tempfile; last if $CPAN::Signal; # need to cleanup } } if ($ret) { $stats->{filesize} = -s $ret; } $self->debug("before _add_to_statistics") if $CPAN::DEBUG; $self->_add_to_statistics($stats); $self->debug("after _add_to_statistics") if $CPAN::DEBUG; if ($ret) { unlink "$aslocal.bak$$"; return $ret; } unless ($CPAN::Signal) { my(@mess); local $" = " "; if (@{$CPAN::Config->{urllist}}) { push @mess, qq{Please check, if the URLs I found in your configuration file \(}. join(", ", @{$CPAN::Config->{urllist}}). qq{\) are valid.}; } else { push @mess, qq{Your urllist is empty!}; } push @mess, qq{The urllist can be edited.}, qq{E.g. with 'o conf urllist push ftp://myurl/'}; $CPAN::Frontend->mywarn(Text::Wrap::wrap("","","@mess"). "\n\n"); $CPAN::Frontend->mywarn("Could not fetch $file\n"); $CPAN::Frontend->mysleep(2); } if ($maybe_restore) { rename "$aslocal.bak$$", $aslocal; $CPAN::Frontend->myprint("Trying to get away with old file:\n" . $self->ls($aslocal)); return $aslocal; } return; } sub mymkpath { my($self, $aslocal_dir) = @_; File::Path::mkpath($aslocal_dir); $CPAN::Frontend->mywarn(qq{Warning: You are not allowed to write into }. qq{directory "$aslocal_dir". I\'ll continue, but if you encounter problems, they may be due to insufficient permissions.\n}) unless -w $aslocal_dir; } sub hostdlxxx { my $self = shift; my $level = shift; my $scheme = shift; my $h = shift; $h = [ grep /^\Q$scheme\E:/, @$h ] if $scheme; my $method = "host$level"; $self->$method($h, @_); } sub _set_attempt { my($self,$stats,$method,$url) = @_; push @{$stats->{attempts}}, { method => $method, start => _mytime, url => $url, }; } # package CPAN::FTP; sub hostdleasy { my($self,$host_seq,$file,$aslocal,$stats) = @_; my($ro_url); HOSTEASY: for $ro_url (@$host_seq) { $self->_set_attempt($stats,"dleasy",$ro_url); my $url .= "$ro_url$file"; $self->debug("localizing perlish[$url]") if $CPAN::DEBUG; if ($url =~ /^file:/) { my $l; if ($CPAN::META->has_inst('URI::URL')) { my $u = URI::URL->new($url); $l = $u->path; } else { # works only on Unix, is poorly constructed, but # hopefully better than nothing. # RFC 1738 says fileurl BNF is # fileurl = "file://" [ host | "localhost" ] "/" fpath # Thanks to "Mark D. Baushke" <mdb@cisco.com> for # the code ($l = $url) =~ s|^file://[^/]*/|/|; # discard the host part $l =~ s|^file:||; # assume they # meant # file://localhost $l =~ s|^/||s if ! -f $l && $l =~ m|^/\w:|; # e.g. /P: } $self->debug("local file[$l]") if $CPAN::DEBUG; if ( -f $l && -r _) { $ThesiteURL = $ro_url; return $l; } if ($l =~ /(.+)\.gz$/) { my $ungz = $1; if ( -f $ungz && -r _) { $ThesiteURL = $ro_url; return $ungz; } } # Maybe mirror has compressed it? if (-f "$l.gz") { $self->debug("found compressed $l.gz") if $CPAN::DEBUG; eval { CPAN::Tarzip->new("$l.gz")->gunzip($aslocal) }; if ( -f $aslocal) { $ThesiteURL = $ro_url; return $aslocal; } } $CPAN::Frontend->mywarn("Could not find '$l'\n"); } $self->debug("it was not a file URL") if $CPAN::DEBUG; if ($CPAN::META->has_usable('LWP')) { $CPAN::Frontend->myprint("Fetching with LWP: $url "); unless ($Ua) { CPAN::LWP::UserAgent->config; eval { $Ua = CPAN::LWP::UserAgent->new; }; if ($@) { $CPAN::Frontend->mywarn("CPAN::LWP::UserAgent->new dies with $@\n"); } } my $res = $Ua->mirror($url, $aslocal); if ($res->is_success) { $ThesiteURL = $ro_url; my $now = time; utime $now, $now, $aslocal; # download time is more # important than upload # time return $aslocal; } elsif ($url !~ /\.gz(?!\n)\Z/) { my $gzurl = "$url.gz"; $CPAN::Frontend->myprint("Fetching with LWP: $gzurl "); $res = $Ua->mirror($gzurl, "$aslocal.gz"); if ($res->is_success) { if (eval {CPAN::Tarzip->new("$aslocal.gz")->gunzip($aslocal)}) { $ThesiteURL = $ro_url; return $aslocal; } } } else { $CPAN::Frontend->myprint(sprintf( "LWP failed with code[%s] message[%s]\n", $res->code, $res->message, )); # Alan Burlison informed me that in firewall environments # Net::FTP can still succeed where LWP fails. So we do not # skip Net::FTP anymore when LWP is available. } } else { $CPAN::Frontend->mywarn(" LWP not available\n"); } return if $CPAN::Signal; if ($url =~ m|^ftp://(.*?)/(.*)/(.*)|) { # that's the nice and easy way thanks to Graham $self->debug("recognized ftp") if $CPAN::DEBUG; my($host,$dir,$getfile) = ($1,$2,$3); if ($CPAN::META->has_usable('Net::FTP')) { $dir =~ s|/+|/|g; $CPAN::Frontend->myprint("Fetching with Net::FTP: $url "); $self->debug("getfile[$getfile]dir[$dir]host[$host]" . "aslocal[$aslocal]") if $CPAN::DEBUG; if (CPAN::FTP->ftp_get($host,$dir,$getfile,$aslocal)) { $ThesiteURL = $ro_url; return $aslocal; } if ($aslocal !~ /\.gz(?!\n)\Z/) { my $gz = "$aslocal.gz"; $CPAN::Frontend->myprint("Fetching with Net::FTP $url.gz "); if (CPAN::FTP->ftp_get($host, $dir, "$getfile.gz", $gz) && eval{CPAN::Tarzip->new($gz)->gunzip($aslocal)} ) { $ThesiteURL = $ro_url; return $aslocal; } } # next HOSTEASY; } else { CPAN->debug("Net::FTP does not count as usable atm") if $CPAN::DEBUG; } } if ( UNIVERSAL::can($ro_url,"text") and $ro_url->{FROM} eq "USER" ) { ##address #17973: default URLs should not try to override ##user-defined URLs just because LWP is not available my $ret = $self->hostdlhard([$ro_url],$file,$aslocal,$stats); return $ret if $ret; } return if $CPAN::Signal; } } # package CPAN::FTP; sub hostdlhard { my($self,$host_seq,$file,$aslocal,$stats) = @_; # Came back if Net::FTP couldn't establish connection (or # failed otherwise) Maybe they are behind a firewall, but they # gave us a socksified (or other) ftp program... my($ro_url); my($devnull) = $CPAN::Config->{devnull} || ""; # < /dev/null "; my($aslocal_dir) = File::Basename::dirname($aslocal); File::Path::mkpath($aslocal_dir); HOSTHARD: for $ro_url (@$host_seq) { $self->_set_attempt($stats,"dlhard",$ro_url); my $url = "$ro_url$file"; my($proto,$host,$dir,$getfile); # Courtesy Mark Conty mark_conty@cargill.com change from # if ($url =~ m|^ftp://(.*?)/(.*)/(.*)|) { # to if ($url =~ m|^([^:]+)://(.*?)/(.*)/(.*)|) { # proto not yet used ($proto,$host,$dir,$getfile) = ($1,$2,$3,$4); } else { next HOSTHARD; # who said, we could ftp anything except ftp? } next HOSTHARD if $proto eq "file"; # file URLs would have had # success above. Likely a bogus URL $self->debug("localizing funkyftpwise[$url]") if $CPAN::DEBUG; # Try the most capable first and leave ncftp* for last as it only # does FTP. DLPRG: for my $f (qw(curl wget lynx ncftpget ncftp)) { my $funkyftp = CPAN::HandleConfig->safe_quote($CPAN::Config->{$f}); next unless defined $funkyftp; next if $funkyftp =~ /^\s*$/; my($asl_ungz, $asl_gz); ($asl_ungz = $aslocal) =~ s/\.gz//; $asl_gz = "$asl_ungz.gz"; my($src_switch) = ""; my($chdir) = ""; my($stdout_redir) = " > $asl_ungz"; if ($f eq "lynx") { $src_switch = " -source"; } elsif ($f eq "ncftp") { $src_switch = " -c"; } elsif ($f eq "wget") { $src_switch = " -O $asl_ungz"; $stdout_redir = ""; } elsif ($f eq 'curl') { $src_switch = ' -L -f -s -S --netrc-optional'; } if ($f eq "ncftpget") { $chdir = "cd $aslocal_dir && "; $stdout_redir = ""; } $CPAN::Frontend->myprint( qq[ Trying with "$funkyftp$src_switch" to get $url ]); my($system) = "$chdir$funkyftp$src_switch \"$url\" $devnull$stdout_redir"; $self->debug("system[$system]") if $CPAN::DEBUG; my($wstatus) = system($system); if ($f eq "lynx") { # lynx returns 0 when it fails somewhere if (-s $asl_ungz) { my $content = do { local *FH; open FH, $asl_ungz or die; local $/; <FH> }; if ($content =~ /^<.*(<title>[45]|Error [45])/si) { $CPAN::Frontend->mywarn(qq{ No success, the file that lynx has downloaded looks like an error message: $content }); $CPAN::Frontend->mysleep(1); next DLPRG; } } else { $CPAN::Frontend->myprint(qq{ No success, the file that lynx has downloaded is an empty file. }); next DLPRG; } } if ($wstatus == 0) { if (-s $aslocal) { # Looks good } elsif ($asl_ungz ne $aslocal) { # test gzip integrity if (eval{CPAN::Tarzip->new($asl_ungz)->gtest}) { # e.g. foo.tar is gzipped --> foo.tar.gz rename $asl_ungz, $aslocal; } else { eval{CPAN::Tarzip->new($asl_gz)->gzip($asl_ungz)}; } } $ThesiteURL = $ro_url; return $aslocal; } elsif ($url !~ /\.gz(?!\n)\Z/) { unlink $asl_ungz if -f $asl_ungz && -s _ == 0; my $gz = "$aslocal.gz"; my $gzurl = "$url.gz"; $CPAN::Frontend->myprint( qq[ Trying with "$funkyftp$src_switch" to get $url.gz ]); my($system) = "$funkyftp$src_switch \"$url.gz\" $devnull > $asl_gz"; $self->debug("system[$system]") if $CPAN::DEBUG; my($wstatus); if (($wstatus = system($system)) == 0 && -s $asl_gz ) { # test gzip integrity my $ct = eval{CPAN::Tarzip->new($asl_gz)}; if ($ct && $ct->gtest) { $ct->gunzip($aslocal); } else { # somebody uncompressed file for us? rename $asl_ungz, $aslocal; } $ThesiteURL = $ro_url; return $aslocal; } else { unlink $asl_gz if -f $asl_gz; } } else { my $estatus = $wstatus >> 8; my $size = -f $aslocal ? ", left\n$aslocal with size ".-s _ : "\nWarning: expected file [$aslocal] doesn't exist"; $CPAN::Frontend->myprint(qq{ System call "$system" returned status $estatus (wstat $wstatus)$size }); } return if $CPAN::Signal; } # transfer programs } # host } # package CPAN::FTP; sub hostdlhardest { my($self,$host_seq,$file,$aslocal,$stats) = @_; return unless @$host_seq; my($ro_url); my($aslocal_dir) = File::Basename::dirname($aslocal); File::Path::mkpath($aslocal_dir); my $ftpbin = $CPAN::Config->{ftp}; unless ($ftpbin && length $ftpbin && MM->maybe_command($ftpbin)) { $CPAN::Frontend->myprint("No external ftp command available\n\n"); return; } $CPAN::Frontend->mywarn(qq{ As a last ressort we now switch to the external ftp command '$ftpbin' to get '$aslocal'. Doing so often leads to problems that are hard to diagnose. If you're victim of such problems, please consider unsetting the ftp config variable with o conf ftp "" o conf commit }); $CPAN::Frontend->mysleep(2); HOSTHARDEST: for $ro_url (@$host_seq) { $self->_set_attempt($stats,"dlhardest",$ro_url); my $url = "$ro_url$file"; $self->debug("localizing ftpwise[$url]") if $CPAN::DEBUG; unless ($url =~ m|^ftp://(.*?)/(.*)/(.*)|) { next; } my($host,$dir,$getfile) = ($1,$2,$3); my $timestamp = 0; my($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime, $ctime,$blksize,$blocks) = stat($aslocal); $timestamp = $mtime ||= 0; my($netrc) = CPAN::FTP::netrc->new; my($netrcfile) = $netrc->netrc; my($verbose) = $CPAN::DEBUG{'FTP'} & $CPAN::DEBUG ? " -v" : ""; my $targetfile = File::Basename::basename($aslocal); my(@dialog); push( @dialog, "lcd $aslocal_dir", "cd /", map("cd $_", split /\//, $dir), # RFC 1738 "bin", "get $getfile $targetfile", "quit" ); if (! $netrcfile) { CPAN->debug("No ~/.netrc file found") if $CPAN::DEBUG; } elsif ($netrc->hasdefault || $netrc->contains($host)) { CPAN->debug(sprintf("hasdef[%d]cont($host)[%d]", $netrc->hasdefault, $netrc->contains($host))) if $CPAN::DEBUG; if ($netrc->protected) { my $dialog = join "", map { " $_\n" } @dialog; my $netrc_explain; if ($netrc->contains($host)) { $netrc_explain = "Relying that your .netrc entry for '$host' ". "manages the login"; } else { $netrc_explain = "Relying that your default .netrc entry ". "manages the login"; } $CPAN::Frontend->myprint(qq{ Trying with external ftp to get $url $netrc_explain Going to send the dialog $dialog } ); $self->talk_ftp("$ftpbin$verbose $host", @dialog); ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat($aslocal); $mtime ||= 0; if ($mtime > $timestamp) { $CPAN::Frontend->myprint("GOT $aslocal\n"); $ThesiteURL = $ro_url; return $aslocal; } else { $CPAN::Frontend->myprint("Hmm... Still failed!\n"); } return if $CPAN::Signal; } else { $CPAN::Frontend->mywarn(qq{Your $netrcfile is not }. qq{correctly protected.\n}); } } else { $CPAN::Frontend->mywarn("Your ~/.netrc neither contains $host nor does it have a default entry\n"); } # OK, they don't have a valid ~/.netrc. Use 'ftp -n' # then and login manually to host, using e-mail as # password. $CPAN::Frontend->myprint(qq{Issuing "$ftpbin$verbose -n"\n}); unshift( @dialog, "open $host", "user anonymous $Config::Config{'cf_email'}" ); my $dialog = join "", map { " $_\n" } @dialog; $CPAN::Frontend->myprint(qq{ Trying with external ftp to get $url Going to send the dialog $dialog } ); $self->talk_ftp("$ftpbin$verbose -n", @dialog); ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat($aslocal); $mtime ||= 0; if ($mtime > $timestamp) { $CPAN::Frontend->myprint("GOT $aslocal\n"); $ThesiteURL = $ro_url; return $aslocal; } else { $CPAN::Frontend->myprint("Bad luck... Still failed!\n"); } return if $CPAN::Signal; $CPAN::Frontend->mywarn("Can't access URL $url.\n\n"); $CPAN::Frontend->mysleep(2); } # host } # package CPAN::FTP; sub talk_ftp { my($self,$command,@dialog) = @_; my $fh = FileHandle->new; $fh->open("|$command") or die "Couldn't open ftp: $!"; foreach (@dialog) { $fh->print("$_\n") } $fh->close; # Wait for process to complete my $wstatus = $?; my $estatus = $wstatus >> 8; $CPAN::Frontend->myprint(qq{ Subprocess "|$command" returned status $estatus (wstat $wstatus) }) if $wstatus; } # find2perl needs modularization, too, all the following is stolen # from there # CPAN::FTP::ls sub ls { my($self,$name) = @_; my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$sizemm, $atime,$mtime,$ctime,$blksize,$blocks) = lstat($name); my($perms,%user,%group); my $pname = $name; if ($blocks) { $blocks = int(($blocks + 1) / 2); } else { $blocks = int(($sizemm + 1023) / 1024); } if (-f _) { $perms = '-'; } elsif (-d _) { $perms = 'd'; } elsif (-c _) { $perms = 'c'; $sizemm = &sizemm; } elsif (-b _) { $perms = 'b'; $sizemm = &sizemm; } elsif (-p _) { $perms = 'p'; } elsif (-S _) { $perms = 's'; } else { $perms = 'l'; $pname .= ' -> ' . readlink($_); } my(@rwx) = ('---','--x','-w-','-wx','r--','r-x','rw-','rwx'); my(@moname) = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); my $tmpmode = $mode; my $tmp = $rwx[$tmpmode & 7]; $tmpmode >>= 3; $tmp = $rwx[$tmpmode & 7] . $tmp; $tmpmode >>= 3; $tmp = $rwx[$tmpmode & 7] . $tmp; substr($tmp,2,1) =~ tr/-x/Ss/ if -u _; substr($tmp,5,1) =~ tr/-x/Ss/ if -g _; substr($tmp,8,1) =~ tr/-x/Tt/ if -k _; $perms .= $tmp; my $user = $user{$uid} || $uid; # too lazy to implement lookup my $group = $group{$gid} || $gid; my($sec,$min,$hour,$mday,$mon,$year) = localtime($mtime); my($timeyear); my($moname) = $moname[$mon]; if (-M _ > 365.25 / 2) { $timeyear = $year + 1900; } else { $timeyear = sprintf("%02d:%02d", $hour, $min); } sprintf "%5lu %4ld %-10s %2d %-8s %-8s %8s %s %2d %5s %s\n", $ino, $blocks, $perms, $nlink, $user, $group, $sizemm, $moname, $mday, $timeyear, $pname; } package CPAN::FTP::netrc; use strict; # package CPAN::FTP::netrc; sub new { my($class) = @_; my $home = CPAN::HandleConfig::home; my $file = File::Spec->catfile($home,".netrc"); my($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat($file); $mode ||= 0; my $protected = 0; my($fh,@machines,$hasdefault); $hasdefault = 0; $fh = FileHandle->new or die "Could not create a filehandle"; if($fh->open($file)) { $protected = ($mode & 077) == 0; local($/) = ""; NETRC: while (<$fh>) { my(@tokens) = split " ", $_; TOKEN: while (@tokens) { my($t) = shift @tokens; if ($t eq "default") { $hasdefault++; last NETRC; } last TOKEN if $t eq "macdef"; if ($t eq "machine") { push @machines, shift @tokens; } } } } else { $file = $hasdefault = $protected = ""; } bless { 'mach' => [@machines], 'netrc' => $file, 'hasdefault' => $hasdefault, 'protected' => $protected, }, $class; } # CPAN::FTP::netrc::hasdefault; sub hasdefault { shift->{'hasdefault'} } sub netrc { shift->{'netrc'} } sub protected { shift->{'protected'} } sub contains { my($self,$mach) = @_; for ( @{$self->{'mach'}} ) { return 1 if $_ eq $mach; } return 0; } package CPAN::Complete; use strict; sub gnu_cpl { my($text, $line, $start, $end) = @_; my(@perlret) = cpl($text, $line, $start); # find longest common match. Can anybody show me how to peruse # T::R::Gnu to have this done automatically? Seems expensive. return () unless @perlret; my($newtext) = $text; for (my $i = length($text)+1;;$i++) { last unless length($perlret[0]) && length($perlret[0]) >= $i; my $try = substr($perlret[0],0,$i); my @tries = grep {substr($_,0,$i) eq $try} @perlret; # warn "try[$try]tries[@tries]"; if (@tries == @perlret) { $newtext = $try; } else { last; } } ($newtext,@perlret); } #-> sub CPAN::Complete::cpl ; sub cpl { my($word,$line,$pos) = @_; $word ||= ""; $line ||= ""; $pos ||= 0; CPAN->debug("word [$word] line[$line] pos[$pos]") if $CPAN::DEBUG; $line =~ s/^\s*//; if ($line =~ s/^((?:notest|f?force)\s*)//) { $pos -= length($1); } my @return; if ($pos == 0 || $line =~ /^(?:h(?:elp)?|\?)\s/) { @return = grep /^\Q$word\E/, @CPAN::Complete::COMMANDS; } elsif ( $line !~ /^[\!abcdghimorutl]/ ) { @return = (); } elsif ($line =~ /^(a|ls)\s/) { @return = cplx('CPAN::Author',uc($word)); } elsif ($line =~ /^b\s/) { CPAN::Shell->local_bundles; @return = cplx('CPAN::Bundle',$word); } elsif ($line =~ /^d\s/) { @return = cplx('CPAN::Distribution',$word); } elsif ($line =~ m/^( [mru]|make|clean|dump|get|test|install|readme|look|cvs_import|perldoc|recent )\s/x ) { if ($word =~ /^Bundle::/) { CPAN::Shell->local_bundles; } @return = (cplx('CPAN::Module',$word),cplx('CPAN::Bundle',$word)); } elsif ($line =~ /^i\s/) { @return = cpl_any($word); } elsif ($line =~ /^reload\s/) { @return = cpl_reload($word,$line,$pos); } elsif ($line =~ /^o\s/) { @return = cpl_option($word,$line,$pos); } elsif ($line =~ m/^\S+\s/ ) { # fallback for future commands and what we have forgotten above @return = (cplx('CPAN::Module',$word),cplx('CPAN::Bundle',$word)); } else { @return = (); } return @return; } #-> sub CPAN::Complete::cplx ; sub cplx { my($class, $word) = @_; if (CPAN::_sqlite_running) { $CPAN::SQLite->search($class, "^\Q$word\E"); } sort grep /^\Q$word\E/, map { $_->id } $CPAN::META->all_objects($class); } #-> sub CPAN::Complete::cpl_any ; sub cpl_any { my($word) = shift; return ( cplx('CPAN::Author',$word), cplx('CPAN::Bundle',$word), cplx('CPAN::Distribution',$word), cplx('CPAN::Module',$word), ); } #-> sub CPAN::Complete::cpl_reload ; sub cpl_reload { my($word,$line,$pos) = @_; $word ||= ""; my(@words) = split " ", $line; CPAN->debug("word[$word] line[$line] pos[$pos]") if $CPAN::DEBUG; my(@ok) = qw(cpan index); return @ok if @words == 1; return grep /^\Q$word\E/, @ok if @words == 2 && $word; } #-> sub CPAN::Complete::cpl_option ; sub cpl_option { my($word,$line,$pos) = @_; $word ||= ""; my(@words) = split " ", $line; CPAN->debug("word[$word] line[$line] pos[$pos]") if $CPAN::DEBUG; my(@ok) = qw(conf debug); return @ok if @words == 1; return grep /^\Q$word\E/, @ok if @words == 2 && length($word); if (0) { } elsif ($words[1] eq 'index') { return (); } elsif ($words[1] eq 'conf') { return CPAN::HandleConfig::cpl(@_); } elsif ($words[1] eq 'debug') { return sort grep /^\Q$word\E/i, sort keys %CPAN::DEBUG, 'all'; } } package CPAN::Index; use strict; #-> sub CPAN::Index::force_reload ; sub force_reload { my($class) = @_; $CPAN::Index::LAST_TIME = 0; $class->reload(1); } #-> sub CPAN::Index::reload ; sub reload { my($self,$force) = @_; my $time = time; # XXX check if a newer one is available. (We currently read it # from time to time) for ($CPAN::Config->{index_expire}) { $_ = 0.001 unless $_ && $_ > 0.001; } unless (1 || $CPAN::Have_warned->{readmetadatacache}++) { # debug here when CPAN doesn't seem to read the Metadata require Carp; Carp::cluck("META-PROTOCOL[$CPAN::META->{PROTOCOL}]"); } unless ($CPAN::META->{PROTOCOL}) { $self->read_metadata_cache; $CPAN::META->{PROTOCOL} ||= "1.0"; } if ( $CPAN::META->{PROTOCOL} < PROTOCOL ) { # warn "Setting last_time to 0"; $LAST_TIME = 0; # No warning necessary } if ($LAST_TIME + $CPAN::Config->{index_expire}*86400 > $time and ! $force) { # called too often # CPAN->debug("LAST_TIME[$LAST_TIME]index_expire[$CPAN::Config->{index_expire}]time[$time]"); } elsif (0) { # IFF we are developing, it helps to wipe out the memory # between reloads, otherwise it is not what a user expects. undef $CPAN::META; # Neue Gruendlichkeit since v1.52(r1.274) $CPAN::META = CPAN->new; } else { my($debug,$t2); local $LAST_TIME = $time; local $CPAN::META->{PROTOCOL} = PROTOCOL; my $needshort = $^O eq "dos"; $self->rd_authindex($self ->reload_x( "authors/01mailrc.txt.gz", $needshort ? File::Spec->catfile('authors', '01mailrc.gz') : File::Spec->catfile('authors', '01mailrc.txt.gz'), $force)); $t2 = time; $debug = "timing reading 01[".($t2 - $time)."]"; $time = $t2; return if $CPAN::Signal; # this is sometimes lengthy $self->rd_modpacks($self ->reload_x( "modules/02packages.details.txt.gz", $needshort ? File::Spec->catfile('modules', '02packag.gz') : File::Spec->catfile('modules', '02packages.details.txt.gz'), $force)); $t2 = time; $debug .= "02[".($t2 - $time)."]"; $time = $t2; return if $CPAN::Signal; # this is sometimes lengthy $self->rd_modlist($self ->reload_x( "modules/03modlist.data.gz", $needshort ? File::Spec->catfile('modules', '03mlist.gz') : File::Spec->catfile('modules', '03modlist.data.gz'), $force)); $self->write_metadata_cache; $t2 = time; $debug .= "03[".($t2 - $time)."]"; $time = $t2; CPAN->debug($debug) if $CPAN::DEBUG; } if ($CPAN::Config->{build_dir_reuse}) { $self->reanimate_build_dir; } if (CPAN::_sqlite_running) { $CPAN::SQLite->reload(time => $time, force => $force) if not $LAST_TIME; } $LAST_TIME = $time; $CPAN::META->{PROTOCOL} = PROTOCOL; } #-> sub CPAN::Index::reanimate_build_dir ; sub reanimate_build_dir { my($self) = @_; unless ($CPAN::META->has_inst($CPAN::Config->{yaml_module}||"YAML")) { return; } return if $HAVE_REANIMATED++; my $d = $CPAN::Config->{build_dir}; my $dh = DirHandle->new; opendir $dh, $d or return; # does not exist my $dirent; my $i = 0; my $painted = 0; my $restored = 0; $CPAN::Frontend->myprint("Going to read $CPAN::Config->{build_dir}/\n"); my @candidates = map { $_->[0] } sort { $b->[1] <=> $a->[1] } map { [ $_, -M File::Spec->catfile($d,$_) ] } grep {/\.yml$/} readdir $dh; DISTRO: for $i (0..$#candidates) { my $dirent = $candidates[$i]; my $y = eval {CPAN->_yaml_loadfile(File::Spec->catfile($d,$dirent))}; if ($@) { warn "Error while parsing file '$dirent'; error: '$@'"; next DISTRO; } my $c = $y->[0]; if ($c && CPAN->_perl_fingerprint($c->{perl})) { my $key = $c->{distribution}{ID}; for my $k (keys %{$c->{distribution}}) { if ($c->{distribution}{$k} && ref $c->{distribution}{$k} && UNIVERSAL::isa($c->{distribution}{$k},"CPAN::Distrostatus")) { $c->{distribution}{$k}{COMMANDID} = $i - @candidates; } } #we tried to restore only if element already #exists; but then we do not work with metadata #turned off. my $do = $CPAN::META->{readwrite}{'CPAN::Distribution'}{$key} = $c->{distribution}; for my $skipper (qw( badtestcnt configure_requires_later configure_requires_later_for force_update later later_for notest should_report sponsored_mods )) { delete $do->{$skipper}; } # $DB::single = 1; if ($do->{make_test} && $do->{build_dir} && !(UNIVERSAL::can($do->{make_test},"failed") ? $do->{make_test}->failed : $do->{make_test} =~ /^YES/ ) && ( !$do->{install} || $do->{install}->failed ) ) { $CPAN::META->is_tested($do->{build_dir},$do->{make_test}{TIME}); } $restored++; } $i++; while (($painted/76) < ($i/@candidates)) { $CPAN::Frontend->myprint("."); $painted++; } } $CPAN::Frontend->myprint(sprintf( "DONE\nFound %s old build%s, restored the state of %s\n", @candidates ? sprintf("%d",scalar @candidates) : "no", @candidates==1 ? "" : "s", $restored || "none", )); } #-> sub CPAN::Index::reload_x ; sub reload_x { my($cl,$wanted,$localname,$force) = @_; $force |= 2; # means we're dealing with an index here CPAN::HandleConfig->load; # we should guarantee loading wherever # we rely on Config XXX $localname ||= $wanted; my $abs_wanted = File::Spec->catfile($CPAN::Config->{'keep_source_where'}, $localname); if ( -f $abs_wanted && -M $abs_wanted < $CPAN::Config->{'index_expire'} && !($force & 1) ) { my $s = $CPAN::Config->{'index_expire'} == 1 ? "" : "s"; $cl->debug(qq{$abs_wanted younger than $CPAN::Config->{'index_expire'} }. qq{day$s. I\'ll use that.}); return $abs_wanted; } else { $force |= 1; # means we're quite serious about it. } return CPAN::FTP->localize($wanted,$abs_wanted,$force); } #-> sub CPAN::Index::rd_authindex ; sub rd_authindex { my($cl, $index_target) = @_; return unless defined $index_target; return if CPAN::_sqlite_running; my @lines; $CPAN::Frontend->myprint("Going to read $index_target\n"); local(*FH); tie *FH, 'CPAN::Tarzip', $index_target; local($/) = "\n"; local($_); push @lines, split /\012/ while <FH>; my $i = 0; my $painted = 0; foreach (@lines) { my($userid,$fullname,$email) = m/alias\s+(\S+)\s+\"([^\"\<]*)\s+\<(.*)\>\"/; $fullname ||= $email; if ($userid && $fullname && $email) { my $userobj = $CPAN::META->instance('CPAN::Author',$userid); $userobj->set('FULLNAME' => $fullname, 'EMAIL' => $email); } else { CPAN->debug(sprintf "line[%s]", $_) if $CPAN::DEBUG; } $i++; while (($painted/76) < ($i/@lines)) { $CPAN::Frontend->myprint("."); $painted++; } return if $CPAN::Signal; } $CPAN::Frontend->myprint("DONE\n"); } sub userid { my($self,$dist) = @_; $dist = $self->{'id'} unless defined $dist; my($ret) = $dist =~ m|(?:\w/\w\w/)?([^/]+)/|; $ret; } #-> sub CPAN::Index::rd_modpacks ; sub rd_modpacks { my($self, $index_target) = @_; return unless defined $index_target; return if CPAN::_sqlite_running; $CPAN::Frontend->myprint("Going to read $index_target\n"); my $fh = CPAN::Tarzip->TIEHANDLE($index_target); local $_; CPAN->debug(sprintf "start[%d]", time) if $CPAN::DEBUG; my $slurp = ""; my $chunk; while (my $bytes = $fh->READ(\$chunk,8192)) { $slurp.=$chunk; } my @lines = split /\012/, $slurp; CPAN->debug(sprintf "end[%d]", time) if $CPAN::DEBUG; undef $fh; # read header my($line_count,$last_updated); while (@lines) { my $shift = shift(@lines); last if $shift =~ /^\s*$/; $shift =~ /^Line-Count:\s+(\d+)/ and $line_count = $1; $shift =~ /^Last-Updated:\s+(.+)/ and $last_updated = $1; } CPAN->debug("line_count[$line_count]last_updated[$last_updated]") if $CPAN::DEBUG; if (not defined $line_count) { $CPAN::Frontend->mywarn(qq{Warning: Your $index_target does not contain a Line-Count header. Please check the validity of the index file by comparing it to more than one CPAN mirror. I'll continue but problems seem likely to happen.\a }); $CPAN::Frontend->mysleep(5); } elsif ($line_count != scalar @lines) { $CPAN::Frontend->mywarn(sprintf qq{Warning: Your %s contains a Line-Count header of %d but I see %d lines there. Please check the validity of the index file by comparing it to more than one CPAN mirror. I'll continue but problems seem likely to happen.\a\n}, $index_target, $line_count, scalar(@lines)); } if (not defined $last_updated) { $CPAN::Frontend->mywarn(qq{Warning: Your $index_target does not contain a Last-Updated header. Please check the validity of the index file by comparing it to more than one CPAN mirror. I'll continue but problems seem likely to happen.\a }); $CPAN::Frontend->mysleep(5); } else { $CPAN::Frontend ->myprint(sprintf qq{ Database was generated on %s\n}, $last_updated); $DATE_OF_02 = $last_updated; my $age = time; if ($CPAN::META->has_inst('HTTP::Date')) { require HTTP::Date; $age -= HTTP::Date::str2time($last_updated); } else { $CPAN::Frontend->mywarn(" HTTP::Date not available\n"); require Time::Local; my(@d) = $last_updated =~ / (\d+) (\w+) (\d+) (\d+):(\d+):(\d+) /; $d[1] = index("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec", $d[1])/4; $age -= $d[1]>=0 ? Time::Local::timegm(@d[5,4,3,0,1,2]) : 0; } $age /= 3600*24; if ($age > 30) { $CPAN::Frontend ->mywarn(sprintf qq{Warning: This index file is %d days old. Please check the host you chose as your CPAN mirror for staleness. I'll continue but problems seem likely to happen.\a\n}, $age); } elsif ($age < -1) { $CPAN::Frontend ->mywarn(sprintf qq{Warning: Your system date is %d days behind this index file! System time: %s Timestamp index file: %s Please fix your system time, problems with the make command expected.\n}, -$age, scalar gmtime, $DATE_OF_02, ); } } # A necessity since we have metadata_cache: delete what isn't # there anymore my $secondtime = $CPAN::META->exists("CPAN::Module","CPAN"); CPAN->debug("secondtime[$secondtime]") if $CPAN::DEBUG; my(%exists); my $i = 0; my $painted = 0; foreach (@lines) { # before 1.56 we split into 3 and discarded the rest. From # 1.57 we assign remaining text to $comment thus allowing to # influence isa_perl my($mod,$version,$dist,$comment) = split " ", $_, 4; my($bundle,$id,$userid); if ($mod eq 'CPAN' && ! ( CPAN::Queue->exists('Bundle::CPAN') || CPAN::Queue->exists('CPAN') ) ) { local($^W)= 0; if ($version > $CPAN::VERSION) { $CPAN::Frontend->mywarn(qq{ New CPAN.pm version (v$version) available. [Currently running version is v$CPAN::VERSION] You might want to try install CPAN reload cpan to both upgrade CPAN.pm and run the new version without leaving the current session. }); #}); $CPAN::Frontend->mysleep(2); $CPAN::Frontend->myprint(qq{\n}); } last if $CPAN::Signal; } elsif ($mod =~ /^Bundle::(.*)/) { $bundle = $1; } if ($bundle) { $id = $CPAN::META->instance('CPAN::Bundle',$mod); # Let's make it a module too, because bundles have so much # in common with modules. # Changed in 1.57_63: seems like memory bloat now without # any value, so commented out # $CPAN::META->instance('CPAN::Module',$mod); } else { # instantiate a module object $id = $CPAN::META->instance('CPAN::Module',$mod); } # Although CPAN prohibits same name with different version the # indexer may have changed the version for the same distro # since the last time ("Force Reindexing" feature) if ($id->cpan_file ne $dist || $id->cpan_version ne $version ) { $userid = $id->userid || $self->userid($dist); $id->set( 'CPAN_USERID' => $userid, 'CPAN_VERSION' => $version, 'CPAN_FILE' => $dist, ); } # instantiate a distribution object if ($CPAN::META->exists('CPAN::Distribution',$dist)) { # we do not need CONTAINSMODS unless we do something with # this dist, so we better produce it on demand. ## my $obj = $CPAN::META->instance( ## 'CPAN::Distribution' => $dist ## ); ## $obj->{CONTAINSMODS}{$mod} = undef; # experimental } else { $CPAN::META->instance( 'CPAN::Distribution' => $dist )->set( 'CPAN_USERID' => $userid, 'CPAN_COMMENT' => $comment, ); } if ($secondtime) { for my $name ($mod,$dist) { # $self->debug("exists name[$name]") if $CPAN::DEBUG; $exists{$name} = undef; } } $i++; while (($painted/76) < ($i/@lines)) { $CPAN::Frontend->myprint("."); $painted++; } return if $CPAN::Signal; } $CPAN::Frontend->myprint("DONE\n"); if ($secondtime) { for my $class (qw(CPAN::Module CPAN::Bundle CPAN::Distribution)) { for my $o ($CPAN::META->all_objects($class)) { next if exists $exists{$o->{ID}}; $CPAN::META->delete($class,$o->{ID}); # CPAN->debug("deleting ID[$o->{ID}] in class[$class]") # if $CPAN::DEBUG; } } } } #-> sub CPAN::Index::rd_modlist ; sub rd_modlist { my($cl,$index_target) = @_; return unless defined $index_target; return if CPAN::_sqlite_running; $CPAN::Frontend->myprint("Going to read $index_target\n"); my $fh = CPAN::Tarzip->TIEHANDLE($index_target); local $_; my $slurp = ""; my $chunk; while (my $bytes = $fh->READ(\$chunk,8192)) { $slurp.=$chunk; } my @eval2 = split /\012/, $slurp; while (@eval2) { my $shift = shift(@eval2); if ($shift =~ /^Date:\s+(.*)/) { if ($DATE_OF_03 eq $1) { $CPAN::Frontend->myprint("Unchanged.\n"); return; } ($DATE_OF_03) = $1; } last if $shift =~ /^\s*$/; } push @eval2, q{CPAN::Modulelist->data;}; local($^W) = 0; my($comp) = Safe->new("CPAN::Safe1"); my($eval2) = join("\n", @eval2); CPAN->debug(sprintf "length of eval2[%d]", length $eval2) if $CPAN::DEBUG; my $ret = $comp->reval($eval2); Carp::confess($@) if $@; return if $CPAN::Signal; my $i = 0; my $until = keys(%$ret); my $painted = 0; CPAN->debug(sprintf "until[%d]", $until) if $CPAN::DEBUG; for (keys %$ret) { my $obj = $CPAN::META->instance("CPAN::Module",$_); delete $ret->{$_}{modid}; # not needed here, maybe elsewhere $obj->set(%{$ret->{$_}}); $i++; while (($painted/76) < ($i/$until)) { $CPAN::Frontend->myprint("."); $painted++; } return if $CPAN::Signal; } $CPAN::Frontend->myprint("DONE\n"); } #-> sub CPAN::Index::write_metadata_cache ; sub write_metadata_cache { my($self) = @_; return unless $CPAN::Config->{'cache_metadata'}; return if CPAN::_sqlite_running; return unless $CPAN::META->has_usable("Storable"); my $cache; foreach my $k (qw(CPAN::Bundle CPAN::Author CPAN::Module CPAN::Distribution)) { $cache->{$k} = $CPAN::META->{readonly}{$k}; # unsafe meta access, ok } my $metadata_file = File::Spec->catfile($CPAN::Config->{cpan_home},"Metadata"); $cache->{last_time} = $LAST_TIME; $cache->{DATE_OF_02} = $DATE_OF_02; $cache->{PROTOCOL} = PROTOCOL; $CPAN::Frontend->myprint("Going to write $metadata_file\n"); eval { Storable::nstore($cache, $metadata_file) }; $CPAN::Frontend->mywarn($@) if $@; # ?? missing "\n" after $@ in mywarn ?? } #-> sub CPAN::Index::read_metadata_cache ; sub read_metadata_cache { my($self) = @_; return unless $CPAN::Config->{'cache_metadata'}; return if CPAN::_sqlite_running; return unless $CPAN::META->has_usable("Storable"); my $metadata_file = File::Spec->catfile($CPAN::Config->{cpan_home},"Metadata"); return unless -r $metadata_file and -f $metadata_file; $CPAN::Frontend->myprint("Going to read $metadata_file\n"); my $cache; eval { $cache = Storable::retrieve($metadata_file) }; $CPAN::Frontend->mywarn($@) if $@; # ?? missing "\n" after $@ in mywarn ?? if (!$cache || !UNIVERSAL::isa($cache, 'HASH')) { $LAST_TIME = 0; return; } if (exists $cache->{PROTOCOL}) { if (PROTOCOL > $cache->{PROTOCOL}) { $CPAN::Frontend->mywarn(sprintf("Ignoring Metadata cache written ". "with protocol v%s, requiring v%s\n", $cache->{PROTOCOL}, PROTOCOL) ); return; } } else { $CPAN::Frontend->mywarn("Ignoring Metadata cache written ". "with protocol v1.0\n"); return; } my $clcnt = 0; my $idcnt = 0; while(my($class,$v) = each %$cache) { next unless $class =~ /^CPAN::/; $CPAN::META->{readonly}{$class} = $v; # unsafe meta access, ok while (my($id,$ro) = each %$v) { $CPAN::META->{readwrite}{$class}{$id} ||= $class->new(ID=>$id, RO=>$ro); $idcnt++; } $clcnt++; } unless ($clcnt) { # sanity check $CPAN::Frontend->myprint("Warning: Found no data in $metadata_file\n"); return; } if ($idcnt < 1000) { $CPAN::Frontend->myprint("Warning: Found only $idcnt objects ". "in $metadata_file\n"); return; } $CPAN::META->{PROTOCOL} ||= $cache->{PROTOCOL}; # reading does not up or downgrade, but it # does initialize to some protocol $LAST_TIME = $cache->{last_time}; $DATE_OF_02 = $cache->{DATE_OF_02}; $CPAN::Frontend->myprint(" Database was generated on $DATE_OF_02\n") if defined $DATE_OF_02; # An old cache may not contain DATE_OF_02 return; } package CPAN::InfoObj; use strict; sub ro { my $self = shift; exists $self->{RO} and return $self->{RO}; } #-> sub CPAN::InfoObj::cpan_userid sub cpan_userid { my $self = shift; my $ro = $self->ro; if ($ro) { return $ro->{CPAN_USERID} || "N/A"; } else { $self->debug("ID[$self->{ID}]"); # N/A for bundles found locally return "N/A"; } } sub id { shift->{ID}; } #-> sub CPAN::InfoObj::new ; sub new { my $this = bless {}, shift; %$this = @_; $this } # The set method may only be used by code that reads index data or # otherwise "objective" data from the outside world. All session # related material may do anything else with instance variables but # must not touch the hash under the RO attribute. The reason is that # the RO hash gets written to Metadata file and is thus persistent. #-> sub CPAN::InfoObj::safe_chdir ; sub safe_chdir { my($self,$todir) = @_; # we die if we cannot chdir and we are debuggable Carp::confess("safe_chdir called without todir argument") unless defined $todir and length $todir; if (chdir $todir) { $self->debug(sprintf "changed directory to %s", CPAN::anycwd()) if $CPAN::DEBUG; } else { if (-e $todir) { unless (-x $todir) { unless (chmod 0755, $todir) { my $cwd = CPAN::anycwd(); $CPAN::Frontend->mywarn("I have neither the -x permission nor the ". "permission to change the permission; cannot ". "chdir to '$todir'\n"); $CPAN::Frontend->mysleep(5); $CPAN::Frontend->mydie(qq{Could not chdir from cwd[$cwd] }. qq{to todir[$todir]: $!}); } } } else { $CPAN::Frontend->mydie("Directory '$todir' has gone. Cannot continue.\n"); } if (chdir $todir) { $self->debug(sprintf "changed directory to %s", CPAN::anycwd()) if $CPAN::DEBUG; } else { my $cwd = CPAN::anycwd(); $CPAN::Frontend->mydie(qq{Could not chdir from cwd[$cwd] }. qq{to todir[$todir] (a chmod has been issued): $!}); } } } #-> sub CPAN::InfoObj::set ; sub set { my($self,%att) = @_; my $class = ref $self; # This must be ||=, not ||, because only if we write an empty # reference, only then the set method will write into the readonly # area. But for Distributions that spring into existence, maybe # because of a typo, we do not like it that they are written into # the readonly area and made permanent (at least for a while) and # that is why we do not "allow" other places to call ->set. unless ($self->id) { CPAN->debug("Bug? Empty ID, rejecting"); return; } my $ro = $self->{RO} = $CPAN::META->{readonly}{$class}{$self->id} ||= {}; while (my($k,$v) = each %att) { $ro->{$k} = $v; } } #-> sub CPAN::InfoObj::as_glimpse ; sub as_glimpse { my($self) = @_; my(@m); my $class = ref($self); $class =~ s/^CPAN:://; my $id = $self->can("pretty_id") ? $self->pretty_id : $self->{ID}; push @m, sprintf "%-15s %s\n", $class, $id; join "", @m; } #-> sub CPAN::InfoObj::as_string ; sub as_string { my($self) = @_; my(@m); my $class = ref($self); $class =~ s/^CPAN:://; push @m, $class, " id = $self->{ID}\n"; my $ro; unless ($ro = $self->ro) { if (substr($self->{ID},-1,1) eq ".") { # directory $ro = +{}; } else { $CPAN::Frontend->mywarn("Unknown object $self->{ID}\n"); $CPAN::Frontend->mysleep(5); return; } } for (sort keys %$ro) { # next if m/^(ID|RO)$/; my $extra = ""; if ($_ eq "CPAN_USERID") { $extra .= " ("; $extra .= $self->fullname; my $email; # old perls! if ($email = $CPAN::META->instance("CPAN::Author", $self->cpan_userid )->email) { $extra .= " <$email>"; } else { $extra .= " <no email>"; } $extra .= ")"; } elsif ($_ eq "FULLNAME") { # potential UTF-8 conversion push @m, sprintf " %-12s %s\n", $_, $self->fullname; next; } next unless defined $ro->{$_}; push @m, sprintf " %-12s %s%s\n", $_, $ro->{$_}, $extra; } KEY: for (sort keys %$self) { next if m/^(ID|RO)$/; unless (defined $self->{$_}) { delete $self->{$_}; next KEY; } if (ref($self->{$_}) eq "ARRAY") { push @m, sprintf " %-12s %s\n", $_, "@{$self->{$_}}"; } elsif (ref($self->{$_}) eq "HASH") { my $value; if (/^CONTAINSMODS$/) { $value = join(" ",sort keys %{$self->{$_}}); } elsif (/^prereq_pm$/) { my @value; my $v = $self->{$_}; for my $x (sort keys %$v) { my @svalue; for my $y (sort keys %{$v->{$x}}) { push @svalue, "$y=>$v->{$x}{$y}"; } push @value, "$x\:" . join ",", @svalue if @svalue; } $value = join ";", @value; } else { $value = $self->{$_}; } push @m, sprintf( " %-12s %s\n", $_, $value, ); } else { push @m, sprintf " %-12s %s\n", $_, $self->{$_}; } } join "", @m, "\n"; } #-> sub CPAN::InfoObj::fullname ; sub fullname { my($self) = @_; $CPAN::META->instance("CPAN::Author",$self->cpan_userid)->fullname; } #-> sub CPAN::InfoObj::dump ; sub dump { my($self, $what) = @_; unless ($CPAN::META->has_inst("Data::Dumper")) { $CPAN::Frontend->mydie("dump command requires Data::Dumper installed"); } local $Data::Dumper::Sortkeys; $Data::Dumper::Sortkeys = 1; my $out = Data::Dumper::Dumper($what ? eval $what : $self); if (length $out > 100000) { my $fh_pager = FileHandle->new; local($SIG{PIPE}) = "IGNORE"; my $pager = $CPAN::Config->{'pager'} || "cat"; $fh_pager->open("|$pager") or die "Could not open pager $pager\: $!"; $fh_pager->print($out); close $fh_pager; } else { $CPAN::Frontend->myprint($out); } } package CPAN::Author; use strict; #-> sub CPAN::Author::force sub force { my $self = shift; $self->{force}++; } #-> sub CPAN::Author::force sub unforce { my $self = shift; delete $self->{force}; } #-> sub CPAN::Author::id sub id { my $self = shift; my $id = $self->{ID}; $CPAN::Frontend->mydie("Illegal author id[$id]") unless $id =~ /^[A-Z]/; $id; } #-> sub CPAN::Author::as_glimpse ; sub as_glimpse { my($self) = @_; my(@m); my $class = ref($self); $class =~ s/^CPAN:://; push @m, sprintf(qq{%-15s %s ("%s" <%s>)\n}, $class, $self->{ID}, $self->fullname, $self->email); join "", @m; } #-> sub CPAN::Author::fullname ; sub fullname { shift->ro->{FULLNAME}; } *name = \&fullname; #-> sub CPAN::Author::email ; sub email { shift->ro->{EMAIL}; } #-> sub CPAN::Author::ls ; sub ls { my $self = shift; my $glob = shift || ""; my $silent = shift || 0; my $id = $self->id; # adapted from CPAN::Distribution::verifyCHECKSUM ; my(@csf); # chksumfile @csf = $self->id =~ /(.)(.)(.*)/; $csf[1] = join "", @csf[0,1]; $csf[2] = join "", @csf[1,2]; # ("A","AN","ANDK") my(@dl); @dl = $self->dir_listing([$csf[0],"CHECKSUMS"], 0, 1); unless (grep {$_->[2] eq $csf[1]} @dl) { $CPAN::Frontend->myprint("Directory $csf[1]/ does not exist\n") unless $silent ; return; } @dl = $self->dir_listing([@csf[0,1],"CHECKSUMS"], 0, 1); unless (grep {$_->[2] eq $csf[2]} @dl) { $CPAN::Frontend->myprint("Directory $id/ does not exist\n") unless $silent; return; } @dl = $self->dir_listing([@csf,"CHECKSUMS"], 1, 1); if ($glob) { if ($CPAN::META->has_inst("Text::Glob")) { my $rglob = Text::Glob::glob_to_regex($glob); @dl = grep { $_->[2] =~ /$rglob/ } @dl; } else { $CPAN::Frontend->mydie("Text::Glob not installed, cannot proceed"); } } unless ($silent >= 2) { $CPAN::Frontend->myprint(join "", map { sprintf("%8d %10s %s/%s\n", $_->[0], $_->[1], $id, $_->[2]) } sort { $a->[2] cmp $b->[2] } @dl); } @dl; } # returns an array of arrays, the latter contain (size,mtime,filename) #-> sub CPAN::Author::dir_listing ; sub dir_listing { my $self = shift; my $chksumfile = shift; my $recursive = shift; my $may_ftp = shift; my $lc_want = File::Spec->catfile($CPAN::Config->{keep_source_where}, "authors", "id", @$chksumfile); my $fh; # Purge and refetch old (pre-PGP) CHECKSUMS; they are a security # hazard. (Without GPG installed they are not that much better, # though.) $fh = FileHandle->new; if (open($fh, $lc_want)) { my $line = <$fh>; close $fh; unlink($lc_want) unless $line =~ /PGP/; } local($") = "/"; # connect "force" argument with "index_expire". my $force = $self->{force}; if (my @stat = stat $lc_want) { $force ||= $stat[9] + $CPAN::Config->{index_expire}*86400 <= time; } my $lc_file; if ($may_ftp) { $lc_file = CPAN::FTP->localize( "authors/id/@$chksumfile", $lc_want, $force, ); unless ($lc_file) { $CPAN::Frontend->myprint("Trying $lc_want.gz\n"); $chksumfile->[-1] .= ".gz"; $lc_file = CPAN::FTP->localize("authors/id/@$chksumfile", "$lc_want.gz",1); if ($lc_file) { $lc_file =~ s{\.gz(?!\n)\Z}{}; #}; eval{CPAN::Tarzip->new("$lc_file.gz")->gunzip($lc_file)}; } else { return; } } } else { $lc_file = $lc_want; # we *could* second-guess and if the user has a file: URL, # then we could look there. But on the other hand, if they do # have a file: URL, wy did they choose to set # $CPAN::Config->{show_upload_date} to false? } # adapted from CPAN::Distribution::CHECKSUM_check_file ; $fh = FileHandle->new; my($cksum); if (open $fh, $lc_file) { local($/); my $eval = <$fh>; $eval =~ s/\015?\012/\n/g; close $fh; my($comp) = Safe->new(); $cksum = $comp->reval($eval); if ($@) { rename $lc_file, "$lc_file.bad"; Carp::confess($@) if $@; } } elsif ($may_ftp) { Carp::carp "Could not open '$lc_file' for reading."; } else { # Maybe should warn: "You may want to set show_upload_date to a true value" return; } my(@result,$f); for $f (sort keys %$cksum) { if (exists $cksum->{$f}{isdir}) { if ($recursive) { my(@dir) = @$chksumfile; pop @dir; push @dir, $f, "CHECKSUMS"; push @result, map { [$_->[0], $_->[1], "$f/$_->[2]"] } $self->dir_listing(\@dir,1,$may_ftp); } else { push @result, [ 0, "-", $f ]; } } else { push @result, [ ($cksum->{$f}{"size"}||0), $cksum->{$f}{"mtime"}||"---", $f ]; } } @result; } #-> sub CPAN::Author::reports sub reports { $CPAN::Frontend->mywarn("reports on authors not implemented. Please file a bugreport if you need this.\n"); } package CPAN::Distribution; use strict; # Accessors sub cpan_comment { my $self = shift; my $ro = $self->ro or return; $ro->{CPAN_COMMENT} } #-> CPAN::Distribution::undelay sub undelay { my $self = shift; for my $delayer ( "configure_requires_later", "configure_requires_later_for", "later", "later_for", ) { delete $self->{$delayer}; } } #-> CPAN::Distribution::is_dot_dist sub is_dot_dist { my($self) = @_; return substr($self->id,-1,1) eq "."; } # add the A/AN/ stuff #-> CPAN::Distribution::normalize sub normalize { my($self,$s) = @_; $s = $self->id unless defined $s; if (substr($s,-1,1) eq ".") { # using a global because we are sometimes called as static method if (!$CPAN::META->{LOCK} && !$CPAN::Have_warned->{"$s is unlocked"}++ ) { $CPAN::Frontend->mywarn("You are visiting the local directory '$s' without lock, take care that concurrent processes do not do likewise.\n"); $CPAN::Frontend->mysleep(1); } if ($s eq ".") { $s = "$CPAN::iCwd/."; } elsif (File::Spec->file_name_is_absolute($s)) { } elsif (File::Spec->can("rel2abs")) { $s = File::Spec->rel2abs($s); } else { $CPAN::Frontend->mydie("Your File::Spec is too old, please upgrade File::Spec"); } CPAN->debug("s[$s]") if $CPAN::DEBUG; unless ($CPAN::META->exists("CPAN::Distribution", $s)) { for ($CPAN::META->instance("CPAN::Distribution", $s)) { $_->{build_dir} = $s; $_->{archived} = "local_directory"; $_->{unwrapped} = CPAN::Distrostatus->new("YES -- local_directory"); } } } elsif ( $s =~ tr|/|| == 1 or $s !~ m|[A-Z]/[A-Z-]{2}/[A-Z-]{2,}/| ) { return $s if $s =~ m:^N/A|^Contact Author: ; $s =~ s|^(.)(.)([^/]*/)(.+)$|$1/$1$2/$1$2$3$4| or $CPAN::Frontend->mywarn("Strange distribution name [$s]\n"); CPAN->debug("s[$s]") if $CPAN::DEBUG; } $s; } #-> sub CPAN::Distribution::author ; sub author { my($self) = @_; my($authorid); if (substr($self->id,-1,1) eq ".") { $authorid = "LOCAL"; } else { ($authorid) = $self->pretty_id =~ /^([\w\-]+)/; } CPAN::Shell->expand("Author",$authorid); } # tries to get the yaml from CPAN instead of the distro itself: # EXPERIMENTAL, UNDOCUMENTED AND UNTESTED, for Tels sub fast_yaml { my($self) = @_; my $meta = $self->pretty_id; $meta =~ s/\.(tar.gz|tgz|zip|tar.bz2)/.meta/; my(@ls) = CPAN::Shell->globls($meta); my $norm = $self->normalize($meta); my($local_file); my($local_wanted) = File::Spec->catfile( $CPAN::Config->{keep_source_where}, "authors", "id", split(/\//,$norm) ); $self->debug("Doing localize") if $CPAN::DEBUG; unless ($local_file = CPAN::FTP->localize("authors/id/$norm", $local_wanted)) { $CPAN::Frontend->mydie("Giving up on downloading yaml file '$local_wanted'\n"); } my $yaml = CPAN->_yaml_loadfile($local_file)->[0]; } #-> sub CPAN::Distribution::cpan_userid sub cpan_userid { my $self = shift; if ($self->{ID} =~ m{[A-Z]/[A-Z\-]{2}/([A-Z\-]+)/}) { return $1; } return $self->SUPER::cpan_userid; } #-> sub CPAN::Distribution::pretty_id sub pretty_id { my $self = shift; my $id = $self->id; return $id unless $id =~ m|^./../|; substr($id,5); } #-> sub CPAN::Distribution::base_id sub base_id { my $self = shift; my $id = $self->pretty_id(); my $base_id = File::Basename::basename($id); $base_id =~ s{\.(?:tar\.(bz2|gz|Z)|t(?:gz|bz)|zip)$}{}i; return $base_id; } # mark as dirty/clean for the sake of recursion detection. $color=1 # means "in use", $color=0 means "not in use anymore". $color=2 means # we have determined prereqs now and thus insist on passing this # through (at least) once again. #-> sub CPAN::Distribution::color_cmd_tmps ; sub color_cmd_tmps { my($self) = shift; my($depth) = shift || 0; my($color) = shift || 0; my($ancestors) = shift || []; # a distribution needs to recurse into its prereq_pms return if exists $self->{incommandcolor} && $color==1 && $self->{incommandcolor}==$color; if ($depth>=$CPAN::MAX_RECURSION) { die(CPAN::Exception::RecursiveDependency->new($ancestors)); } # warn "color_cmd_tmps $depth $color " . $self->id; # sleep 1; my $prereq_pm = $self->prereq_pm; if (defined $prereq_pm) { PREREQ: for my $pre (keys %{$prereq_pm->{requires}||{}}, keys %{$prereq_pm->{build_requires}||{}}) { next PREREQ if $pre eq "perl"; my $premo; unless ($premo = CPAN::Shell->expand("Module",$pre)) { $CPAN::Frontend->mywarn("prerequisite module[$pre] not known\n"); $CPAN::Frontend->mysleep(2); next PREREQ; } $premo->color_cmd_tmps($depth+1,$color,[@$ancestors, $self->id]); } } if ($color==0) { delete $self->{sponsored_mods}; # as we are at the end of a command, we'll give up this # reminder of a broken test. Other commands may test this guy # again. Maybe 'badtestcnt' should be renamed to # 'make_test_failed_within_command'? delete $self->{badtestcnt}; } $self->{incommandcolor} = $color; } #-> sub CPAN::Distribution::as_string ; sub as_string { my $self = shift; $self->containsmods; $self->upload_date; $self->SUPER::as_string(@_); } #-> sub CPAN::Distribution::containsmods ; sub containsmods { my $self = shift; return keys %{$self->{CONTAINSMODS}} if exists $self->{CONTAINSMODS}; my $dist_id = $self->{ID}; for my $mod ($CPAN::META->all_objects("CPAN::Module")) { my $mod_file = $mod->cpan_file or next; my $mod_id = $mod->{ID} or next; # warn "mod_file[$mod_file] dist_id[$dist_id] mod_id[$mod_id]"; # sleep 1; if ($CPAN::Signal) { delete $self->{CONTAINSMODS}; return; } $self->{CONTAINSMODS}{$mod_id} = undef if $mod_file eq $dist_id; } keys %{$self->{CONTAINSMODS}||={}}; } #-> sub CPAN::Distribution::upload_date ; sub upload_date { my $self = shift; return $self->{UPLOAD_DATE} if exists $self->{UPLOAD_DATE}; my(@local_wanted) = split(/\//,$self->id); my $filename = pop @local_wanted; push @local_wanted, "CHECKSUMS"; my $author = CPAN::Shell->expand("Author",$self->cpan_userid); return unless $author; my @dl = $author->dir_listing(\@local_wanted,0,$CPAN::Config->{show_upload_date}); return unless @dl; my($dirent) = grep { $_->[2] eq $filename } @dl; # warn sprintf "dirent[%s]id[%s]", $dirent, $self->id; return unless $dirent->[1]; return $self->{UPLOAD_DATE} = $dirent->[1]; } #-> sub CPAN::Distribution::uptodate ; sub uptodate { my($self) = @_; my $c; foreach $c ($self->containsmods) { my $obj = CPAN::Shell->expandany($c); unless ($obj->uptodate) { my $id = $self->pretty_id; $self->debug("$id not uptodate due to $c") if $CPAN::DEBUG; return 0; } } return 1; } #-> sub CPAN::Distribution::called_for ; sub called_for { my($self,$id) = @_; $self->{CALLED_FOR} = $id if defined $id; return $self->{CALLED_FOR}; } #-> sub CPAN::Distribution::get ; sub get { my($self) = @_; $self->debug("checking goto id[$self->{ID}]") if $CPAN::DEBUG; if (my $goto = $self->prefs->{goto}) { $CPAN::Frontend->mywarn (sprintf( "delegating to '%s' as specified in prefs file '%s' doc %d\n", $goto, $self->{prefs_file}, $self->{prefs_file_doc}, )); return $self->goto($goto); } local $ENV{PERL5LIB} = defined($ENV{PERL5LIB}) ? $ENV{PERL5LIB} : ($ENV{PERLLIB} || ""); $CPAN::META->set_perl5lib; local $ENV{MAKEFLAGS}; # protect us from outer make calls EXCUSE: { my @e; my $goodbye_message; $self->debug("checking disabled id[$self->{ID}]") if $CPAN::DEBUG; if ($self->prefs->{disabled}) { my $why = sprintf( "Disabled via prefs file '%s' doc %d", $self->{prefs_file}, $self->{prefs_file_doc}, ); push @e, $why; $self->{unwrapped} = CPAN::Distrostatus->new("NO $why"); $goodbye_message = "[disabled] -- NA $why"; # note: not intended to be persistent but at least visible # during this session } else { if (exists $self->{build_dir} && -d $self->{build_dir} && ($self->{modulebuild}||$self->{writemakefile}) ) { # this deserves print, not warn: $CPAN::Frontend->myprint(" Has already been unwrapped into directory ". "$self->{build_dir}\n" ); return 1; } # although we talk about 'force' we shall not test on # force directly. New model of force tries to refrain from # direct checking of force. exists $self->{unwrapped} and ( UNIVERSAL::can($self->{unwrapped},"failed") ? $self->{unwrapped}->failed : $self->{unwrapped} =~ /^NO/ ) and push @e, "Unwrapping had some problem, won't try again without force"; } if (@e) { $CPAN::Frontend->mywarn(join "", map {"$_\n"} @e); if ($goodbye_message) { $self->goodbye($goodbye_message); } return; } } my $sub_wd = CPAN::anycwd(); # for cleaning up as good as possible my($local_file); unless ($self->{build_dir} && -d $self->{build_dir}) { $self->get_file_onto_local_disk; return if $CPAN::Signal; $self->check_integrity; return if $CPAN::Signal; (my $packagedir,$local_file) = $self->run_preps_on_packagedir; $packagedir ||= $self->{build_dir}; $self->{build_dir} = $packagedir; } if ($CPAN::Signal) { $self->safe_chdir($sub_wd); return; } return $self->run_MM_or_MB($local_file); } #-> CPAN::Distribution::get_file_onto_local_disk sub get_file_onto_local_disk { my($self) = @_; return if $self->is_dot_dist; my($local_file); my($local_wanted) = File::Spec->catfile( $CPAN::Config->{keep_source_where}, "authors", "id", split(/\//,$self->id) ); $self->debug("Doing localize") if $CPAN::DEBUG; unless ($local_file = CPAN::FTP->localize("authors/id/$self->{ID}", $local_wanted)) { my $note = ""; if ($CPAN::Index::DATE_OF_02) { $note = "Note: Current database in memory was generated ". "on $CPAN::Index::DATE_OF_02\n"; } $CPAN::Frontend->mydie("Giving up on '$local_wanted'\n$note"); } $self->debug("local_wanted[$local_wanted]local_file[$local_file]") if $CPAN::DEBUG; $self->{localfile} = $local_file; } #-> CPAN::Distribution::check_integrity sub check_integrity { my($self) = @_; return if $self->is_dot_dist; if ($CPAN::META->has_inst("Digest::SHA")) { $self->debug("Digest::SHA is installed, verifying"); $self->verifyCHECKSUM; } else { $self->debug("Digest::SHA is NOT installed"); } } #-> CPAN::Distribution::run_preps_on_packagedir sub run_preps_on_packagedir { my($self) = @_; return if $self->is_dot_dist; $CPAN::META->{cachemgr} ||= CPAN::CacheMgr->new(); # unsafe meta access, ok my $builddir = $CPAN::META->{cachemgr}->dir; # unsafe meta access, ok $self->safe_chdir($builddir); $self->debug("Removing tmp-$$") if $CPAN::DEBUG; File::Path::rmtree("tmp-$$"); unless (mkdir "tmp-$$", 0755) { $CPAN::Frontend->unrecoverable_error(<<EOF); Couldn't mkdir '$builddir/tmp-$$': $! Cannot continue: Please find the reason why I cannot make the directory $builddir/tmp-$$ and fix the problem, then retry. EOF } if ($CPAN::Signal) { return; } $self->safe_chdir("tmp-$$"); # # Unpack the goods # my $local_file = $self->{localfile}; my $ct = eval{CPAN::Tarzip->new($local_file)}; unless ($ct) { $self->{unwrapped} = CPAN::Distrostatus->new("NO"); delete $self->{build_dir}; return; } if ($local_file =~ /(\.tar\.(bz2|gz|Z)|\.tgz)(?!\n)\Z/i) { $self->{was_uncompressed}++ unless eval{$ct->gtest()}; $self->untar_me($ct); } elsif ( $local_file =~ /\.zip(?!\n)\Z/i ) { $self->unzip_me($ct); } else { $self->{was_uncompressed}++ unless $ct->gtest(); $local_file = $self->handle_singlefile($local_file); } # we are still in the tmp directory! # Let's check if the package has its own directory. my $dh = DirHandle->new(File::Spec->curdir) or Carp::croak("Couldn't opendir .: $!"); my @readdir = grep $_ !~ /^\.\.?(?!\n)\Z/s, $dh->read; ### MAC?? $dh->close; my ($packagedir); # XXX here we want in each branch File::Temp to protect all build_dir directories if (CPAN->has_usable("File::Temp")) { my $tdir_base; my $from_dir; my @dirents; if (@readdir == 1 && -d $readdir[0]) { $tdir_base = $readdir[0]; $from_dir = File::Spec->catdir(File::Spec->curdir,$readdir[0]); my $dh2 = DirHandle->new($from_dir) or Carp::croak("Couldn't opendir $from_dir: $!"); @dirents = grep $_ !~ /^\.\.?(?!\n)\Z/s, $dh2->read; ### MAC?? } else { my $userid = $self->cpan_userid; CPAN->debug("userid[$userid]"); if (!$userid or $userid eq "N/A") { $userid = "anon"; } $tdir_base = $userid; $from_dir = File::Spec->curdir; @dirents = @readdir; } $packagedir = File::Temp::tempdir( "$tdir_base-XXXXXX", DIR => $builddir, CLEANUP => 0, ); my $f; for $f (@dirents) { # is already without "." and ".." my $from = File::Spec->catdir($from_dir,$f); my $to = File::Spec->catdir($packagedir,$f); unless (File::Copy::move($from,$to)) { my $err = $!; $from = File::Spec->rel2abs($from); Carp::confess("Couldn't move $from to $to: $err"); } } } else { # older code below, still better than nothing when there is no File::Temp my($distdir); if (@readdir == 1 && -d $readdir[0]) { $distdir = $readdir[0]; $packagedir = File::Spec->catdir($builddir,$distdir); $self->debug("packagedir[$packagedir]builddir[$builddir]distdir[$distdir]") if $CPAN::DEBUG; -d $packagedir and $CPAN::Frontend->myprint("Removing previously used ". "$packagedir\n"); File::Path::rmtree($packagedir); unless (File::Copy::move($distdir,$packagedir)) { $CPAN::Frontend->unrecoverable_error(<<EOF); Couldn't move '$distdir' to '$packagedir': $! Cannot continue: Please find the reason why I cannot move $builddir/tmp-$$/$distdir to $packagedir and fix the problem, then retry EOF } $self->debug(sprintf("moved distdir[%s] to packagedir[%s] -e[%s]-d[%s]", $distdir, $packagedir, -e $packagedir, -d $packagedir, )) if $CPAN::DEBUG; } else { my $userid = $self->cpan_userid; CPAN->debug("userid[$userid]") if $CPAN::DEBUG; if (!$userid or $userid eq "N/A") { $userid = "anon"; } my $pragmatic_dir = $userid . '000'; $pragmatic_dir =~ s/\W_//g; $pragmatic_dir++ while -d "../$pragmatic_dir"; $packagedir = File::Spec->catdir($builddir,$pragmatic_dir); $self->debug("packagedir[$packagedir]") if $CPAN::DEBUG; File::Path::mkpath($packagedir); my($f); for $f (@readdir) { # is already without "." and ".." my $to = File::Spec->catdir($packagedir,$f); File::Copy::move($f,$to) or Carp::confess("Couldn't move $f to $to: $!"); } } } $self->{build_dir} = $packagedir; $self->safe_chdir($builddir); File::Path::rmtree("tmp-$$"); $self->safe_chdir($packagedir); $self->_signature_business(); $self->safe_chdir($builddir); return($packagedir,$local_file); } #-> sub CPAN::Distribution::parse_meta_yml ; sub parse_meta_yml { my($self) = @_; my $build_dir = $self->{build_dir} or die "PANIC: cannot parse yaml without a build_dir"; my $yaml = File::Spec->catfile($build_dir,"META.yml"); $self->debug("yaml[$yaml]") if $CPAN::DEBUG; return unless -f $yaml; my $early_yaml; eval { require Parse::Metayaml; # hypothetical $early_yaml = Parse::Metayaml::LoadFile($yaml)->[0]; }; unless ($early_yaml) { eval { $early_yaml = CPAN->_yaml_loadfile($yaml)->[0]; }; } unless ($early_yaml) { return; } return $early_yaml; } #-> sub CPAN::Distribution::satisfy_configure_requires ; sub satisfy_configure_requires { my($self) = @_; my $enable_configure_requires = 1; if (!$enable_configure_requires) { return 1; # if we return 1 here, everything is as before we introduced # configure_requires that means, things with # configure_requires simply fail, all others succeed } my @prereq = $self->unsat_prereq("configure_requires_later") or return 1; if ($self->{configure_requires_later}) { for my $k (keys %{$self->{configure_requires_later_for}||{}}) { if ($self->{configure_requires_later_for}{$k}>1) { # we must not come here a second time $CPAN::Frontend->mywarn("Panic: Some prerequisites is not available, please investigate..."); require YAML::Syck; $CPAN::Frontend->mydie ( YAML::Syck::Dump ({self=>$self, prereq=>\@prereq}) ); } } } if ($prereq[0][0] eq "perl") { my $need = "requires perl '$prereq[0][1]'"; my $id = $self->pretty_id; $CPAN::Frontend->mywarn("$id $need; you have only $]; giving up\n"); $self->{make} = CPAN::Distrostatus->new("NO $need"); $self->store_persistent_state; return $self->goodbye("[prereq] -- NOT OK"); } else { my $follow = eval { $self->follow_prereqs("configure_requires_later", @prereq); }; if (0) { } elsif ($follow) { return; } elsif ($@ && ref $@ && $@->isa("CPAN::Exception::RecursiveDependency")) { $CPAN::Frontend->mywarn($@); return $self->goodbye("[depend] -- NOT OK"); } } die "never reached"; } #-> sub CPAN::Distribution::run_MM_or_MB ; sub run_MM_or_MB { my($self,$local_file) = @_; $self->satisfy_configure_requires() or return; my($mpl) = File::Spec->catfile($self->{build_dir},"Makefile.PL"); my($mpl_exists) = -f $mpl; unless ($mpl_exists) { # NFS has been reported to have racing problems after the # renaming of a directory in some environments. # This trick helps. $CPAN::Frontend->mysleep(1); my $mpldh = DirHandle->new($self->{build_dir}) or Carp::croak("Couldn't opendir $self->{build_dir}: $!"); $mpl_exists = grep /^Makefile\.PL$/, $mpldh->read; $mpldh->close; } my $prefer_installer = "eumm"; # eumm|mb if (-f File::Spec->catfile($self->{build_dir},"Build.PL")) { if ($mpl_exists) { # they *can* choose if ($CPAN::META->has_inst("Module::Build")) { $prefer_installer = CPAN::HandleConfig->prefs_lookup($self, q{prefer_installer}); } } else { $prefer_installer = "mb"; } } return unless $self->patch; if (lc($prefer_installer) eq "rand") { $prefer_installer = rand()<.5 ? "eumm" : "mb"; } if (lc($prefer_installer) eq "mb") { $self->{modulebuild} = 1; } elsif ($self->{archived} eq "patch") { # not an edge case, nothing to install for sure my $why = "A patch file cannot be installed"; $CPAN::Frontend->mywarn("Refusing to handle this file: $why\n"); $self->{writemakefile} = CPAN::Distrostatus->new("NO $why"); } elsif (! $mpl_exists) { $self->_edge_cases($mpl,$local_file); } if ($self->{build_dir} && $CPAN::Config->{build_dir_reuse} ) { $self->store_persistent_state; } return $self; } #-> CPAN::Distribution::store_persistent_state sub store_persistent_state { my($self) = @_; my $dir = $self->{build_dir}; unless (File::Spec->canonpath(File::Basename::dirname($dir)) eq File::Spec->canonpath($CPAN::Config->{build_dir})) { $CPAN::Frontend->mywarn("Directory '$dir' not below $CPAN::Config->{build_dir}, ". "will not store persistent state\n"); return; } my $file = sprintf "%s.yml", $dir; my $yaml_module = CPAN::_yaml_module; if ($CPAN::META->has_inst($yaml_module)) { CPAN->_yaml_dumpfile( $file, { time => time, perl => CPAN::_perl_fingerprint, distribution => $self, } ); } else { $CPAN::Frontend->myprint("Warning (usually harmless): '$yaml_module' not installed, ". "will not store persistent state\n"); } } #-> CPAN::Distribution::try_download sub try_download { my($self,$patch) = @_; my $norm = $self->normalize($patch); my($local_wanted) = File::Spec->catfile( $CPAN::Config->{keep_source_where}, "authors", "id", split(/\//,$norm), ); $self->debug("Doing localize") if $CPAN::DEBUG; return CPAN::FTP->localize("authors/id/$norm", $local_wanted); } { my $stdpatchargs = ""; #-> CPAN::Distribution::patch sub patch { my($self) = @_; $self->debug("checking patches id[$self->{ID}]") if $CPAN::DEBUG; my $patches = $self->prefs->{patches}; $patches ||= ""; $self->debug("patches[$patches]") if $CPAN::DEBUG; if ($patches) { return unless @$patches; $self->safe_chdir($self->{build_dir}); CPAN->debug("patches[$patches]") if $CPAN::DEBUG; my $patchbin = $CPAN::Config->{patch}; unless ($patchbin && length $patchbin) { $CPAN::Frontend->mydie("No external patch command configured\n\n". "Please run 'o conf init /patch/'\n\n"); } unless (MM->maybe_command($patchbin)) { $CPAN::Frontend->mydie("No external patch command available\n\n". "Please run 'o conf init /patch/'\n\n"); } $patchbin = CPAN::HandleConfig->safe_quote($patchbin); local $ENV{PATCH_GET} = 0; # formerly known as -g0 unless ($stdpatchargs) { my $system = "$patchbin --version |"; local *FH; open FH, $system or die "Could not fork '$system': $!"; local $/ = "\n"; my $pversion; PARSEVERSION: while (<FH>) { if (/^patch\s+([\d\.]+)/) { $pversion = $1; last PARSEVERSION; } } if ($pversion) { $stdpatchargs = "-N --fuzz=3"; } else { $stdpatchargs = "-N"; } } my $countedpatches = @$patches == 1 ? "1 patch" : (scalar @$patches . " patches"); $CPAN::Frontend->myprint("Going to apply $countedpatches:\n"); for my $patch (@$patches) { unless (-f $patch) { if (my $trydl = $self->try_download($patch)) { $patch = $trydl; } else { my $fail = "Could not find patch '$patch'"; $CPAN::Frontend->mywarn("$fail; cannot continue\n"); $self->{unwrapped} = CPAN::Distrostatus->new("NO -- $fail"); delete $self->{build_dir}; return; } } $CPAN::Frontend->myprint(" $patch\n"); my $readfh = CPAN::Tarzip->TIEHANDLE($patch); my $pcommand; my $ppp = $self->_patch_p_parameter($readfh); if ($ppp eq "applypatch") { $pcommand = "$CPAN::Config->{applypatch} -verbose"; } else { my $thispatchargs = join " ", $stdpatchargs, $ppp; $pcommand = "$patchbin $thispatchargs"; } $readfh = CPAN::Tarzip->TIEHANDLE($patch); # open again my $writefh = FileHandle->new; $CPAN::Frontend->myprint(" $pcommand\n"); unless (open $writefh, "|$pcommand") { my $fail = "Could not fork '$pcommand'"; $CPAN::Frontend->mywarn("$fail; cannot continue\n"); $self->{unwrapped} = CPAN::Distrostatus->new("NO -- $fail"); delete $self->{build_dir}; return; } while (my $x = $readfh->READLINE) { print $writefh $x; } unless (close $writefh) { my $fail = "Could not apply patch '$patch'"; $CPAN::Frontend->mywarn("$fail; cannot continue\n"); $self->{unwrapped} = CPAN::Distrostatus->new("NO -- $fail"); delete $self->{build_dir}; return; } } $self->{patched}++; } return 1; } } sub _patch_p_parameter { my($self,$fh) = @_; my $cnt_files = 0; my $cnt_p0files = 0; local($_); while ($_ = $fh->READLINE) { if ( $CPAN::Config->{applypatch} && /\#\#\#\# ApplyPatch data follows \#\#\#\#/ ) { return "applypatch" } next unless /^[\*\+]{3}\s(\S+)/; my $file = $1; $cnt_files++; $cnt_p0files++ if -f $file; CPAN->debug("file[$file]cnt_files[$cnt_files]cnt_p0files[$cnt_p0files]") if $CPAN::DEBUG; } return "-p1" unless $cnt_files; return $cnt_files==$cnt_p0files ? "-p0" : "-p1"; } #-> sub CPAN::Distribution::_edge_cases # with "configure" or "Makefile" or single file scripts sub _edge_cases { my($self,$mpl,$local_file) = @_; $self->debug(sprintf("makefilepl[%s]anycwd[%s]", $mpl, CPAN::anycwd(), )) if $CPAN::DEBUG; my $build_dir = $self->{build_dir}; my($configure) = File::Spec->catfile($build_dir,"Configure"); if (-f $configure) { # do we have anything to do? $self->{configure} = $configure; } elsif (-f File::Spec->catfile($build_dir,"Makefile")) { $CPAN::Frontend->mywarn(qq{ Package comes with a Makefile and without a Makefile.PL. We\'ll try to build it with that Makefile then. }); $self->{writemakefile} = CPAN::Distrostatus->new("YES"); $CPAN::Frontend->mysleep(2); } else { my $cf = $self->called_for || "unknown"; if ($cf =~ m|/|) { $cf =~ s|.*/||; $cf =~ s|\W.*||; } $cf =~ s|[/\\:]||g; # risk of filesystem damage $cf = "unknown" unless length($cf); $CPAN::Frontend->mywarn(qq{Package seems to come without Makefile.PL. (The test -f "$mpl" returned false.) Writing one on our own (setting NAME to $cf)\a\n}); $self->{had_no_makefile_pl}++; $CPAN::Frontend->mysleep(3); # Writing our own Makefile.PL my $script = ""; if ($self->{archived} eq "maybe_pl") { my $fh = FileHandle->new; my $script_file = File::Spec->catfile($build_dir,$local_file); $fh->open($script_file) or Carp::croak("Could not open script '$script_file': $!"); local $/ = "\n"; # name parsen und prereq my($state) = "poddir"; my($name, $prereq) = ("", ""); while (<$fh>) { if ($state eq "poddir" && /^=head\d\s+(\S+)/) { if ($1 eq 'NAME') { $state = "name"; } elsif ($1 eq 'PREREQUISITES') { $state = "prereq"; } } elsif ($state =~ m{^(name|prereq)$}) { if (/^=/) { $state = "poddir"; } elsif (/^\s*$/) { # nop } elsif ($state eq "name") { if ($name eq "") { ($name) = /^(\S+)/; $state = "poddir"; } } elsif ($state eq "prereq") { $prereq .= $_; } } elsif (/^=cut\b/) { last; } } $fh->close; for ($name) { s{.*<}{}; # strip X<...> s{>.*}{}; } chomp $prereq; $prereq = join " ", split /\s+/, $prereq; my($PREREQ_PM) = join("\n", map { s{.*<}{}; # strip X<...> s{>.*}{}; if (/[\s\'\"]/) { # prose? } else { s/[^\w:]$//; # period? " "x28 . "'$_' => 0,"; } } split /\s*,\s*/, $prereq); $script = " EXE_FILES => ['$name'], PREREQ_PM => { $PREREQ_PM }, "; if ($name) { my $to_file = File::Spec->catfile($build_dir, $name); rename $script_file, $to_file or die "Can't rename $script_file to $to_file: $!"; } } my $fh = FileHandle->new; $fh->open(">$mpl") or Carp::croak("Could not open >$mpl: $!"); $fh->print( qq{# This Makefile.PL has been autogenerated by the module CPAN.pm # because there was no Makefile.PL supplied. # Autogenerated on: }.scalar localtime().qq{ use ExtUtils::MakeMaker; WriteMakefile( NAME => q[$cf],$script ); }); $fh->close; } } #-> CPAN::Distribution::_signature_business sub _signature_business { my($self) = @_; my $check_sigs = CPAN::HandleConfig->prefs_lookup($self, q{check_sigs}); if ($check_sigs) { if ($CPAN::META->has_inst("Module::Signature")) { if (-f "SIGNATURE") { $self->debug("Module::Signature is installed, verifying") if $CPAN::DEBUG; my $rv = Module::Signature::verify(); if ($rv != Module::Signature::SIGNATURE_OK() and $rv != Module::Signature::SIGNATURE_MISSING()) { $CPAN::Frontend->mywarn( qq{\nSignature invalid for }. qq{distribution file. }. qq{Please investigate.\n\n} ); my $wrap = sprintf(qq{I'd recommend removing %s. Some error occured }. qq{while checking its signature, so it could }. qq{be invalid. Maybe you have configured }. qq{your 'urllist' with a bad URL. Please check this }. qq{array with 'o conf urllist' and retry. Or }. qq{examine the distribution in a subshell. Try look %s and run cpansign -v }, $self->{localfile}, $self->pretty_id, ); $self->{signature_verify} = CPAN::Distrostatus->new("NO"); $CPAN::Frontend->mywarn(Text::Wrap::wrap("","",$wrap)); $CPAN::Frontend->mysleep(5) if $CPAN::Frontend->can("mysleep"); } else { $self->{signature_verify} = CPAN::Distrostatus->new("YES"); $self->debug("Module::Signature has verified") if $CPAN::DEBUG; } } else { $CPAN::Frontend->mywarn(qq{Package came without SIGNATURE\n\n}); } } else { $self->debug("Module::Signature is NOT installed") if $CPAN::DEBUG; } } } #-> CPAN::Distribution::untar_me ; sub untar_me { my($self,$ct) = @_; $self->{archived} = "tar"; if ($ct->untar()) { $self->{unwrapped} = CPAN::Distrostatus->new("YES"); } else { $self->{unwrapped} = CPAN::Distrostatus->new("NO -- untar failed"); } } # CPAN::Distribution::unzip_me ; sub unzip_me { my($self,$ct) = @_; $self->{archived} = "zip"; if ($ct->unzip()) { $self->{unwrapped} = CPAN::Distrostatus->new("YES"); } else { $self->{unwrapped} = CPAN::Distrostatus->new("NO -- unzip failed"); } return; } sub handle_singlefile { my($self,$local_file) = @_; if ( $local_file =~ /\.pm(\.(gz|Z))?(?!\n)\Z/ ) { $self->{archived} = "pm"; } elsif ( $local_file =~ /\.patch(\.(gz|bz2))?(?!\n)\Z/ ) { $self->{archived} = "patch"; } else { $self->{archived} = "maybe_pl"; } my $to = File::Basename::basename($local_file); if ($to =~ s/\.(gz|Z)(?!\n)\Z//) { if (eval{CPAN::Tarzip->new($local_file)->gunzip($to)}) { $self->{unwrapped} = CPAN::Distrostatus->new("YES"); } else { $self->{unwrapped} = CPAN::Distrostatus->new("NO -- uncompressing failed"); } } else { if (File::Copy::cp($local_file,".")) { $self->{unwrapped} = CPAN::Distrostatus->new("YES"); } else { $self->{unwrapped} = CPAN::Distrostatus->new("NO -- copying failed"); } } return $to; } #-> sub CPAN::Distribution::new ; sub new { my($class,%att) = @_; # $CPAN::META->{cachemgr} ||= CPAN::CacheMgr->new(); my $this = { %att }; return bless $this, $class; } #-> sub CPAN::Distribution::look ; sub look { my($self) = @_; if ($^O eq 'MacOS') { $self->Mac::BuildTools::look; return; } if ( $CPAN::Config->{'shell'} ) { $CPAN::Frontend->myprint(qq{ Trying to open a subshell in the build directory... }); } else { $CPAN::Frontend->myprint(qq{ Your configuration does not define a value for subshells. Please define it with "o conf shell <your shell>" }); return; } my $dist = $self->id; my $dir; unless ($dir = $self->dir) { $self->get; } unless ($dir ||= $self->dir) { $CPAN::Frontend->mywarn(qq{ Could not determine which directory to use for looking at $dist. }); return; } my $pwd = CPAN::anycwd(); $self->safe_chdir($dir); $CPAN::Frontend->myprint(qq{Working directory is $dir\n}); { local $ENV{CPAN_SHELL_LEVEL} = $ENV{CPAN_SHELL_LEVEL}||0; $ENV{CPAN_SHELL_LEVEL} += 1; my $shell = CPAN::HandleConfig->safe_quote($CPAN::Config->{'shell'}); unless (system($shell) == 0) { my $code = $? >> 8; $CPAN::Frontend->mywarn("Subprocess shell exit code $code\n"); } } $self->safe_chdir($pwd); } # CPAN::Distribution::cvs_import ; sub cvs_import { my($self) = @_; $self->get; my $dir = $self->dir; my $package = $self->called_for; my $module = $CPAN::META->instance('CPAN::Module', $package); my $version = $module->cpan_version; my $userid = $self->cpan_userid; my $cvs_dir = (split /\//, $dir)[-1]; $cvs_dir =~ s/-\d+[^-]+(?!\n)\Z//; my $cvs_root = $CPAN::Config->{cvsroot} || $ENV{CVSROOT}; my $cvs_site_perl = $CPAN::Config->{cvs_site_perl} || $ENV{CVS_SITE_PERL}; if ($cvs_site_perl) { $cvs_dir = "$cvs_site_perl/$cvs_dir"; } my $cvs_log = qq{"imported $package $version sources"}; $version =~ s/\./_/g; # XXX cvs: undocumented and unclear how it was meant to work my @cmd = ('cvs', '-d', $cvs_root, 'import', '-m', $cvs_log, "$cvs_dir", $userid, "v$version"); my $pwd = CPAN::anycwd(); chdir($dir) or $CPAN::Frontend->mydie(qq{Could not chdir to "$dir": $!}); $CPAN::Frontend->myprint(qq{Working directory is $dir\n}); $CPAN::Frontend->myprint(qq{@cmd\n}); system(@cmd) == 0 or # XXX cvs $CPAN::Frontend->mydie("cvs import failed"); chdir($pwd) or $CPAN::Frontend->mydie(qq{Could not chdir to "$pwd": $!}); } #-> sub CPAN::Distribution::readme ; sub readme { my($self) = @_; my($dist) = $self->id; my($sans,$suffix) = $dist =~ /(.+)\.(tgz|tar[\._-]gz|tar\.Z|zip)$/; $self->debug("sans[$sans] suffix[$suffix]\n") if $CPAN::DEBUG; my($local_file); my($local_wanted) = File::Spec->catfile( $CPAN::Config->{keep_source_where}, "authors", "id", split(/\//,"$sans.readme"), ); $self->debug("Doing localize") if $CPAN::DEBUG; $local_file = CPAN::FTP->localize("authors/id/$sans.readme", $local_wanted) or $CPAN::Frontend->mydie(qq{No $sans.readme found});; if ($^O eq 'MacOS') { Mac::BuildTools::launch_file($local_file); return; } my $fh_pager = FileHandle->new; local($SIG{PIPE}) = "IGNORE"; my $pager = $CPAN::Config->{'pager'} || "cat"; $fh_pager->open("|$pager") or die "Could not open pager $pager\: $!"; my $fh_readme = FileHandle->new; $fh_readme->open($local_file) or $CPAN::Frontend->mydie(qq{Could not open "$local_file": $!}); $CPAN::Frontend->myprint(qq{ Displaying file $local_file with pager "$pager" }); $fh_pager->print(<$fh_readme>); $fh_pager->close; } #-> sub CPAN::Distribution::verifyCHECKSUM ; sub verifyCHECKSUM { my($self) = @_; EXCUSE: { my @e; $self->{CHECKSUM_STATUS} ||= ""; $self->{CHECKSUM_STATUS} eq "OK" and push @e, "Checksum was ok"; $CPAN::Frontend->myprint(join "", map {" $_\n"} @e) and return if @e; } my($lc_want,$lc_file,@local,$basename); @local = split(/\//,$self->id); pop @local; push @local, "CHECKSUMS"; $lc_want = File::Spec->catfile($CPAN::Config->{keep_source_where}, "authors", "id", @local); local($") = "/"; if (my $size = -s $lc_want) { $self->debug("lc_want[$lc_want]size[$size]") if $CPAN::DEBUG; if ($self->CHECKSUM_check_file($lc_want,1)) { return $self->{CHECKSUM_STATUS} = "OK"; } } $lc_file = CPAN::FTP->localize("authors/id/@local", $lc_want,1); unless ($lc_file) { $CPAN::Frontend->myprint("Trying $lc_want.gz\n"); $local[-1] .= ".gz"; $lc_file = CPAN::FTP->localize("authors/id/@local", "$lc_want.gz",1); if ($lc_file) { $lc_file =~ s/\.gz(?!\n)\Z//; eval{CPAN::Tarzip->new("$lc_file.gz")->gunzip($lc_file)}; } else { return; } } if ($self->CHECKSUM_check_file($lc_file)) { return $self->{CHECKSUM_STATUS} = "OK"; } } #-> sub CPAN::Distribution::SIG_check_file ; sub SIG_check_file { my($self,$chk_file) = @_; my $rv = eval { Module::Signature::_verify($chk_file) }; if ($rv == Module::Signature::SIGNATURE_OK()) { $CPAN::Frontend->myprint("Signature for $chk_file ok\n"); return $self->{SIG_STATUS} = "OK"; } else { $CPAN::Frontend->myprint(qq{\nSignature invalid for }. qq{distribution file. }. qq{Please investigate.\n\n}. $self->as_string, $CPAN::META->instance( 'CPAN::Author', $self->cpan_userid )->as_string); my $wrap = qq{I\'d recommend removing $chk_file. Its signature is invalid. Maybe you have configured your 'urllist' with a bad URL. Please check this array with 'o conf urllist', and retry.}; $CPAN::Frontend->mydie(Text::Wrap::wrap("","",$wrap)); } } #-> sub CPAN::Distribution::CHECKSUM_check_file ; # sloppy is 1 when we have an old checksums file that maybe is good # enough sub CHECKSUM_check_file { my($self,$chk_file,$sloppy) = @_; my($cksum,$file,$basename); $sloppy ||= 0; $self->debug("chk_file[$chk_file]sloppy[$sloppy]") if $CPAN::DEBUG; my $check_sigs = CPAN::HandleConfig->prefs_lookup($self, q{check_sigs}); if ($check_sigs) { if ($CPAN::META->has_inst("Module::Signature")) { $self->debug("Module::Signature is installed, verifying") if $CPAN::DEBUG; $self->SIG_check_file($chk_file); } else { $self->debug("Module::Signature is NOT installed") if $CPAN::DEBUG; } } $file = $self->{localfile}; $basename = File::Basename::basename($file); my $fh = FileHandle->new; if (open $fh, $chk_file) { local($/); my $eval = <$fh>; $eval =~ s/\015?\012/\n/g; close $fh; my($comp) = Safe->new(); $cksum = $comp->reval($eval); if ($@) { rename $chk_file, "$chk_file.bad"; Carp::confess($@) if $@; } } else { Carp::carp "Could not open $chk_file for reading"; } if (! ref $cksum or ref $cksum ne "HASH") { $CPAN::Frontend->mywarn(qq{ Warning: checksum file '$chk_file' broken. When trying to read that file I expected to get a hash reference for further processing, but got garbage instead. }); my $answer = CPAN::Shell::colorable_makemaker_prompt("Proceed nonetheless?", "no"); $answer =~ /^\s*y/i or $CPAN::Frontend->mydie("Aborted.\n"); $self->{CHECKSUM_STATUS} = "NIL -- CHECKSUMS file broken"; return; } elsif (exists $cksum->{$basename}{sha256}) { $self->debug("Found checksum for $basename:" . "$cksum->{$basename}{sha256}\n") if $CPAN::DEBUG; open($fh, $file); binmode $fh; my $eq = $self->eq_CHECKSUM($fh,$cksum->{$basename}{sha256}); $fh->close; $fh = CPAN::Tarzip->TIEHANDLE($file); unless ($eq) { my $dg = Digest::SHA->new(256); my($data,$ref); $ref = \$data; while ($fh->READ($ref, 4096) > 0) { $dg->add($data); } my $hexdigest = $dg->hexdigest; $eq += $hexdigest eq $cksum->{$basename}{'sha256-ungz'}; } if ($eq) { $CPAN::Frontend->myprint("Checksum for $file ok\n"); return $self->{CHECKSUM_STATUS} = "OK"; } else { $CPAN::Frontend->myprint(qq{\nChecksum mismatch for }. qq{distribution file. }. qq{Please investigate.\n\n}. $self->as_string, $CPAN::META->instance( 'CPAN::Author', $self->cpan_userid )->as_string); my $wrap = qq{I\'d recommend removing $file. Its checksum is incorrect. Maybe you have configured your 'urllist' with a bad URL. Please check this array with 'o conf urllist', and retry.}; $CPAN::Frontend->mydie(Text::Wrap::wrap("","",$wrap)); # former versions just returned here but this seems a # serious threat that deserves a die # $CPAN::Frontend->myprint("\n\n"); # sleep 3; # return; } # close $fh if fileno($fh); } else { return if $sloppy; unless ($self->{CHECKSUM_STATUS}) { $CPAN::Frontend->mywarn(qq{ Warning: No checksum for $basename in $chk_file. The cause for this may be that the file is very new and the checksum has not yet been calculated, but it may also be that something is going awry right now. }); my $answer = CPAN::Shell::colorable_makemaker_prompt("Proceed?", "yes"); $answer =~ /^\s*y/i or $CPAN::Frontend->mydie("Aborted.\n"); } $self->{CHECKSUM_STATUS} = "NIL -- distro not in CHECKSUMS file"; return; } } #-> sub CPAN::Distribution::eq_CHECKSUM ; sub eq_CHECKSUM { my($self,$fh,$expect) = @_; if ($CPAN::META->has_inst("Digest::SHA")) { my $dg = Digest::SHA->new(256); my($data); while (read($fh, $data, 4096)) { $dg->add($data); } my $hexdigest = $dg->hexdigest; # warn "fh[$fh] hex[$hexdigest] aexp[$expectMD5]"; return $hexdigest eq $expect; } return 1; } #-> sub CPAN::Distribution::force ; # Both CPAN::Modules and CPAN::Distributions know if "force" is in # effect by autoinspection, not by inspecting a global variable. One # of the reason why this was chosen to work that way was the treatment # of dependencies. They should not automatically inherit the force # status. But this has the downside that ^C and die() will return to # the prompt but will not be able to reset the force_update # attributes. We try to correct for it currently in the read_metadata # routine, and immediately before we check for a Signal. I hope this # works out in one of v1.57_53ff # "Force get forgets previous error conditions" #-> sub CPAN::Distribution::fforce ; sub fforce { my($self, $method) = @_; $self->force($method,1); } #-> sub CPAN::Distribution::force ; sub force { my($self, $method,$fforce) = @_; my %phase_map = ( get => [ "unwrapped", "build_dir", "archived", "localfile", "CHECKSUM_STATUS", "signature_verify", "prefs", "prefs_file", "prefs_file_doc", ], make => [ "writemakefile", "make", "modulebuild", "prereq_pm", "prereq_pm_detected", ], test => [ "badtestcnt", "make_test", ], install => [ "install", ], unknown => [ "reqtype", "yaml_content", ], ); my $methodmatch = 0; my $ldebug = 0; PHASE: for my $phase (qw(unknown get make test install)) { # order matters $methodmatch = 1 if $fforce || $phase eq $method; next unless $methodmatch; ATTRIBUTE: for my $att (@{$phase_map{$phase}}) { if ($phase eq "get") { if (substr($self->id,-1,1) eq "." && $att =~ /(unwrapped|build_dir|archived)/ ) { # cannot be undone for local distros next ATTRIBUTE; } if ($att eq "build_dir" && $self->{build_dir} && $CPAN::META->{is_tested} ) { delete $CPAN::META->{is_tested}{$self->{build_dir}}; } } elsif ($phase eq "test") { if ($att eq "make_test" && $self->{make_test} && $self->{make_test}{COMMANDID} && $self->{make_test}{COMMANDID} == $CPAN::CurrentCommandId ) { # endless loop too likely next ATTRIBUTE; } } delete $self->{$att}; if ($ldebug || $CPAN::DEBUG) { # local $CPAN::DEBUG = 16; # Distribution CPAN->debug(sprintf "id[%s]phase[%s]att[%s]", $self->id, $phase, $att); } } } if ($method && $method =~ /make|test|install/) { $self->{force_update} = 1; # name should probably have been force_install } } #-> sub CPAN::Distribution::notest ; sub notest { my($self, $method) = @_; # $CPAN::Frontend->mywarn("XDEBUG: set notest for $self $method"); $self->{"notest"}++; # name should probably have been force_install } #-> sub CPAN::Distribution::unnotest ; sub unnotest { my($self) = @_; # warn "XDEBUG: deleting notest"; delete $self->{notest}; } #-> sub CPAN::Distribution::unforce ; sub unforce { my($self) = @_; delete $self->{force_update}; } #-> sub CPAN::Distribution::isa_perl ; sub isa_perl { my($self) = @_; my $file = File::Basename::basename($self->id); if ($file =~ m{ ^ perl -? (5) ([._-]) ( \d{3}(_[0-4][0-9])? | \d+\.\d+ ) \.tar[._-](?:gz|bz2) (?!\n)\Z }xs) { return "$1.$3"; } elsif ($self->cpan_comment && $self->cpan_comment =~ /isa_perl\(.+?\)/) { return $1; } } #-> sub CPAN::Distribution::perl ; sub perl { my ($self) = @_; if (! $self) { use Carp qw(carp); carp __PACKAGE__ . "::perl was called without parameters."; } return CPAN::HandleConfig->safe_quote($CPAN::Perl); } #-> sub CPAN::Distribution::make ; sub make { my($self) = @_; if (my $goto = $self->prefs->{goto}) { return $self->goto($goto); } my $make = $self->{modulebuild} ? "Build" : "make"; # Emergency brake if they said install Pippi and get newest perl if ($self->isa_perl) { if ( $self->called_for ne $self->id && ! $self->{force_update} ) { # if we die here, we break bundles $CPAN::Frontend ->mywarn(sprintf( qq{The most recent version "%s" of the module "%s" is part of the perl-%s distribution. To install that, you need to run force install %s --or-- install %s }, $CPAN::META->instance( 'CPAN::Module', $self->called_for )->cpan_version, $self->called_for, $self->isa_perl, $self->called_for, $self->id, )); $self->{make} = CPAN::Distrostatus->new("NO isa perl"); $CPAN::Frontend->mysleep(1); return; } } $CPAN::Frontend->myprint(sprintf "Running %s for %s\n", $make, $self->id); $self->get; if ($self->{configure_requires_later}) { return; } local $ENV{PERL5LIB} = defined($ENV{PERL5LIB}) ? $ENV{PERL5LIB} : ($ENV{PERLLIB} || ""); $CPAN::META->set_perl5lib; local $ENV{MAKEFLAGS}; # protect us from outer make calls if ($CPAN::Signal) { delete $self->{force_update}; return; } my $builddir; EXCUSE: { my @e; if (!$self->{archived} || $self->{archived} eq "NO") { push @e, "Is neither a tar nor a zip archive."; } if (!$self->{unwrapped} || ( UNIVERSAL::can($self->{unwrapped},"failed") ? $self->{unwrapped}->failed : $self->{unwrapped} =~ /^NO/ )) { push @e, "Had problems unarchiving. Please build manually"; } unless ($self->{force_update}) { exists $self->{signature_verify} and ( UNIVERSAL::can($self->{signature_verify},"failed") ? $self->{signature_verify}->failed : $self->{signature_verify} =~ /^NO/ ) and push @e, "Did not pass the signature test."; } if (exists $self->{writemakefile} && ( UNIVERSAL::can($self->{writemakefile},"failed") ? $self->{writemakefile}->failed : $self->{writemakefile} =~ /^NO/ )) { # XXX maybe a retry would be in order? my $err = UNIVERSAL::can($self->{writemakefile},"text") ? $self->{writemakefile}->text : $self->{writemakefile}; $err =~ s/^NO\s*//; $err ||= "Had some problem writing Makefile"; $err .= ", won't make"; push @e, $err; } if (defined $self->{make}) { if (UNIVERSAL::can($self->{make},"failed") ? $self->{make}->failed : $self->{make} =~ /^NO/) { if ($self->{force_update}) { # Trying an already failed 'make' (unless somebody else blocks) } else { # introduced for turning recursion detection into a distrostatus my $error = length $self->{make}>3 ? substr($self->{make},3) : "Unknown error"; $CPAN::Frontend->mywarn("Could not make: $error\n"); $self->store_persistent_state; return; } } else { push @e, "Has already been made"; } } my $later = $self->{later} || $self->{configure_requires_later}; if ($later) { # see also undelay if ($later) { push @e, $later; } } $CPAN::Frontend->myprint(join "", map {" $_\n"} @e) and return if @e; $builddir = $self->dir or $CPAN::Frontend->mydie("PANIC: Cannot determine build directory\n"); unless (chdir $builddir) { push @e, "Couldn't chdir to '$builddir': $!"; } $CPAN::Frontend->mywarn(join "", map {" $_\n"} @e) and return if @e; } if ($CPAN::Signal) { delete $self->{force_update}; return; } $CPAN::Frontend->myprint("\n CPAN.pm: Going to build ".$self->id."\n\n"); $self->debug("Changed directory to $builddir") if $CPAN::DEBUG; if ($^O eq 'MacOS') { Mac::BuildTools::make($self); return; } my %env; while (my($k,$v) = each %ENV) { next unless defined $v; $env{$k} = $v; } local %ENV = %env; my $system; if (my $commandline = $self->prefs->{pl}{commandline}) { $system = $commandline; $ENV{PERL} = $^X; } elsif ($self->{'configure'}) { $system = $self->{'configure'}; } elsif ($self->{modulebuild}) { my($perl) = $self->perl or die "Couldn\'t find executable perl\n"; $system = "$perl Build.PL $CPAN::Config->{mbuildpl_arg}"; } else { my($perl) = $self->perl or die "Couldn\'t find executable perl\n"; my $switch = ""; # This needs a handler that can be turned on or off: # $switch = "-MExtUtils::MakeMaker ". # "-Mops=:default,:filesys_read,:filesys_open,require,chdir" # if $] > 5.00310; my $makepl_arg = $self->make_x_arg("pl"); $ENV{PERL5_CPAN_IS_EXECUTING} = File::Spec->catfile($self->{build_dir}, "Makefile.PL"); $system = sprintf("%s%s Makefile.PL%s", $perl, $switch ? " $switch" : "", $makepl_arg ? " $makepl_arg" : "", ); } if (my $env = $self->prefs->{pl}{env}) { for my $e (keys %$env) { $ENV{$e} = $env->{$e}; } } if (exists $self->{writemakefile}) { } else { local($SIG{ALRM}) = sub { die "inactivity_timeout reached\n" }; my($ret,$pid,$output); $@ = ""; my $go_via_alarm; if ($CPAN::Config->{inactivity_timeout}) { require Config; if ($Config::Config{d_alarm} && $Config::Config{d_alarm} eq "define" ) { $go_via_alarm++ } else { $CPAN::Frontend->mywarn("Warning: you have configured the config ". "variable 'inactivity_timeout' to ". "'$CPAN::Config->{inactivity_timeout}'. But ". "on this machine the system call 'alarm' ". "isn't available. This means that we cannot ". "provide the feature of intercepting long ". "waiting code and will turn this feature off.\n" ); $CPAN::Config->{inactivity_timeout} = 0; } } if ($go_via_alarm) { if ( $self->_should_report('pl') ) { ($output, $ret) = CPAN::Reporter::record_command( $system, $CPAN::Config->{inactivity_timeout}, ); CPAN::Reporter::grade_PL( $self, $system, $output, $ret ); } else { eval { alarm $CPAN::Config->{inactivity_timeout}; local $SIG{CHLD}; # = sub { wait }; if (defined($pid = fork)) { if ($pid) { #parent # wait; waitpid $pid, 0; } else { #child # note, this exec isn't necessary if # inactivity_timeout is 0. On the Mac I'd # suggest, we set it always to 0. exec $system; } } else { $CPAN::Frontend->myprint("Cannot fork: $!"); return; } }; alarm 0; if ($@) { kill 9, $pid; waitpid $pid, 0; my $err = "$@"; $CPAN::Frontend->myprint($err); $self->{writemakefile} = CPAN::Distrostatus->new("NO $err"); $@ = ""; $self->store_persistent_state; return $self->goodbye("$system -- TIMED OUT"); } } } else { if (my $expect_model = $self->_prefs_with_expect("pl")) { # XXX probably want to check _should_report here and warn # about not being able to use CPAN::Reporter with expect $ret = $self->_run_via_expect($system,$expect_model); if (! defined $ret && $self->{writemakefile} && $self->{writemakefile}->failed) { # timeout return; } } elsif ( $self->_should_report('pl') ) { ($output, $ret) = CPAN::Reporter::record_command($system); CPAN::Reporter::grade_PL( $self, $system, $output, $ret ); } else { $ret = system($system); } if ($ret != 0) { $self->{writemakefile} = CPAN::Distrostatus ->new("NO '$system' returned status $ret"); $CPAN::Frontend->mywarn("Warning: No success on command[$system]\n"); $self->store_persistent_state; return $self->goodbye("$system -- NOT OK"); } } if (-f "Makefile" || -f "Build") { $self->{writemakefile} = CPAN::Distrostatus->new("YES"); delete $self->{make_clean}; # if cleaned before, enable next } else { my $makefile = $self->{modulebuild} ? "Build" : "Makefile"; $self->{writemakefile} = CPAN::Distrostatus ->new(qq{NO -- No $makefile created}); $self->store_persistent_state; return $self->goodbye("$system -- NO $makefile created"); } } if ($CPAN::Signal) { delete $self->{force_update}; return; } if (my @prereq = $self->unsat_prereq("later")) { if ($prereq[0][0] eq "perl") { my $need = "requires perl '$prereq[0][1]'"; my $id = $self->pretty_id; $CPAN::Frontend->mywarn("$id $need; you have only $]; giving up\n"); $self->{make} = CPAN::Distrostatus->new("NO $need"); $self->store_persistent_state; return $self->goodbye("[prereq] -- NOT OK"); } else { my $follow = eval { $self->follow_prereqs("later",@prereq); }; if (0) { } elsif ($follow) { # signal success to the queuerunner return 1; } elsif ($@ && ref $@ && $@->isa("CPAN::Exception::RecursiveDependency")) { $CPAN::Frontend->mywarn($@); return $self->goodbye("[depend] -- NOT OK"); } } } if ($CPAN::Signal) { delete $self->{force_update}; return; } if (my $commandline = $self->prefs->{make}{commandline}) { $system = $commandline; $ENV{PERL} = CPAN::find_perl; } else { if ($self->{modulebuild}) { unless (-f "Build") { my $cwd = CPAN::anycwd(); $CPAN::Frontend->mywarn("Alert: no Build file available for 'make $self->{id}'". " in cwd[$cwd]. Danger, Will Robinson!\n"); $CPAN::Frontend->mysleep(5); } $system = join " ", $self->_build_command(), $CPAN::Config->{mbuild_arg}; } else { $system = join " ", $self->_make_command(), $CPAN::Config->{make_arg}; } $system =~ s/\s+$//; my $make_arg = $self->make_x_arg("make"); $system = sprintf("%s%s", $system, $make_arg ? " $make_arg" : "", ); } if (my $env = $self->prefs->{make}{env}) { # overriding the local # ENV of PL, not the # outer ENV, but # unlikely to be a risk for my $e (keys %$env) { $ENV{$e} = $env->{$e}; } } my $expect_model = $self->_prefs_with_expect("make"); my $want_expect = 0; if ( $expect_model && @{$expect_model->{talk}} ) { my $can_expect = $CPAN::META->has_inst("Expect"); if ($can_expect) { $want_expect = 1; } else { $CPAN::Frontend->mywarn("Expect not installed, falling back to ". "system()\n"); } } my $system_ok; if ($want_expect) { # XXX probably want to check _should_report here and # warn about not being able to use CPAN::Reporter with expect $system_ok = $self->_run_via_expect($system,$expect_model) == 0; } elsif ( $self->_should_report('make') ) { my ($output, $ret) = CPAN::Reporter::record_command($system); CPAN::Reporter::grade_make( $self, $system, $output, $ret ); $system_ok = ! $ret; } else { $system_ok = system($system) == 0; } $self->introduce_myself; if ( $system_ok ) { $CPAN::Frontend->myprint(" $system -- OK\n"); $self->{make} = CPAN::Distrostatus->new("YES"); } else { $self->{writemakefile} ||= CPAN::Distrostatus->new("YES"); $self->{make} = CPAN::Distrostatus->new("NO"); $CPAN::Frontend->mywarn(" $system -- NOT OK\n"); } $self->store_persistent_state; } # CPAN::Distribution::goodbye ; sub goodbye { my($self,$goodbye) = @_; my $id = $self->pretty_id; $CPAN::Frontend->mywarn(" $id\n $goodbye\n"); return; } # CPAN::Distribution::_run_via_expect ; sub _run_via_expect { my($self,$system,$expect_model) = @_; CPAN->debug("system[$system]expect_model[$expect_model]") if $CPAN::DEBUG; if ($CPAN::META->has_inst("Expect")) { my $expo = Expect->new; # expo Expect object; $expo->spawn($system); $expect_model->{mode} ||= "deterministic"; if ($expect_model->{mode} eq "deterministic") { return $self->_run_via_expect_deterministic($expo,$expect_model); } elsif ($expect_model->{mode} eq "anyorder") { return $self->_run_via_expect_anyorder($expo,$expect_model); } else { die "Panic: Illegal expect mode: $expect_model->{mode}"; } } else { $CPAN::Frontend->mywarn("Expect not installed, falling back to system()\n"); return system($system); } } sub _run_via_expect_anyorder { my($self,$expo,$expect_model) = @_; my $timeout = $expect_model->{timeout} || 5; my $reuse = $expect_model->{reuse}; my @expectacopy = @{$expect_model->{talk}}; # we trash it! my $but = ""; EXPECT: while () { my($eof,$ran_into_timeout); my @match = $expo->expect($timeout, [ eof => sub { $eof++; } ], [ timeout => sub { $ran_into_timeout++; } ], -re => eval"qr{.}", ); if ($match[2]) { $but .= $match[2]; } $but .= $expo->clear_accum; if ($eof) { $expo->soft_close; return $expo->exitstatus(); } elsif ($ran_into_timeout) { # warn "DEBUG: they are asking a question, but[$but]"; for (my $i = 0; $i <= $#expectacopy; $i+=2) { my($next,$send) = @expectacopy[$i,$i+1]; my $regex = eval "qr{$next}"; # warn "DEBUG: will compare with regex[$regex]."; if ($but =~ /$regex/) { # warn "DEBUG: will send send[$send]"; $expo->send($send); # never allow reusing an QA pair unless they told us splice @expectacopy, $i, 2 unless $reuse; next EXPECT; } } my $why = "could not answer a question during the dialog"; $CPAN::Frontend->mywarn("Failing: $why\n"); $self->{writemakefile} = CPAN::Distrostatus->new("NO $why"); return; } } } sub _run_via_expect_deterministic { my($self,$expo,$expect_model) = @_; my $ran_into_timeout; my $timeout = $expect_model->{timeout} || 15; # currently unsettable my $expecta = $expect_model->{talk}; EXPECT: for (my $i = 0; $i <= $#$expecta; $i+=2) { my($re,$send) = @$expecta[$i,$i+1]; CPAN->debug("timeout[$timeout]re[$re]") if $CPAN::DEBUG; my $regex = eval "qr{$re}"; $expo->expect($timeout, [ eof => sub { my $but = $expo->clear_accum; $CPAN::Frontend->mywarn("EOF (maybe harmless) expected[$regex]\nbut[$but]\n\n"); last EXPECT; } ], [ timeout => sub { my $but = $expo->clear_accum; $CPAN::Frontend->mywarn("TIMEOUT expected[$regex]\nbut[$but]\n\n"); $ran_into_timeout++; } ], -re => $regex); if ($ran_into_timeout) { # note that the caller expects 0 for success $self->{writemakefile} = CPAN::Distrostatus->new("NO timeout during expect dialog"); return; } $expo->send($send); } $expo->soft_close; return $expo->exitstatus(); } #-> CPAN::Distribution::_validate_distropref sub _validate_distropref { my($self,@args) = @_; if ( $CPAN::META->has_inst("CPAN::Kwalify") && $CPAN::META->has_inst("Kwalify") ) { eval {CPAN::Kwalify::_validate("distroprefs",@args);}; if ($@) { $CPAN::Frontend->mywarn($@); } } else { CPAN->debug("not validating '@args'") if $CPAN::DEBUG; } } #-> CPAN::Distribution::_find_prefs sub _find_prefs { my($self) = @_; my $distroid = $self->pretty_id; #CPAN->debug("distroid[$distroid]") if $CPAN::DEBUG; my $prefs_dir = $CPAN::Config->{prefs_dir}; return if $prefs_dir =~ /^\s*$/; eval { File::Path::mkpath($prefs_dir); }; if ($@) { $CPAN::Frontend->mydie("Cannot create directory $prefs_dir"); } my $yaml_module = CPAN::_yaml_module; my @extensions; if ($CPAN::META->has_inst($yaml_module)) { push @extensions, "yml"; } else { my @fallbacks; if ($CPAN::META->has_inst("Data::Dumper")) { push @extensions, "dd"; push @fallbacks, "Data::Dumper"; } if ($CPAN::META->has_inst("Storable")) { push @extensions, "st"; push @fallbacks, "Storable"; } if (@fallbacks) { local $" = " and "; unless ($self->{have_complained_about_missing_yaml}++) { $CPAN::Frontend->mywarn("'$yaml_module' not installed, falling back ". "to @fallbacks to read prefs '$prefs_dir'\n"); } } else { unless ($self->{have_complained_about_missing_yaml}++) { $CPAN::Frontend->mywarn("'$yaml_module' not installed, cannot ". "read prefs '$prefs_dir'\n"); } } } if (@extensions) { my $dh = DirHandle->new($prefs_dir) or die Carp::croak("Couldn't open '$prefs_dir': $!"); DIRENT: for (sort $dh->read) { next if $_ eq "." || $_ eq ".."; my $exte = join "|", @extensions; next unless /\.($exte)$/; my $thisexte = $1; my $abs = File::Spec->catfile($prefs_dir, $_); if (-f $abs) { #CPAN->debug(sprintf "abs[%s]", $abs) if $CPAN::DEBUG; my @distropref; if ($thisexte eq "yml") { # need no eval because if we have no YAML we do not try to read *.yml #CPAN->debug(sprintf "before yaml load abs[%s]", $abs) if $CPAN::DEBUG; @distropref = @{CPAN->_yaml_loadfile($abs)}; #CPAN->debug(sprintf "after yaml load abs[%s]", $abs) if $CPAN::DEBUG; } elsif ($thisexte eq "dd") { package CPAN::Eval; no strict; open FH, "<$abs" or $CPAN::Frontend->mydie("Could not open '$abs': $!"); local $/; my $eval = <FH>; close FH; eval $eval; if ($@) { $CPAN::Frontend->mydie("Error in distroprefs file $_\: $@"); } my $i = 1; while (${"VAR".$i}) { push @distropref, ${"VAR".$i}; $i++; } } elsif ($thisexte eq "st") { # eval because Storable is never forward compatible eval { @distropref = @{scalar Storable::retrieve($abs)}; }; if ($@) { $CPAN::Frontend->mywarn("Error reading distroprefs file ". "$_, skipping\: $@"); $CPAN::Frontend->mysleep(4); next DIRENT; } } # $DB::single=1; #CPAN->debug(sprintf "#distropref[%d]", scalar @distropref) if $CPAN::DEBUG; ELEMENT: for my $y (0..$#distropref) { my $distropref = $distropref[$y]; $self->_validate_distropref($distropref,$abs,$y); my $match = $distropref->{match}; unless ($match) { #CPAN->debug("no 'match' in abs[$abs], skipping") if $CPAN::DEBUG; next ELEMENT; } my $ok = 1; # do not take the order of C<keys %$match> because # "module" is by far the slowest my $saw_valid_subkeys = 0; for my $sub_attribute (qw(distribution perl perlconfig module)) { next unless exists $match->{$sub_attribute}; $saw_valid_subkeys++; my $qr = eval "qr{$distropref->{match}{$sub_attribute}}"; if ($sub_attribute eq "module") { my $okm = 0; #CPAN->debug(sprintf "distropref[%d]", scalar @distropref) if $CPAN::DEBUG; my @modules = $self->containsmods; #CPAN->debug(sprintf "modules[%s]", join(",",@modules)) if $CPAN::DEBUG; MODULE: for my $module (@modules) { $okm ||= $module =~ /$qr/; last MODULE if $okm; } $ok &&= $okm; } elsif ($sub_attribute eq "distribution") { my $okd = $distroid =~ /$qr/; $ok &&= $okd; } elsif ($sub_attribute eq "perl") { my $okp = CPAN::find_perl =~ /$qr/; $ok &&= $okp; } elsif ($sub_attribute eq "perlconfig") { for my $perlconfigkey (keys %{$match->{perlconfig}}) { my $perlconfigval = $match->{perlconfig}->{$perlconfigkey}; # XXX should probably warn if Config does not exist my $okpc = $Config::Config{$perlconfigkey} =~ /$perlconfigval/; $ok &&= $okpc; last if $ok == 0; } } else { $CPAN::Frontend->mydie("Nonconforming .$thisexte file '$abs': ". "unknown sub_attribut '$sub_attribute'. ". "Please ". "remove, cannot continue."); } last if $ok == 0; # short circuit } unless ($saw_valid_subkeys) { $CPAN::Frontend->mydie("Nonconforming .$thisexte file '$abs': ". "missing match/* subattribute. ". "Please ". "remove, cannot continue."); } #CPAN->debug(sprintf "ok[%d]", $ok) if $CPAN::DEBUG; if ($ok) { return { prefs => $distropref, prefs_file => $abs, prefs_file_doc => $y, }; } } } } $dh->close; } return; } # CPAN::Distribution::prefs sub prefs { my($self) = @_; if (exists $self->{negative_prefs_cache} && $self->{negative_prefs_cache} != $CPAN::CurrentCommandId ) { delete $self->{negative_prefs_cache}; delete $self->{prefs}; } if (exists $self->{prefs}) { return $self->{prefs}; # XXX comment out during debugging } if ($CPAN::Config->{prefs_dir}) { CPAN->debug("prefs_dir[$CPAN::Config->{prefs_dir}]") if $CPAN::DEBUG; my $prefs = $self->_find_prefs(); $prefs ||= ""; # avoid warning next line CPAN->debug("prefs[$prefs]") if $CPAN::DEBUG; if ($prefs) { for my $x (qw(prefs prefs_file prefs_file_doc)) { $self->{$x} = $prefs->{$x}; } my $bs = sprintf( "%s[%s]", File::Basename::basename($self->{prefs_file}), $self->{prefs_file_doc}, ); my $filler1 = "_" x 22; my $filler2 = int(66 - length($bs))/2; $filler2 = 0 if $filler2 < 0; $filler2 = " " x $filler2; $CPAN::Frontend->myprint(" $filler1 D i s t r o P r e f s $filler1 $filler2 $bs $filler2 "); $CPAN::Frontend->mysleep(1); return $self->{prefs}; } } $self->{negative_prefs_cache} = $CPAN::CurrentCommandId; return $self->{prefs} = +{}; } # CPAN::Distribution::make_x_arg sub make_x_arg { my($self, $whixh) = @_; my $make_x_arg; my $prefs = $self->prefs; if ( $prefs && exists $prefs->{$whixh} && exists $prefs->{$whixh}{args} && $prefs->{$whixh}{args} ) { $make_x_arg = join(" ", map {CPAN::HandleConfig ->safe_quote($_)} @{$prefs->{$whixh}{args}}, ); } my $what = sprintf "make%s_arg", $whixh eq "make" ? "" : $whixh; $make_x_arg ||= $CPAN::Config->{$what}; return $make_x_arg; } # CPAN::Distribution::_make_command sub _make_command { my ($self) = @_; if ($self) { return CPAN::HandleConfig ->safe_quote( CPAN::HandleConfig->prefs_lookup($self, q{make}) || $Config::Config{make} || 'make' ); } else { # Old style call, without object. Deprecated Carp::confess("CPAN::_make_command() used as function. Don't Do That."); return safe_quote(undef, CPAN::HandleConfig->prefs_lookup($self,q{make}) || $CPAN::Config->{make} || $Config::Config{make} || 'make'); } } #-> sub CPAN::Distribution::follow_prereqs ; sub follow_prereqs { my($self) = shift; my($slot) = shift; my(@prereq_tuples) = grep {$_->[0] ne "perl"} @_; return unless @prereq_tuples; my @prereq = map { $_->[0] } @prereq_tuples; my $pretty_id = $self->pretty_id; my %map = ( b => "build_requires", r => "requires", c => "commandline", ); my($filler1,$filler2,$filler3,$filler4); # $DB::single=1; my $unsat = "Unsatisfied dependencies detected during"; my $w = length($unsat) > length($pretty_id) ? length($unsat) : length($pretty_id); { my $r = int(($w - length($unsat))/2); my $l = $w - length($unsat) - $r; $filler1 = "-"x4 . " "x$l; $filler2 = " "x$r . "-"x4 . "\n"; } { my $r = int(($w - length($pretty_id))/2); my $l = $w - length($pretty_id) - $r; $filler3 = "-"x4 . " "x$l; $filler4 = " "x$r . "-"x4 . "\n"; } $CPAN::Frontend-> myprint("$filler1 $unsat $filler2". "$filler3 $pretty_id $filler4". join("", map {" $_->[0] \[$map{$_->[1]}]\n"} @prereq_tuples), ); my $follow = 0; if ($CPAN::Config->{prerequisites_policy} eq "follow") { $follow = 1; } elsif ($CPAN::Config->{prerequisites_policy} eq "ask") { my $answer = CPAN::Shell::colorable_makemaker_prompt( "Shall I follow them and prepend them to the queue of modules we are processing right now?", "yes"); $follow = $answer =~ /^\s*y/i; } else { local($") = ", "; $CPAN::Frontend-> myprint(" Ignoring dependencies on modules @prereq\n"); } if ($follow) { my $id = $self->id; # color them as dirty for my $p (@prereq) { # warn "calling color_cmd_tmps(0,1)"; my $any = CPAN::Shell->expandany($p); $self->{$slot . "_for"}{$any->id}++; if ($any) { $any->color_cmd_tmps(0,2); } else { $CPAN::Frontend->mywarn("Warning (maybe a bug): Cannot expand prereq '$p'\n"); $CPAN::Frontend->mysleep(2); } } # queue them and re-queue yourself CPAN::Queue->jumpqueue({qmod => $id, reqtype => $self->{reqtype}}, map {+{qmod=>$_->[0],reqtype=>$_->[1]}} reverse @prereq_tuples); $self->{$slot} = "Delayed until after prerequisites"; return 1; # signal success to the queuerunner } return; } #-> sub CPAN::Distribution::unsat_prereq ; # return ([Foo=>1],[Bar=>1.2]) for normal modules # return ([perl=>5.008]) if we need a newer perl than we are running under sub unsat_prereq { my($self,$slot) = @_; my(%merged,$prereq_pm); my $prefs_depends = $self->prefs->{depends}||{}; if ($slot eq "configure_requires_later") { my $meta_yml = $self->parse_meta_yml(); %merged = (%{$meta_yml->{configure_requires}||{}}, %{$prefs_depends->{configure_requires}||{}}); $prereq_pm = {}; # configure_requires defined as "b" } elsif ($slot eq "later") { my $prereq_pm_0 = $self->prereq_pm || {}; for my $reqtype (qw(requires build_requires)) { $prereq_pm->{$reqtype} = {%{$prereq_pm_0->{$reqtype}||{}}}; # copy to not pollute it for my $k (keys %{$prefs_depends->{$reqtype}||{}}) { $prereq_pm->{$reqtype}{$k} = $prefs_depends->{$reqtype}{$k}; } } %merged = (%{$prereq_pm->{requires}||{}},%{$prereq_pm->{build_requires}||{}}); } else { die "Panic: illegal slot '$slot'"; } my(@need); my @merged = %merged; CPAN->debug("all merged_prereqs[@merged]") if $CPAN::DEBUG; NEED: while (my($need_module, $need_version) = each %merged) { my($available_version,$available_file,$nmo); if ($need_module eq "perl") { $available_version = $]; $available_file = CPAN::find_perl; } else { $nmo = $CPAN::META->instance("CPAN::Module",$need_module); next if $nmo->uptodate; $available_file = $nmo->available_file; # if they have not specified a version, we accept any installed one if (defined $available_file and ( # a few quick shortcurcuits not defined $need_version or $need_version eq '0' # "==" would trigger warning when not numeric or $need_version eq "undef" )) { next NEED; } $available_version = $nmo->available_version; } # We only want to install prereqs if either they're not installed # or if the installed version is too old. We cannot omit this # check, because if 'force' is in effect, nobody else will check. if (defined $available_file) { my(@all_requirements) = split /\s*,\s*/, $need_version; local($^W) = 0; my $ok = 0; RQ: for my $rq (@all_requirements) { if ($rq =~ s|>=\s*||) { } elsif ($rq =~ s|>\s*||) { # 2005-12: one user if (CPAN::Version->vgt($available_version,$rq)) { $ok++; } next RQ; } elsif ($rq =~ s|!=\s*||) { # 2005-12: no user if (CPAN::Version->vcmp($available_version,$rq)) { $ok++; next RQ; } else { last RQ; } } elsif ($rq =~ m|<=?\s*|) { # 2005-12: no user $CPAN::Frontend->mywarn("Downgrading not supported (rq[$rq])\n"); $ok++; next RQ; } if (! CPAN::Version->vgt($rq, $available_version)) { $ok++; } CPAN->debug(sprintf("need_module[%s]available_file[%s]". "available_version[%s]rq[%s]ok[%d]", $need_module, $available_file, $available_version, CPAN::Version->readable($rq), $ok, )) if $CPAN::DEBUG; } next NEED if $ok == @all_requirements; } if ($need_module eq "perl") { return ["perl", $need_version]; } $self->{sponsored_mods}{$need_module} ||= 0; CPAN->debug("need_module[$need_module]s/s/n[$self->{sponsored_mods}{$need_module}]") if $CPAN::DEBUG; if ($self->{sponsored_mods}{$need_module}++) { # We have already sponsored it and for some reason it's still # not available. So we do ... what?? # if we push it again, we have a potential infinite loop # The following "next" was a very problematic construct. # It helped a lot but broke some day and had to be # replaced. # We must be able to deal with modules that come again and # again as a prereq and have themselves prereqs and the # queue becomes long but finally we would find the correct # order. The RecursiveDependency check should trigger a # die when it's becoming too weird. Unfortunately removing # this next breaks many other things. # The bug that brought this up is described in Todo under # "5.8.9 cannot install Compress::Zlib" # next; # this is the next that had to go away # The following "next NEED" are fine and the error message # explains well what is going on. For example when the DBI # fails and consequently DBD::SQLite fails and now we are # processing CPAN::SQLite. Then we must have a "next" for # DBD::SQLite. How can we get it and how can we identify # all other cases we must identify? my $do = $nmo->distribution; next NEED unless $do; # not on CPAN if (CPAN::Version->vcmp($need_version, $nmo->ro->{CPAN_VERSION}) > 0){ $CPAN::Frontend->mywarn("Warning: Prerequisite ". "'$need_module => $need_version' ". "for '$self->{ID}' seems ". "not available according to the indexes\n" ); next NEED; } NOSAYER: for my $nosayer ( "unwrapped", "writemakefile", "signature_verify", "make", "make_test", "install", "make_clean", ) { if ($do->{$nosayer}) { if (UNIVERSAL::can($do->{$nosayer},"failed") ? $do->{$nosayer}->failed : $do->{$nosayer} =~ /^NO/) { if ($nosayer eq "make_test" && $do->{make_test}{COMMANDID} != $CPAN::CurrentCommandId ) { next NOSAYER; } $CPAN::Frontend->mywarn("Warning: Prerequisite ". "'$need_module => $need_version' ". "for '$self->{ID}' failed when ". "processing '$do->{ID}' with ". "'$nosayer => $do->{$nosayer}'. Continuing, ". "but chances to succeed are limited.\n" ); next NEED; } else { # the other guy succeeded if ($nosayer eq "install") { # we had this with # DMAKI/DateTime-Calendar-Chinese-0.05.tar.gz # 2007-03 $CPAN::Frontend->mywarn("Warning: Prerequisite ". "'$need_module => $need_version' ". "for '$self->{ID}' already installed ". "but installation looks suspicious. ". "Skipping another installation attempt, ". "to prevent looping endlessly.\n" ); next NEED; } } } } } my $needed_as = exists $prereq_pm->{requires}{$need_module} ? "r" : "b"; push @need, [$need_module,$needed_as]; } my @unfolded = map { "[".join(",",@$_)."]" } @need; CPAN->debug("returning from unsat_prereq[@unfolded]") if $CPAN::DEBUG; @need; } #-> sub CPAN::Distribution::read_yaml ; sub read_yaml { my($self) = @_; return $self->{yaml_content} if exists $self->{yaml_content}; my $build_dir = $self->{build_dir}; my $yaml = File::Spec->catfile($build_dir,"META.yml"); $self->debug("yaml[$yaml]") if $CPAN::DEBUG; return unless -f $yaml; eval { $self->{yaml_content} = CPAN->_yaml_loadfile($yaml)->[0]; }; if ($@) { $CPAN::Frontend->mywarn("Could not read ". "'$yaml'. Falling back to other ". "methods to determine prerequisites\n"); return $self->{yaml_content} = undef; # if we die, then we # cannot read YAML's own # META.yml } # not "authoritative" if (not exists $self->{yaml_content}{dynamic_config} or $self->{yaml_content}{dynamic_config} ) { $self->{yaml_content} = undef; } $self->debug(sprintf "yaml_content[%s]", $self->{yaml_content} || "UNDEF") if $CPAN::DEBUG; return $self->{yaml_content}; } #-> sub CPAN::Distribution::prereq_pm ; sub prereq_pm { my($self) = @_; $self->{prereq_pm_detected} ||= 0; CPAN->debug("ID[$self->{ID}]prereq_pm_detected[$self->{prereq_pm_detected}]") if $CPAN::DEBUG; return $self->{prereq_pm} if $self->{prereq_pm_detected}; return unless $self->{writemakefile} # no need to have succeeded # but we must have run it || $self->{modulebuild}; CPAN->debug(sprintf "writemakefile[%s]modulebuild[%s]", $self->{writemakefile}||"", $self->{modulebuild}||"", ) if $CPAN::DEBUG; my($req,$breq); if (my $yaml = $self->read_yaml) { # often dynamic_config prevents a result here $req = $yaml->{requires} || {}; $breq = $yaml->{build_requires} || {}; undef $req unless ref $req eq "HASH" && %$req; if ($req) { if ($yaml->{generated_by} && $yaml->{generated_by} =~ /ExtUtils::MakeMaker version ([\d\._]+)/) { my $eummv = do { local $^W = 0; $1+0; }; if ($eummv < 6.2501) { # thanks to Slaven for digging that out: MM before # that could be wrong because it could reflect a # previous release undef $req; } } my $areq; my $do_replace; while (my($k,$v) = each %{$req||{}}) { if ($v =~ /\d/) { $areq->{$k} = $v; } elsif ($k =~ /[A-Za-z]/ && $v =~ /[A-Za-z]/ && $CPAN::META->exists("Module",$v) ) { $CPAN::Frontend->mywarn("Suspicious key-value pair in META.yml's ". "requires hash: $k => $v; I'll take both ". "key and value as a module name\n"); $CPAN::Frontend->mysleep(1); $areq->{$k} = 0; $areq->{$v} = 0; $do_replace++; } } $req = $areq if $do_replace; } } unless ($req || $breq) { my $build_dir = $self->{build_dir} or die "Panic: no build_dir?"; my $makefile = File::Spec->catfile($build_dir,"Makefile"); my $fh; if (-f $makefile and $fh = FileHandle->new("<$makefile\0")) { CPAN->debug("Getting prereq from Makefile") if $CPAN::DEBUG; local($/) = "\n"; while (<$fh>) { last if /MakeMaker post_initialize section/; my($p) = m{^[\#] \s+PREREQ_PM\s+=>\s+(.+) }x; next unless $p; # warn "Found prereq expr[$p]"; # Regexp modified by A.Speer to remember actual version of file # PREREQ_PM hash key wants, then add to while ( $p =~ m/(?:\s)([\w\:]+)=>(q\[.*?\]|undef),?/g ) { # In case a prereq is mentioned twice, complain. if ( defined $req->{$1} ) { warn "Warning: PREREQ_PM mentions $1 more than once, ". "last mention wins"; } my($m,$n) = ($1,$2); if ($n =~ /^q\[(.*?)\]$/) { $n = $1; } $req->{$m} = $n; } last; } } } unless ($req || $breq) { my $build_dir = $self->{build_dir} or die "Panic: no build_dir?"; my $buildfile = File::Spec->catfile($build_dir,"Build"); if (-f $buildfile) { CPAN->debug("Found '$buildfile'") if $CPAN::DEBUG; my $build_prereqs = File::Spec->catfile($build_dir,"_build","prereqs"); if (-f $build_prereqs) { CPAN->debug("Getting prerequisites from '$build_prereqs'") if $CPAN::DEBUG; my $content = do { local *FH; open FH, $build_prereqs or $CPAN::Frontend->mydie("Could not open ". "'$build_prereqs': $!"); local $/; <FH>; }; my $bphash = eval $content; if ($@) { } else { $req = $bphash->{requires} || +{}; $breq = $bphash->{build_requires} || +{}; } } } } if (-f "Build.PL" && ! -f "Makefile.PL" && ! exists $req->{"Module::Build"} && ! $CPAN::META->has_inst("Module::Build")) { $CPAN::Frontend->mywarn(" Warning: CPAN.pm discovered Module::Build as ". "undeclared prerequisite.\n". " Adding it now as such.\n" ); $CPAN::Frontend->mysleep(5); $req->{"Module::Build"} = 0; delete $self->{writemakefile}; } if ($req || $breq) { $self->{prereq_pm_detected}++; return $self->{prereq_pm} = { requires => $req, build_requires => $breq }; } } #-> sub CPAN::Distribution::test ; sub test { my($self) = @_; if (my $goto = $self->prefs->{goto}) { return $self->goto($goto); } $self->make; if ($CPAN::Signal) { delete $self->{force_update}; return; } # warn "XDEBUG: checking for notest: $self->{notest} $self"; if ($self->{notest}) { $CPAN::Frontend->myprint("Skipping test because of notest pragma\n"); return 1; } my $make = $self->{modulebuild} ? "Build" : "make"; local $ENV{PERL5LIB} = defined($ENV{PERL5LIB}) ? $ENV{PERL5LIB} : ($ENV{PERLLIB} || ""); $CPAN::META->set_perl5lib; local $ENV{MAKEFLAGS}; # protect us from outer make calls $CPAN::Frontend->myprint("Running $make test\n"); EXCUSE: { my @e; if ($self->{make} or $self->{later}) { # go ahead } else { push @e, "Make had some problems, won't test"; } exists $self->{make} and ( UNIVERSAL::can($self->{make},"failed") ? $self->{make}->failed : $self->{make} =~ /^NO/ ) and push @e, "Can't test without successful make"; $self->{badtestcnt} ||= 0; if ($self->{badtestcnt} > 0) { require Data::Dumper; CPAN->debug(sprintf "NOREPEAT[%s]", Data::Dumper::Dumper($self)) if $CPAN::DEBUG; push @e, "Won't repeat unsuccessful test during this command"; } push @e, $self->{later} if $self->{later}; push @e, $self->{configure_requires_later} if $self->{configure_requires_later}; if (exists $self->{build_dir}) { if (exists $self->{make_test}) { if ( UNIVERSAL::can($self->{make_test},"failed") ? $self->{make_test}->failed : $self->{make_test} =~ /^NO/ ) { if ( UNIVERSAL::can($self->{make_test},"commandid") && $self->{make_test}->commandid == $CPAN::CurrentCommandId ) { push @e, "Has already been tested within this command"; } } else { push @e, "Has already been tested successfully"; } } } elsif (!@e) { push @e, "Has no own directory"; } $CPAN::Frontend->myprint(join "", map {" $_\n"} @e) and return if @e; unless (chdir $self->{build_dir}) { push @e, "Couldn't chdir to '$self->{build_dir}': $!"; } $CPAN::Frontend->mywarn(join "", map {" $_\n"} @e) and return if @e; } $self->debug("Changed directory to $self->{build_dir}") if $CPAN::DEBUG; if ($^O eq 'MacOS') { Mac::BuildTools::make_test($self); return; } if ($self->{modulebuild}) { my $v = CPAN::Shell->expand("Module","Test::Harness")->inst_version; if (CPAN::Version->vlt($v,2.62)) { $CPAN::Frontend->mywarn(qq{The version of your Test::Harness is only '$v', you need at least '2.62'. Please upgrade your Test::Harness.\n}); $self->{make_test} = CPAN::Distrostatus->new("NO Test::Harness too old"); return; } } my $system; my $prefs_test = $self->prefs->{test}; if (my $commandline = exists $prefs_test->{commandline} ? $prefs_test->{commandline} : "") { $system = $commandline; $ENV{PERL} = CPAN::find_perl; } elsif ($self->{modulebuild}) { $system = sprintf "%s test", $self->_build_command(); } else { $system = join " ", $self->_make_command(), "test"; } my $make_test_arg = $self->make_x_arg("test"); $system = sprintf("%s%s", $system, $make_test_arg ? " $make_test_arg" : "", ); my($tests_ok); my %env; while (my($k,$v) = each %ENV) { next unless defined $v; $env{$k} = $v; } local %ENV = %env; if (my $env = $self->prefs->{test}{env}) { for my $e (keys %$env) { $ENV{$e} = $env->{$e}; } } my $expect_model = $self->_prefs_with_expect("test"); my $want_expect = 0; if ( $expect_model && @{$expect_model->{talk}} ) { my $can_expect = $CPAN::META->has_inst("Expect"); if ($can_expect) { $want_expect = 1; } else { $CPAN::Frontend->mywarn("Expect not installed, falling back to ". "testing without\n"); } } if ($want_expect) { if ($self->_should_report('test')) { $CPAN::Frontend->mywarn("Reporting via CPAN::Reporter is currently ". "not supported when distroprefs specify ". "an interactive test\n"); } $tests_ok = $self->_run_via_expect($system,$expect_model) == 0; } elsif ( $self->_should_report('test') ) { $tests_ok = CPAN::Reporter::test($self, $system); } else { $tests_ok = system($system) == 0; } $self->introduce_myself; if ( $tests_ok ) { { my @prereq; # local $CPAN::DEBUG = 16; # Distribution for my $m (keys %{$self->{sponsored_mods}}) { next unless $self->{sponsored_mods}{$m} > 0; my $m_obj = CPAN::Shell->expand("Module",$m) or next; # XXX we need available_version which reflects # $ENV{PERL5LIB} so that already tested but not yet # installed modules are counted. my $available_version = $m_obj->available_version; my $available_file = $m_obj->available_file; if ($available_version && !CPAN::Version->vlt($available_version,$self->{prereq_pm}{$m}) ) { CPAN->debug("m[$m] good enough available_version[$available_version]") if $CPAN::DEBUG; } elsif ($available_file && ( !$self->{prereq_pm}{$m} || $self->{prereq_pm}{$m} == 0 ) ) { # lex Class::Accessor::Chained::Fast which has no $VERSION CPAN->debug("m[$m] have available_file[$available_file]") if $CPAN::DEBUG; } else { push @prereq, $m; } } if (@prereq) { my $cnt = @prereq; my $which = join ",", @prereq; my $but = $cnt == 1 ? "one dependency not OK ($which)" : "$cnt dependencies missing ($which)"; $CPAN::Frontend->mywarn("Tests succeeded but $but\n"); $self->{make_test} = CPAN::Distrostatus->new("NO $but"); $self->store_persistent_state; return $self->goodbye("[dependencies] -- NA"); } } $CPAN::Frontend->myprint(" $system -- OK\n"); $self->{make_test} = CPAN::Distrostatus->new("YES"); $CPAN::META->is_tested($self->{build_dir},$self->{make_test}{TIME}); # probably impossible to need the next line because badtestcnt # has a lifespan of one command delete $self->{badtestcnt}; } else { $self->{make_test} = CPAN::Distrostatus->new("NO"); $self->{badtestcnt}++; $CPAN::Frontend->mywarn(" $system -- NOT OK\n"); CPAN::Shell->optprint ("hint", sprintf ("//hint// to see the cpan-testers results for installing this module, try: reports %s\n", $self->pretty_id)); } $self->store_persistent_state; } sub _prefs_with_expect { my($self,$where) = @_; return unless my $prefs = $self->prefs; return unless my $where_prefs = $prefs->{$where}; if ($where_prefs->{expect}) { return { mode => "deterministic", timeout => 15, talk => $where_prefs->{expect}, }; } elsif ($where_prefs->{"eexpect"}) { return $where_prefs->{"eexpect"}; } return; } #-> sub CPAN::Distribution::clean ; sub clean { my($self) = @_; my $make = $self->{modulebuild} ? "Build" : "make"; $CPAN::Frontend->myprint("Running $make clean\n"); unless (exists $self->{archived}) { $CPAN::Frontend->mywarn("Distribution seems to have never been unzipped". "/untarred, nothing done\n"); return 1; } unless (exists $self->{build_dir}) { $CPAN::Frontend->mywarn("Distribution has no own directory, nothing to do.\n"); return 1; } if (exists $self->{writemakefile} and $self->{writemakefile}->failed ) { $CPAN::Frontend->mywarn("No Makefile, don't know how to 'make clean'\n"); return 1; } EXCUSE: { my @e; exists $self->{make_clean} and $self->{make_clean} eq "YES" and push @e, "make clean already called once"; $CPAN::Frontend->myprint(join "", map {" $_\n"} @e) and return if @e; } chdir $self->{build_dir} or Carp::confess("Couldn't chdir to $self->{build_dir}: $!"); $self->debug("Changed directory to $self->{build_dir}") if $CPAN::DEBUG; if ($^O eq 'MacOS') { Mac::BuildTools::make_clean($self); return; } my $system; if ($self->{modulebuild}) { unless (-f "Build") { my $cwd = CPAN::anycwd(); $CPAN::Frontend->mywarn("Alert: no Build file available for 'clean $self->{id}". " in cwd[$cwd]. Danger, Will Robinson!"); $CPAN::Frontend->mysleep(5); } $system = sprintf "%s clean", $self->_build_command(); } else { $system = join " ", $self->_make_command(), "clean"; } my $system_ok = system($system) == 0; $self->introduce_myself; if ( $system_ok ) { $CPAN::Frontend->myprint(" $system -- OK\n"); # $self->force; # Jost Krieger pointed out that this "force" was wrong because # it has the effect that the next "install" on this distribution # will untar everything again. Instead we should bring the # object's state back to where it is after untarring. for my $k (qw( force_update install writemakefile make make_test )) { delete $self->{$k}; } $self->{make_clean} = CPAN::Distrostatus->new("YES"); } else { # Hmmm, what to do if make clean failed? $self->{make_clean} = CPAN::Distrostatus->new("NO"); $CPAN::Frontend->mywarn(qq{ $system -- NOT OK\n}); # 2006-02-27: seems silly to me to force a make now # $self->force("make"); # so that this directory won't be used again } $self->store_persistent_state; } #-> sub CPAN::Distribution::goto ; sub goto { my($self,$goto) = @_; $goto = $self->normalize($goto); my $why = sprintf( "Goto '$goto' via prefs file '%s' doc %d", $self->{prefs_file}, $self->{prefs_file_doc}, ); $self->{unwrapped} = CPAN::Distrostatus->new("NO $why"); # 2007-07-16 akoenig : Better than NA would be if we could inherit # the status of the $goto distro but given the exceptional nature # of 'goto' I feel reluctant to implement it my $goodbye_message = "[goto] -- NA $why"; $self->goodbye($goodbye_message); # inject into the queue CPAN::Queue->delete($self->id); CPAN::Queue->jumpqueue({qmod => $goto, reqtype => $self->{reqtype}}); # and run where we left off my($method) = (caller(1))[3]; CPAN->instance("CPAN::Distribution",$goto)->$method(); CPAN::Queue->delete_first($goto); } #-> sub CPAN::Distribution::install ; sub install { my($self) = @_; if (my $goto = $self->prefs->{goto}) { return $self->goto($goto); } # $DB::single=1; unless ($self->{badtestcnt}) { $self->test; } if ($CPAN::Signal) { delete $self->{force_update}; return; } my $make = $self->{modulebuild} ? "Build" : "make"; $CPAN::Frontend->myprint("Running $make install\n"); EXCUSE: { my @e; if ($self->{make} or $self->{later}) { # go ahead } else { push @e, "Make had some problems, won't install"; } exists $self->{make} and ( UNIVERSAL::can($self->{make},"failed") ? $self->{make}->failed : $self->{make} =~ /^NO/ ) and push @e, "Make had returned bad status, install seems impossible"; if (exists $self->{build_dir}) { } elsif (!@e) { push @e, "Has no own directory"; } if (exists $self->{make_test} and ( UNIVERSAL::can($self->{make_test},"failed") ? $self->{make_test}->failed : $self->{make_test} =~ /^NO/ )) { if ($self->{force_update}) { $self->{make_test}->text("FAILED but failure ignored because ". "'force' in effect"); } else { push @e, "make test had returned bad status, ". "won't install without force" } } if (exists $self->{install}) { if (UNIVERSAL::can($self->{install},"text") ? $self->{install}->text eq "YES" : $self->{install} =~ /^YES/ ) { $CPAN::Frontend->myprint(" Already done\n"); $CPAN::META->is_installed($self->{build_dir}); return 1; } else { # comment in Todo on 2006-02-11; maybe retry? push @e, "Already tried without success"; } } push @e, $self->{later} if $self->{later}; push @e, $self->{configure_requires_later} if $self->{configure_requires_later}; $CPAN::Frontend->myprint(join "", map {" $_\n"} @e) and return if @e; unless (chdir $self->{build_dir}) { push @e, "Couldn't chdir to '$self->{build_dir}': $!"; } $CPAN::Frontend->mywarn(join "", map {" $_\n"} @e) and return if @e; } $self->debug("Changed directory to $self->{build_dir}") if $CPAN::DEBUG; if ($^O eq 'MacOS') { Mac::BuildTools::make_install($self); return; } my $system; if (my $commandline = $self->prefs->{install}{commandline}) { $system = $commandline; $ENV{PERL} = CPAN::find_perl; } elsif ($self->{modulebuild}) { my($mbuild_install_build_command) = exists $CPAN::HandleConfig::keys{mbuild_install_build_command} && $CPAN::Config->{mbuild_install_build_command} ? $CPAN::Config->{mbuild_install_build_command} : $self->_build_command(); $system = sprintf("%s install %s", $mbuild_install_build_command, $CPAN::Config->{mbuild_install_arg}, ); } else { my($make_install_make_command) = CPAN::HandleConfig->prefs_lookup($self, q{make_install_make_command}) || $self->_make_command(); $system = sprintf("%s install %s", $make_install_make_command, $CPAN::Config->{make_install_arg}, ); } my($stderr) = $^O eq "MSWin32" ? "" : " 2>&1 "; my $brip = CPAN::HandleConfig->prefs_lookup($self, q{build_requires_install_policy}); $brip ||="ask/yes"; my $id = $self->id; my $reqtype = $self->{reqtype} ||= "c"; # in doubt it was a command my $want_install = "yes"; if ($reqtype eq "b") { if ($brip eq "no") { $want_install = "no"; } elsif ($brip =~ m|^ask/(.+)|) { my $default = $1; $default = "yes" unless $default =~ /^(y|n)/i; $want_install = CPAN::Shell::colorable_makemaker_prompt ("$id is just needed temporarily during building or testing. ". "Do you want to install it permanently? (Y/n)", $default); } } unless ($want_install =~ /^y/i) { my $is_only = "is only 'build_requires'"; $CPAN::Frontend->mywarn("Not installing because $is_only\n"); $self->{install} = CPAN::Distrostatus->new("NO -- $is_only"); delete $self->{force_update}; return; } local $ENV{PERL5LIB} = defined($ENV{PERL5LIB}) ? $ENV{PERL5LIB} : ($ENV{PERLLIB} || ""); $CPAN::META->set_perl5lib; my($pipe) = FileHandle->new("$system $stderr |"); my($makeout) = ""; while (<$pipe>) { print $_; # intentionally NOT use Frontend->myprint because it # looks irritating when we markup in color what we # just pass through from an external program $makeout .= $_; } $pipe->close; my $close_ok = $? == 0; $self->introduce_myself; if ( $close_ok ) { $CPAN::Frontend->myprint(" $system -- OK\n"); $CPAN::META->is_installed($self->{build_dir}); $self->{install} = CPAN::Distrostatus->new("YES"); } else { $self->{install} = CPAN::Distrostatus->new("NO"); $CPAN::Frontend->mywarn(" $system -- NOT OK\n"); my $mimc = CPAN::HandleConfig->prefs_lookup($self, q{make_install_make_command}); if ( $makeout =~ /permission/s && $> > 0 && ( ! $mimc || $mimc eq (CPAN::HandleConfig->prefs_lookup($self, q{make})) ) ) { $CPAN::Frontend->myprint( qq{----\n}. qq{ You may have to su }. qq{to root to install the package\n}. qq{ (Or you may want to run something like\n}. qq{ o conf make_install_make_command 'sudo make'\n}. qq{ to raise your permissions.} ); } } delete $self->{force_update}; # $DB::single = 1; $self->store_persistent_state; } sub introduce_myself { my($self) = @_; $CPAN::Frontend->myprint(sprintf(" %s\n",$self->pretty_id)); } #-> sub CPAN::Distribution::dir ; sub dir { shift->{build_dir}; } #-> sub CPAN::Distribution::perldoc ; sub perldoc { my($self) = @_; my($dist) = $self->id; my $package = $self->called_for; $self->_display_url( $CPAN::Defaultdocs . $package ); } #-> sub CPAN::Distribution::_check_binary ; sub _check_binary { my ($dist,$shell,$binary) = @_; my ($pid,$out); $CPAN::Frontend->myprint(qq{ + _check_binary($binary)\n}) if $CPAN::DEBUG; if ($CPAN::META->has_inst("File::Which")) { return File::Which::which($binary); } else { local *README; $pid = open README, "which $binary|" or $CPAN::Frontend->mywarn(qq{Could not fork 'which $binary': $!\n}); return unless $pid; while (<README>) { $out .= $_; } close README or $CPAN::Frontend->mywarn("Could not run 'which $binary': $!\n") and return; } $CPAN::Frontend->myprint(qq{ + $out \n}) if $CPAN::DEBUG && $out; return $out; } #-> sub CPAN::Distribution::_display_url ; sub _display_url { my($self,$url) = @_; my($res,$saved_file,$pid,$out); $CPAN::Frontend->myprint(qq{ + _display_url($url)\n}) if $CPAN::DEBUG; # should we define it in the config instead? my $html_converter = "html2text.pl"; my $web_browser = $CPAN::Config->{'lynx'} || undef; my $web_browser_out = $web_browser ? CPAN::Distribution->_check_binary($self,$web_browser) : undef; if ($web_browser_out) { # web browser found, run the action my $browser = CPAN::HandleConfig->safe_quote($CPAN::Config->{'lynx'}); $CPAN::Frontend->myprint(qq{system[$browser $url]}) if $CPAN::DEBUG; $CPAN::Frontend->myprint(qq{ Displaying URL $url with browser $browser }); $CPAN::Frontend->mysleep(1); system("$browser $url"); if ($saved_file) { 1 while unlink($saved_file) } } else { # web browser not found, let's try text only my $html_converter_out = CPAN::Distribution->_check_binary($self,$html_converter); $html_converter_out = CPAN::HandleConfig->safe_quote($html_converter_out); if ($html_converter_out ) { # html2text found, run it $saved_file = CPAN::Distribution->_getsave_url( $self, $url ); $CPAN::Frontend->mydie(qq{ERROR: problems while getting $url\n}) unless defined($saved_file); local *README; $pid = open README, "$html_converter $saved_file |" or $CPAN::Frontend->mydie(qq{ Could not fork '$html_converter $saved_file': $!}); my($fh,$filename); if ($CPAN::META->has_usable("File::Temp")) { $fh = File::Temp->new( dir => File::Spec->tmpdir, template => 'cpan_htmlconvert_XXXX', suffix => '.txt', unlink => 0, ); $filename = $fh->filename; } else { $filename = "cpan_htmlconvert_$$.txt"; $fh = FileHandle->new(); open $fh, ">$filename" or die; } while (<README>) { $fh->print($_); } close README or $CPAN::Frontend->mydie(qq{Could not run '$html_converter $saved_file': $!}); my $tmpin = $fh->filename; $CPAN::Frontend->myprint(sprintf(qq{ Run '%s %s' and saved output to %s\n}, $html_converter, $saved_file, $tmpin, )) if $CPAN::DEBUG; close $fh; local *FH; open FH, $tmpin or $CPAN::Frontend->mydie(qq{Could not open "$tmpin": $!}); my $fh_pager = FileHandle->new; local($SIG{PIPE}) = "IGNORE"; my $pager = $CPAN::Config->{'pager'} || "cat"; $fh_pager->open("|$pager") or $CPAN::Frontend->mydie(qq{ Could not open pager '$pager': $!}); $CPAN::Frontend->myprint(qq{ Displaying URL $url with pager "$pager" }); $CPAN::Frontend->mysleep(1); $fh_pager->print(<FH>); $fh_pager->close; } else { # coldn't find the web browser or html converter $CPAN::Frontend->myprint(qq{ You need to install lynx or $html_converter to use this feature.}); } } } #-> sub CPAN::Distribution::_getsave_url ; sub _getsave_url { my($dist, $shell, $url) = @_; $CPAN::Frontend->myprint(qq{ + _getsave_url($url)\n}) if $CPAN::DEBUG; my($fh,$filename); if ($CPAN::META->has_usable("File::Temp")) { $fh = File::Temp->new( dir => File::Spec->tmpdir, template => "cpan_getsave_url_XXXX", suffix => ".html", unlink => 0, ); $filename = $fh->filename; } else { $fh = FileHandle->new; $filename = "cpan_getsave_url_$$.html"; } my $tmpin = $filename; if ($CPAN::META->has_usable('LWP')) { $CPAN::Frontend->myprint("Fetching with LWP: $url "); my $Ua; CPAN::LWP::UserAgent->config; eval { $Ua = CPAN::LWP::UserAgent->new; }; if ($@) { $CPAN::Frontend->mywarn("ERROR: CPAN::LWP::UserAgent->new dies with $@\n"); return; } else { my($var); $Ua->proxy('http', $var) if $var = $CPAN::Config->{http_proxy} || $ENV{http_proxy}; $Ua->no_proxy($var) if $var = $CPAN::Config->{no_proxy} || $ENV{no_proxy}; } my $req = HTTP::Request->new(GET => $url); $req->header('Accept' => 'text/html'); my $res = $Ua->request($req); if ($res->is_success) { $CPAN::Frontend->myprint(" + request successful.\n") if $CPAN::DEBUG; print $fh $res->content; close $fh; $CPAN::Frontend->myprint(qq{ + saved content to $tmpin \n}) if $CPAN::DEBUG; return $tmpin; } else { $CPAN::Frontend->myprint(sprintf( "LWP failed with code[%s], message[%s]\n", $res->code, $res->message, )); return; } } else { $CPAN::Frontend->mywarn(" LWP not available\n"); return; } } #-> sub CPAN::Distribution::_build_command sub _build_command { my($self) = @_; if ($^O eq "MSWin32") { # special code needed at least up to # Module::Build 0.2611 and 0.2706; a fix # in M:B has been promised 2006-01-30 my($perl) = $self->perl or $CPAN::Frontend->mydie("Couldn't find executable perl\n"); return "$perl ./Build"; } return "./Build"; } #-> sub CPAN::Distribution::_should_report sub _should_report { my($self, $phase) = @_; die "_should_report() requires a 'phase' argument" if ! defined $phase; # configured my $test_report = CPAN::HandleConfig->prefs_lookup($self, q{test_report}); return unless $test_report; # don't repeat if we cached a result return $self->{should_report} if exists $self->{should_report}; # available if ( ! $CPAN::META->has_inst("CPAN::Reporter")) { $CPAN::Frontend->mywarn( "CPAN::Reporter not installed. No reports will be sent.\n" ); return $self->{should_report} = 0; } # capable my $crv = CPAN::Reporter->VERSION; if ( CPAN::Version->vlt( $crv, 0.99 ) ) { # don't cache $self->{should_report} -- need to check each phase if ( $phase eq 'test' ) { return 1; } else { $CPAN::Frontend->mywarn( "Reporting on the '$phase' phase requires CPAN::Reporter 0.99, but \n" . "you only have version $crv\. Only 'test' phase reports will be sent.\n" ); return; } } # appropriate if ($self->is_dot_dist) { $CPAN::Frontend->mywarn("Reporting via CPAN::Reporter is disabled ". "for local directories\n"); return $self->{should_report} = 0; } if ($self->prefs->{patches} && @{$self->prefs->{patches}} && $self->{patched} ) { $CPAN::Frontend->mywarn("Reporting via CPAN::Reporter is disabled ". "when the source has been patched\n"); return $self->{should_report} = 0; } # proceed and cache success return $self->{should_report} = 1; } #-> sub CPAN::Distribution::reports sub reports { my($self) = @_; my $pathname = $self->id; $CPAN::Frontend->myprint("Distribution: $pathname\n"); unless ($CPAN::META->has_inst("CPAN::DistnameInfo")) { $CPAN::Frontend->mydie("CPAN::DistnameInfo not installed; cannot continue"); } unless ($CPAN::META->has_usable("LWP")) { $CPAN::Frontend->mydie("LWP not installed; cannot continue"); } unless ($CPAN::META->has_usable("File::Temp")) { $CPAN::Frontend->mydie("File::Temp not installed; cannot continue"); } my $d = CPAN::DistnameInfo->new($pathname); my $dist = $d->dist; # "CPAN-DistnameInfo" my $version = $d->version; # "0.02" my $maturity = $d->maturity; # "released" my $filename = $d->filename; # "CPAN-DistnameInfo-0.02.tar.gz" my $cpanid = $d->cpanid; # "GBARR" my $distvname = $d->distvname; # "CPAN-DistnameInfo-0.02" my $url = sprintf "http://cpantesters.perl.org/show/%s.yaml", $dist; CPAN::LWP::UserAgent->config; my $Ua; eval { $Ua = CPAN::LWP::UserAgent->new; }; if ($@) { $CPAN::Frontend->mydie("CPAN::LWP::UserAgent->new dies with $@\n"); } $CPAN::Frontend->myprint("Fetching '$url'..."); my $resp = $Ua->get($url); unless ($resp->is_success) { $CPAN::Frontend->mydie(sprintf "Could not download '%s': %s\n", $url, $resp->code); } $CPAN::Frontend->myprint("DONE\n\n"); my $yaml = $resp->content; # was fuer ein Umweg! my $fh = File::Temp->new( dir => File::Spec->tmpdir, template => 'cpan_reports_XXXX', suffix => '.yaml', unlink => 0, ); my $tfilename = $fh->filename; print $fh $yaml; close $fh or $CPAN::Frontend->mydie("Could not close '$tfilename': $!"); my $unserialized = CPAN->_yaml_loadfile($tfilename)->[0]; unlink $tfilename or $CPAN::Frontend->mydie("Could not unlink '$tfilename': $!"); my %other_versions; my $this_version_seen; for my $rep (@$unserialized) { my $rversion = $rep->{version}; if ($rversion eq $version) { unless ($this_version_seen++) { $CPAN::Frontend->myprint ("$rep->{version}:\n"); } $CPAN::Frontend->myprint (sprintf("%1s%1s%-4s %s on %s %s (%s)\n", $rep->{archname} eq $Config::Config{archname}?"*":"", $rep->{action}eq"PASS"?"+":$rep->{action}eq"FAIL"?"-":"", $rep->{action}, $rep->{perl}, ucfirst $rep->{osname}, $rep->{osvers}, $rep->{archname}, )); } else { $other_versions{$rep->{version}}++; } } unless ($this_version_seen) { $CPAN::Frontend->myprint("No reports found for version '$version' Reports for other versions:\n"); for my $v (sort keys %other_versions) { $CPAN::Frontend->myprint(" $v\: $other_versions{$v}\n"); } } $url =~ s/\.yaml/.html/; $CPAN::Frontend->myprint("See $url for details\n"); } package CPAN::Bundle; use strict; sub look { my $self = shift; $CPAN::Frontend->myprint($self->as_string); } #-> CPAN::Bundle::undelay sub undelay { my $self = shift; delete $self->{later}; for my $c ( $self->contains ) { my $obj = CPAN::Shell->expandany($c) or next; $obj->undelay; } } # mark as dirty/clean #-> sub CPAN::Bundle::color_cmd_tmps ; sub color_cmd_tmps { my($self) = shift; my($depth) = shift || 0; my($color) = shift || 0; my($ancestors) = shift || []; # a module needs to recurse to its cpan_file, a distribution needs # to recurse into its prereq_pms, a bundle needs to recurse into its modules return if exists $self->{incommandcolor} && $color==1 && $self->{incommandcolor}==$color; if ($depth>=$CPAN::MAX_RECURSION) { die(CPAN::Exception::RecursiveDependency->new($ancestors)); } # warn "color_cmd_tmps $depth $color " . $self->id; # sleep 1; for my $c ( $self->contains ) { my $obj = CPAN::Shell->expandany($c) or next; CPAN->debug("c[$c]obj[$obj]") if $CPAN::DEBUG; $obj->color_cmd_tmps($depth+1,$color,[@$ancestors, $self->id]); } # never reached code? #if ($color==0) { #delete $self->{badtestcnt}; #} $self->{incommandcolor} = $color; } #-> sub CPAN::Bundle::as_string ; sub as_string { my($self) = @_; $self->contains; # following line must be "=", not "||=" because we have a moving target $self->{INST_VERSION} = $self->inst_version; return $self->SUPER::as_string; } #-> sub CPAN::Bundle::contains ; sub contains { my($self) = @_; my($inst_file) = $self->inst_file || ""; my($id) = $self->id; $self->debug("inst_file[$inst_file]id[$id]") if $CPAN::DEBUG; if ($inst_file && CPAN::Version->vlt($self->inst_version,$self->cpan_version)) { undef $inst_file; } unless ($inst_file) { # Try to get at it in the cpan directory $self->debug("no inst_file") if $CPAN::DEBUG; my $cpan_file; $CPAN::Frontend->mydie("I don't know a bundle with ID $id\n") unless $cpan_file = $self->cpan_file; if ($cpan_file eq "N/A") { $CPAN::Frontend->mydie("Bundle $id not found on disk and not on CPAN. Maybe stale symlink? Maybe removed during session? Giving up.\n"); } my $dist = $CPAN::META->instance('CPAN::Distribution', $self->cpan_file); $self->debug("before get id[$dist->{ID}]") if $CPAN::DEBUG; $dist->get; $self->debug("after get id[$dist->{ID}]") if $CPAN::DEBUG; my($todir) = $CPAN::Config->{'cpan_home'}; my(@me,$from,$to,$me); @me = split /::/, $self->id; $me[-1] .= ".pm"; $me = File::Spec->catfile(@me); $from = $self->find_bundle_file($dist->{build_dir},join('/',@me)); $to = File::Spec->catfile($todir,$me); File::Path::mkpath(File::Basename::dirname($to)); File::Copy::copy($from, $to) or Carp::confess("Couldn't copy $from to $to: $!"); $inst_file = $to; } my @result; my $fh = FileHandle->new; local $/ = "\n"; open($fh,$inst_file) or die "Could not open '$inst_file': $!"; my $in_cont = 0; $self->debug("inst_file[$inst_file]") if $CPAN::DEBUG; while (<$fh>) { $in_cont = m/^=(?!head1\s+CONTENTS)/ ? 0 : m/^=head1\s+CONTENTS/ ? 1 : $in_cont; next unless $in_cont; next if /^=/; s/\#.*//; next if /^\s+$/; chomp; push @result, (split " ", $_, 2)[0]; } close $fh; delete $self->{STATUS}; $self->{CONTAINS} = \@result; $self->debug("CONTAINS[@result]") if $CPAN::DEBUG; unless (@result) { $CPAN::Frontend->mywarn(qq{ The bundle file "$inst_file" may be a broken bundlefile. It seems not to contain any bundle definition. Please check the file and if it is bogus, please delete it. Sorry for the inconvenience. }); } @result; } #-> sub CPAN::Bundle::find_bundle_file # $where is in local format, $what is in unix format sub find_bundle_file { my($self,$where,$what) = @_; $self->debug("where[$where]what[$what]") if $CPAN::DEBUG; ### The following two lines let CPAN.pm become Bundle/CPAN.pm :-( ### my $bu = File::Spec->catfile($where,$what); ### return $bu if -f $bu; my $manifest = File::Spec->catfile($where,"MANIFEST"); unless (-f $manifest) { require ExtUtils::Manifest; my $cwd = CPAN::anycwd(); $self->safe_chdir($where); ExtUtils::Manifest::mkmanifest(); $self->safe_chdir($cwd); } my $fh = FileHandle->new($manifest) or Carp::croak("Couldn't open $manifest: $!"); local($/) = "\n"; my $bundle_filename = $what; $bundle_filename =~ s|Bundle.*/||; my $bundle_unixpath; while (<$fh>) { next if /^\s*\#/; my($file) = /(\S+)/; if ($file =~ m|\Q$what\E$|) { $bundle_unixpath = $file; # return File::Spec->catfile($where,$bundle_unixpath); # bad last; } # retry if she managed to have no Bundle directory $bundle_unixpath = $file if $file =~ m|\Q$bundle_filename\E$|; } return File::Spec->catfile($where, split /\//, $bundle_unixpath) if $bundle_unixpath; Carp::croak("Couldn't find a Bundle file in $where"); } # needs to work quite differently from Module::inst_file because of # cpan_home/Bundle/ directory and the possibility that we have # shadowing effect. As it makes no sense to take the first in @INC for # Bundles, we parse them all for $VERSION and take the newest. #-> sub CPAN::Bundle::inst_file ; sub inst_file { my($self) = @_; my($inst_file); my(@me); @me = split /::/, $self->id; $me[-1] .= ".pm"; my($incdir,$bestv); foreach $incdir ($CPAN::Config->{'cpan_home'},@INC) { my $bfile = File::Spec->catfile($incdir, @me); CPAN->debug("bfile[$bfile]") if $CPAN::DEBUG; next unless -f $bfile; my $foundv = MM->parse_version($bfile); if (!$bestv || CPAN::Version->vgt($foundv,$bestv)) { $self->{INST_FILE} = $bfile; $self->{INST_VERSION} = $bestv = $foundv; } } $self->{INST_FILE}; } #-> sub CPAN::Bundle::inst_version ; sub inst_version { my($self) = @_; $self->inst_file; # finds INST_VERSION as side effect $self->{INST_VERSION}; } #-> sub CPAN::Bundle::rematein ; sub rematein { my($self,$meth) = @_; $self->debug("self[$self] meth[$meth]") if $CPAN::DEBUG; my($id) = $self->id; Carp::croak "Can't $meth $id, don't have an associated bundle file. :-(\n" unless $self->inst_file || $self->cpan_file; my($s,%fail); for $s ($self->contains) { my($type) = $s =~ m|/| ? 'CPAN::Distribution' : $s =~ m|^Bundle::| ? 'CPAN::Bundle' : 'CPAN::Module'; if ($type eq 'CPAN::Distribution') { $CPAN::Frontend->mywarn(qq{ The Bundle }.$self->id.qq{ contains explicitly a file '$s'. Going to $meth that. }); $CPAN::Frontend->mysleep(5); } # possibly noisy action: $self->debug("type[$type] s[$s]") if $CPAN::DEBUG; my $obj = $CPAN::META->instance($type,$s); $obj->{reqtype} = $self->{reqtype}; $obj->$meth(); } } # If a bundle contains another that contains an xs_file we have here, # we just don't bother I suppose #-> sub CPAN::Bundle::xs_file sub xs_file { return 0; } #-> sub CPAN::Bundle::force ; sub fforce { shift->rematein('fforce',@_); } #-> sub CPAN::Bundle::force ; sub force { shift->rematein('force',@_); } #-> sub CPAN::Bundle::notest ; sub notest { shift->rematein('notest',@_); } #-> sub CPAN::Bundle::get ; sub get { shift->rematein('get',@_); } #-> sub CPAN::Bundle::make ; sub make { shift->rematein('make',@_); } #-> sub CPAN::Bundle::test ; sub test { my $self = shift; # $self->{badtestcnt} ||= 0; $self->rematein('test',@_); } #-> sub CPAN::Bundle::install ; sub install { my $self = shift; $self->rematein('install',@_); } #-> sub CPAN::Bundle::clean ; sub clean { shift->rematein('clean',@_); } #-> sub CPAN::Bundle::uptodate ; sub uptodate { my($self) = @_; return 0 unless $self->SUPER::uptodate; # we mut have the current Bundle def my $c; foreach $c ($self->contains) { my $obj = CPAN::Shell->expandany($c); return 0 unless $obj->uptodate; } return 1; } #-> sub CPAN::Bundle::readme ; sub readme { my($self) = @_; my($file) = $self->cpan_file or $CPAN::Frontend->myprint(qq{ No File found for bundle } . $self->id . qq{\n}), return; $self->debug("self[$self] file[$file]") if $CPAN::DEBUG; $CPAN::META->instance('CPAN::Distribution',$file)->readme; } package CPAN::Module; use strict; # Accessors #-> sub CPAN::Module::userid sub userid { my $self = shift; my $ro = $self->ro; return unless $ro; return $ro->{userid} || $ro->{CPAN_USERID}; } #-> sub CPAN::Module::description sub description { my $self = shift; my $ro = $self->ro or return ""; $ro->{description} } #-> sub CPAN::Module::distribution sub distribution { my($self) = @_; CPAN::Shell->expand("Distribution",$self->cpan_file); } #-> sub CPAN::Module::undelay sub undelay { my $self = shift; delete $self->{later}; if ( my $dist = CPAN::Shell->expand("Distribution", $self->cpan_file) ) { $dist->undelay; } } # mark as dirty/clean #-> sub CPAN::Module::color_cmd_tmps ; sub color_cmd_tmps { my($self) = shift; my($depth) = shift || 0; my($color) = shift || 0; my($ancestors) = shift || []; # a module needs to recurse to its cpan_file return if exists $self->{incommandcolor} && $color==1 && $self->{incommandcolor}==$color; return if $color==0 && !$self->{incommandcolor}; if ($color>=1) { if ( $self->uptodate ) { $self->{incommandcolor} = $color; return; } elsif (my $have_version = $self->available_version) { # maybe what we have is good enough if (@$ancestors) { my $who_asked_for_me = $ancestors->[-1]; my $obj = CPAN::Shell->expandany($who_asked_for_me); if (0) { } elsif ($obj->isa("CPAN::Bundle")) { # bundles cannot specify a minimum version return; } elsif ($obj->isa("CPAN::Distribution")) { if (my $prereq_pm = $obj->prereq_pm) { for my $k (keys %$prereq_pm) { if (my $want_version = $prereq_pm->{$k}{$self->id}) { if (CPAN::Version->vcmp($have_version,$want_version) >= 0) { $self->{incommandcolor} = $color; return; } } } } } } } } else { $self->{incommandcolor} = $color; # set me before recursion, # so we can break it } if ($depth>=$CPAN::MAX_RECURSION) { die(CPAN::Exception::RecursiveDependency->new($ancestors)); } # warn "color_cmd_tmps $depth $color " . $self->id; # sleep 1; if ( my $dist = CPAN::Shell->expand("Distribution", $self->cpan_file) ) { $dist->color_cmd_tmps($depth+1,$color,[@$ancestors, $self->id]); } # unreached code? # if ($color==0) { # delete $self->{badtestcnt}; # } $self->{incommandcolor} = $color; } #-> sub CPAN::Module::as_glimpse ; sub as_glimpse { my($self) = @_; my(@m); my $class = ref($self); $class =~ s/^CPAN:://; my $color_on = ""; my $color_off = ""; if ( $CPAN::Shell::COLOR_REGISTERED && $CPAN::META->has_inst("Term::ANSIColor") && $self->description ) { $color_on = Term::ANSIColor::color("green"); $color_off = Term::ANSIColor::color("reset"); } my $uptodateness = " "; unless ($class eq "Bundle") { my $u = $self->uptodate; $uptodateness = $u ? "=" : "<" if defined $u; }; my $id = do { my $d = $self->distribution; $d ? $d -> pretty_id : $self->cpan_userid; }; push @m, sprintf("%-7s %1s %s%-22s%s (%s)\n", $class, $uptodateness, $color_on, $self->id, $color_off, $id, ); join "", @m; } #-> sub CPAN::Module::dslip_status sub dslip_status { my($self) = @_; my($stat); # development status @{$stat->{D}}{qw,i c a b R M S,} = qw,idea pre-alpha alpha beta released mature standard,; # support level @{$stat->{S}}{qw,m d u n a,} = qw,mailing-list developer comp.lang.perl.* none abandoned,; # language @{$stat->{L}}{qw,p c + o h,} = qw,perl C C++ other hybrid,; # interface @{$stat->{I}}{qw,f r O p h n,} = qw,functions references+ties object-oriented pragma hybrid none,; # public licence @{$stat->{P}}{qw,p g l b a 2 o d r n,} = qw,Standard-Perl GPL LGPL BSD Artistic Artistic_2 open-source distribution_allowed restricted_distribution no_licence,; for my $x (qw(d s l i p)) { $stat->{$x}{' '} = 'unknown'; $stat->{$x}{'?'} = 'unknown'; } my $ro = $self->ro; return +{} unless $ro && $ro->{statd}; return { D => $ro->{statd}, S => $ro->{stats}, L => $ro->{statl}, I => $ro->{stati}, P => $ro->{statp}, DV => $stat->{D}{$ro->{statd}}, SV => $stat->{S}{$ro->{stats}}, LV => $stat->{L}{$ro->{statl}}, IV => $stat->{I}{$ro->{stati}}, PV => $stat->{P}{$ro->{statp}}, }; } #-> sub CPAN::Module::as_string ; sub as_string { my($self) = @_; my(@m); CPAN->debug("$self entering as_string") if $CPAN::DEBUG; my $class = ref($self); $class =~ s/^CPAN:://; local($^W) = 0; push @m, $class, " id = $self->{ID}\n"; my $sprintf = " %-12s %s\n"; push @m, sprintf($sprintf, 'DESCRIPTION', $self->description) if $self->description; my $sprintf2 = " %-12s %s (%s)\n"; my($userid); $userid = $self->userid; if ( $userid ) { my $author; if ($author = CPAN::Shell->expand('Author',$userid)) { my $email = ""; my $m; # old perls if ($m = $author->email) { $email = " <$m>"; } push @m, sprintf( $sprintf2, 'CPAN_USERID', $userid, $author->fullname . $email ); } } push @m, sprintf($sprintf, 'CPAN_VERSION', $self->cpan_version) if $self->cpan_version; if (my $cpan_file = $self->cpan_file) { push @m, sprintf($sprintf, 'CPAN_FILE', $cpan_file); if (my $dist = CPAN::Shell->expand("Distribution",$cpan_file)) { my $upload_date = $dist->upload_date; if ($upload_date) { push @m, sprintf($sprintf, 'UPLOAD_DATE', $upload_date); } } } my $sprintf3 = " %-12s %1s%1s%1s%1s%1s (%s,%s,%s,%s,%s)\n"; my $dslip = $self->dslip_status; push @m, sprintf( $sprintf3, 'DSLIP_STATUS', @{$dslip}{qw(D S L I P DV SV LV IV PV)}, ) if $dslip->{D}; my $local_file = $self->inst_file; unless ($self->{MANPAGE}) { my $manpage; if ($local_file) { $manpage = $self->manpage_headline($local_file); } else { # If we have already untarred it, we should look there my $dist = $CPAN::META->instance('CPAN::Distribution', $self->cpan_file); # warn "dist[$dist]"; # mff=manifest file; mfh=manifest handle my($mff,$mfh); if ( $dist->{build_dir} and (-f ($mff = File::Spec->catfile($dist->{build_dir}, "MANIFEST"))) and $mfh = FileHandle->new($mff) ) { CPAN->debug("mff[$mff]") if $CPAN::DEBUG; my $lfre = $self->id; # local file RE $lfre =~ s/::/./g; $lfre .= "\\.pm\$"; my($lfl); # local file file local $/ = "\n"; my(@mflines) = <$mfh>; for (@mflines) { s/^\s+//; s/\s.*//s; } while (length($lfre)>5 and !$lfl) { ($lfl) = grep /$lfre/, @mflines; CPAN->debug("lfl[$lfl]lfre[$lfre]") if $CPAN::DEBUG; $lfre =~ s/.+?\.//; } $lfl =~ s/\s.*//; # remove comments $lfl =~ s/\s+//g; # chomp would maybe be too system-specific my $lfl_abs = File::Spec->catfile($dist->{build_dir},$lfl); # warn "lfl_abs[$lfl_abs]"; if (-f $lfl_abs) { $manpage = $self->manpage_headline($lfl_abs); } } } $self->{MANPAGE} = $manpage if $manpage; } my($item); for $item (qw/MANPAGE/) { push @m, sprintf($sprintf, $item, $self->{$item}) if exists $self->{$item}; } for $item (qw/CONTAINS/) { push @m, sprintf($sprintf, $item, join(" ",@{$self->{$item}})) if exists $self->{$item} && @{$self->{$item}}; } push @m, sprintf($sprintf, 'INST_FILE', $local_file || "(not installed)"); push @m, sprintf($sprintf, 'INST_VERSION', $self->inst_version) if $local_file; join "", @m, "\n"; } #-> sub CPAN::Module::manpage_headline sub manpage_headline { my($self,$local_file) = @_; my(@local_file) = $local_file; $local_file =~ s/\.pm(?!\n)\Z/.pod/; push @local_file, $local_file; my(@result,$locf); for $locf (@local_file) { next unless -f $locf; my $fh = FileHandle->new($locf) or $Carp::Frontend->mydie("Couldn't open $locf: $!"); my $inpod = 0; local $/ = "\n"; while (<$fh>) { $inpod = m/^=(?!head1\s+NAME\s*$)/ ? 0 : m/^=head1\s+NAME\s*$/ ? 1 : $inpod; next unless $inpod; next if /^=/; next if /^\s+$/; chomp; push @result, $_; } close $fh; last if @result; } for (@result) { s/^\s+//; s/\s+$//; } join " ", @result; } #-> sub CPAN::Module::cpan_file ; # Note: also inherited by CPAN::Bundle sub cpan_file { my $self = shift; # CPAN->debug(sprintf "id[%s]", $self->id) if $CPAN::DEBUG; unless ($self->ro) { CPAN::Index->reload; } my $ro = $self->ro; if ($ro && defined $ro->{CPAN_FILE}) { return $ro->{CPAN_FILE}; } else { my $userid = $self->userid; if ( $userid ) { if ($CPAN::META->exists("CPAN::Author",$userid)) { my $author = $CPAN::META->instance("CPAN::Author", $userid); my $fullname = $author->fullname; my $email = $author->email; unless (defined $fullname && defined $email) { return sprintf("Contact Author %s", $userid, ); } return "Contact Author $fullname <$email>"; } else { return "Contact Author $userid (Email address not available)"; } } else { return "N/A"; } } } #-> sub CPAN::Module::cpan_version ; sub cpan_version { my $self = shift; my $ro = $self->ro; unless ($ro) { # Can happen with modules that are not on CPAN $ro = {}; } $ro->{CPAN_VERSION} = 'undef' unless defined $ro->{CPAN_VERSION}; $ro->{CPAN_VERSION}; } #-> sub CPAN::Module::force ; sub force { my($self) = @_; $self->{force_update} = 1; } #-> sub CPAN::Module::fforce ; sub fforce { my($self) = @_; $self->{force_update} = 2; } #-> sub CPAN::Module::notest ; sub notest { my($self) = @_; # $CPAN::Frontend->mywarn("XDEBUG: set notest for Module"); $self->{notest}++; } #-> sub CPAN::Module::rematein ; sub rematein { my($self,$meth) = @_; $CPAN::Frontend->myprint(sprintf("Running %s for module '%s'\n", $meth, $self->id)); my $cpan_file = $self->cpan_file; if ($cpan_file eq "N/A" || $cpan_file =~ /^Contact Author/) { $CPAN::Frontend->mywarn(sprintf qq{ The module %s isn\'t available on CPAN. Either the module has not yet been uploaded to CPAN, or it is temporary unavailable. Please contact the author to find out more about the status. Try 'i %s'. }, $self->id, $self->id, ); return; } my $pack = $CPAN::META->instance('CPAN::Distribution',$cpan_file); $pack->called_for($self->id); if (exists $self->{force_update}) { if ($self->{force_update} == 2) { $pack->fforce($meth); } else { $pack->force($meth); } } $pack->notest($meth) if exists $self->{notest} && $self->{notest}; $pack->{reqtype} ||= ""; CPAN->debug("dist-reqtype[$pack->{reqtype}]". "self-reqtype[$self->{reqtype}]") if $CPAN::DEBUG; if ($pack->{reqtype}) { if ($pack->{reqtype} eq "b" && $self->{reqtype} =~ /^[rc]$/) { $pack->{reqtype} = $self->{reqtype}; if ( exists $pack->{install} && ( UNIVERSAL::can($pack->{install},"failed") ? $pack->{install}->failed : $pack->{install} =~ /^NO/ ) ) { delete $pack->{install}; $CPAN::Frontend->mywarn ("Promoting $pack->{ID} from 'build_requires' to 'requires'"); } } } else { $pack->{reqtype} = $self->{reqtype}; } my $success = eval { $pack->$meth(); }; my $err = $@; $pack->unforce if $pack->can("unforce") && exists $self->{force_update}; $pack->unnotest if $pack->can("unnotest") && exists $self->{notest}; delete $self->{force_update}; delete $self->{notest}; if ($err) { die $err; } return $success; } #-> sub CPAN::Module::perldoc ; sub perldoc { shift->rematein('perldoc') } #-> sub CPAN::Module::readme ; sub readme { shift->rematein('readme') } #-> sub CPAN::Module::look ; sub look { shift->rematein('look') } #-> sub CPAN::Module::cvs_import ; sub cvs_import { shift->rematein('cvs_import') } #-> sub CPAN::Module::get ; sub get { shift->rematein('get',@_) } #-> sub CPAN::Module::make ; sub make { shift->rematein('make') } #-> sub CPAN::Module::test ; sub test { my $self = shift; # $self->{badtestcnt} ||= 0; $self->rematein('test',@_); } #-> sub CPAN::Module::uptodate ; sub uptodate { my ($self) = @_; local ($_); my $inst = $self->inst_version or return undef; my $cpan = $self->cpan_version; local ($^W) = 0; CPAN::Version->vgt($cpan,$inst) and return 0; CPAN->debug(join("", "returning uptodate. inst_file[", $self->inst_file, "cpan[$cpan] inst[$inst]")) if $CPAN::DEBUG; return 1; } #-> sub CPAN::Module::install ; sub install { my($self) = @_; my($doit) = 0; if ($self->uptodate && not exists $self->{force_update} ) { $CPAN::Frontend->myprint(sprintf("%s is up to date (%s).\n", $self->id, $self->inst_version, )); } else { $doit = 1; } my $ro = $self->ro; if ($ro && $ro->{stats} && $ro->{stats} eq "a") { $CPAN::Frontend->mywarn(qq{ \n\n\n ***WARNING*** The module $self->{ID} has no active maintainer.\n\n\n }); $CPAN::Frontend->mysleep(5); } $self->rematein('install') if $doit; } #-> sub CPAN::Module::clean ; sub clean { shift->rematein('clean') } #-> sub CPAN::Module::inst_file ; sub inst_file { my($self) = @_; $self->_file_in_path([@INC]); } #-> sub CPAN::Module::available_file ; sub available_file { my($self) = @_; my $sep = $Config::Config{path_sep}; my $perllib = $ENV{PERL5LIB}; $perllib = $ENV{PERLLIB} unless defined $perllib; my @perllib = split(/$sep/,$perllib) if defined $perllib; $self->_file_in_path([@perllib,@INC]); } #-> sub CPAN::Module::file_in_path ; sub _file_in_path { my($self,$path) = @_; my($dir,@packpath); @packpath = split /::/, $self->{ID}; $packpath[-1] .= ".pm"; if (@packpath == 1 && $packpath[0] eq "readline.pm") { unshift @packpath, "Term", "ReadLine"; # historical reasons } foreach $dir (@$path) { my $pmfile = File::Spec->catfile($dir,@packpath); if (-f $pmfile) { return $pmfile; } } return; } #-> sub CPAN::Module::xs_file ; sub xs_file { my($self) = @_; my($dir,@packpath); @packpath = split /::/, $self->{ID}; push @packpath, $packpath[-1]; $packpath[-1] .= "." . $Config::Config{'dlext'}; foreach $dir (@INC) { my $xsfile = File::Spec->catfile($dir,'auto',@packpath); if (-f $xsfile) { return $xsfile; } } return; } #-> sub CPAN::Module::inst_version ; sub inst_version { my($self) = @_; my $parsefile = $self->inst_file or return; my $have = $self->parse_version($parsefile); $have; } #-> sub CPAN::Module::inst_version ; sub available_version { my($self) = @_; my $parsefile = $self->available_file or return; my $have = $self->parse_version($parsefile); $have; } #-> sub CPAN::Module::parse_version ; sub parse_version { my($self,$parsefile) = @_; my $have = MM->parse_version($parsefile); $have = "undef" unless defined $have && length $have; $have =~ s/^ //; # since the %vd hack these two lines here are needed $have =~ s/ $//; # trailing whitespace happens all the time $have = CPAN::Version->readable($have); $have =~ s/\s*//g; # stringify to float around floating point issues $have; # no stringify needed, \s* above matches always } #-> sub CPAN::Module::reports sub reports { my($self) = @_; $self->distribution->reports; } package CPAN; use strict; 1; __END__ =head1 NAME CPAN - query, download and build perl modules from CPAN sites =head1 SYNOPSIS Interactive mode: perl -MCPAN -e shell --or-- cpan Basic commands: # Modules: cpan> install Acme::Meta # in the shell CPAN::Shell->install("Acme::Meta"); # in perl # Distributions: cpan> install NWCLARK/Acme-Meta-0.02.tar.gz # in the shell CPAN::Shell-> install("NWCLARK/Acme-Meta-0.02.tar.gz"); # in perl # module objects: $mo = CPAN::Shell->expandany($mod); $mo = CPAN::Shell->expand("Module",$mod); # same thing # distribution objects: $do = CPAN::Shell->expand("Module",$mod)->distribution; $do = CPAN::Shell->expandany($distro); # same thing $do = CPAN::Shell->expand("Distribution", $distro); # same thing =head1 DESCRIPTION The CPAN module automates or at least simplifies the make and install of perl modules and extensions. It includes some primitive searching capabilities and knows how to use Net::FTP or LWP or some external download clients to fetch the distributions from the net. These are fetched from one or more of the mirrored CPAN (Comprehensive Perl Archive Network) sites and unpacked in a dedicated directory. The CPAN module also supports the concept of named and versioned I<bundles> of modules. Bundles simplify the handling of sets of related modules. See Bundles below. The package contains a session manager and a cache manager. The session manager keeps track of what has been fetched, built and installed in the current session. The cache manager keeps track of the disk space occupied by the make processes and deletes excess space according to a simple FIFO mechanism. All methods provided are accessible in a programmer style and in an interactive shell style. =head2 CPAN::shell([$prompt, $command]) Starting Interactive Mode The interactive mode is entered by running perl -MCPAN -e shell or cpan which puts you into a readline interface. If C<Term::ReadKey> and either C<Term::ReadLine::Perl> or C<Term::ReadLine::Gnu> are installed it supports both history and command completion. Once you are on the command line, type C<h> to get a one page help screen and the rest should be self-explanatory. The function call C<shell> takes two optional arguments, one is the prompt, the second is the default initial command line (the latter only works if a real ReadLine interface module is installed). The most common uses of the interactive modes are =over 2 =item Searching for authors, bundles, distribution files and modules There are corresponding one-letter commands C<a>, C<b>, C<d>, and C<m> for each of the four categories and another, C<i> for any of the mentioned four. Each of the four entities is implemented as a class with slightly differing methods for displaying an object. Arguments you pass to these commands are either strings exactly matching the identification string of an object or regular expressions that are then matched case-insensitively against various attributes of the objects. The parser recognizes a regular expression only if you enclose it between two slashes. The principle is that the number of found objects influences how an item is displayed. If the search finds one item, the result is displayed with the rather verbose method C<as_string>, but if we find more than one, we display each object with the terse method C<as_glimpse>. =item C<get>, C<make>, C<test>, C<install>, C<clean> modules or distributions These commands take any number of arguments and investigate what is necessary to perform the action. If the argument is a distribution file name (recognized by embedded slashes), it is processed. If it is a module, CPAN determines the distribution file in which this module is included and processes that, following any dependencies named in the module's META.yml or Makefile.PL (this behavior is controlled by the configuration parameter C<prerequisites_policy>.) C<get> downloads a distribution file and untars or unzips it, C<make> builds it, C<test> runs the test suite, and C<install> installs it. Any C<make> or C<test> are run unconditionally. An install <distribution_file> also is run unconditionally. But for install <module> CPAN checks if an install is actually needed for it and prints I<module up to date> in the case that the distribution file containing the module doesn't need to be updated. CPAN also keeps track of what it has done within the current session and doesn't try to build a package a second time regardless if it succeeded or not. It does not repeat a test run if the test has been run successfully before. Same for install runs. The C<force> pragma may precede another command (currently: C<get>, C<make>, C<test>, or C<install>) and executes the command from scratch and tries to continue in case of some errors. See the section below on the C<force> and the C<fforce> pragma. The C<notest> pragma may be used to skip the test part in the build process. Example: cpan> notest install Tk A C<clean> command results in a make clean being executed within the distribution file's working directory. =item C<readme>, C<perldoc>, C<look> module or distribution C<readme> displays the README file of the associated distribution. C<Look> gets and untars (if not yet done) the distribution file, changes to the appropriate directory and opens a subshell process in that directory. C<perldoc> displays the pod documentation of the module in html or plain text format. =item C<ls> author =item C<ls> globbing_expression The first form lists all distribution files in and below an author's CPAN directory as they are stored in the CHECKUMS files distributed on CPAN. The listing goes recursive into all subdirectories. The second form allows to limit or expand the output with shell globbing as in the following examples: ls JV/make* ls GSAR/*make* ls */*make* The last example is very slow and outputs extra progress indicators that break the alignment of the result. Note that globbing only lists directories explicitly asked for, for example FOO/* will not list FOO/bar/Acme-Sthg-n.nn.tar.gz. This may be regarded as a bug and may be changed in future versions. =item C<failed> The C<failed> command reports all distributions that failed on one of C<make>, C<test> or C<install> for some reason in the currently running shell session. =item Persistence between sessions If the C<YAML> or the C<YAML::Syck> module is installed a record of the internal state of all modules is written to disk after each step. The files contain a signature of the currently running perl version for later perusal. If the configurations variable C<build_dir_reuse> is set to a true value, then CPAN.pm reads the collected YAML files. If the stored signature matches the currently running perl the stored state is loaded into memory such that effectively persistence between sessions is established. =item The C<force> and the C<fforce> pragma To speed things up in complex installation scenarios, CPAN.pm keeps track of what it has already done and refuses to do some things a second time. A C<get>, a C<make>, and an C<install> are not repeated. A C<test> is only repeated if the previous test was unsuccessful. The diagnostic message when CPAN.pm refuses to do something a second time is one of I<Has already been >C<unwrapped|made|tested successfully> or something similar. Another situation where CPAN refuses to act is an C<install> if the according C<test> was not successful. In all these cases, the user can override the goatish behaviour by prepending the command with the word force, for example: cpan> force get Foo cpan> force make AUTHOR/Bar-3.14.tar.gz cpan> force test Baz cpan> force install Acme::Meta Each I<forced> command is executed with the according part of its memory erased. The C<fforce> pragma is a variant that emulates a C<force get> which erases the entire memory followed by the action specified, effectively restarting the whole get/make/test/install procedure from scratch. =item Lockfile Interactive sessions maintain a lockfile, per default C<~/.cpan/.lock>. Batch jobs can run without a lockfile and do not disturb each other. The shell offers to run in I<degraded mode> when another process is holding the lockfile. This is an experimental feature that is not yet tested very well. This second shell then does not write the history file, does not use the metadata file and has a different prompt. =item Signals CPAN.pm installs signal handlers for SIGINT and SIGTERM. While you are in the cpan-shell it is intended that you can press C<^C> anytime and return to the cpan-shell prompt. A SIGTERM will cause the cpan-shell to clean up and leave the shell loop. You can emulate the effect of a SIGTERM by sending two consecutive SIGINTs, which usually means by pressing C<^C> twice. CPAN.pm ignores a SIGPIPE. If the user sets C<inactivity_timeout>, a SIGALRM is used during the run of the C<perl Makefile.PL> or C<perl Build.PL> subprocess. =back =head2 CPAN::Shell The commands that are available in the shell interface are methods in the package CPAN::Shell. If you enter the shell command, all your input is split by the Text::ParseWords::shellwords() routine which acts like most shells do. The first word is being interpreted as the method to be called and the rest of the words are treated as arguments to this method. Continuation lines are supported if a line ends with a literal backslash. =head2 autobundle C<autobundle> writes a bundle file into the C<$CPAN::Config-E<gt>{cpan_home}/Bundle> directory. The file contains a list of all modules that are both available from CPAN and currently installed within @INC. The name of the bundle file is based on the current date and a counter. =head2 hosts Note: this feature is still in alpha state and may change in future versions of CPAN.pm This commands provides a statistical overview over recent download activities. The data for this is collected in the YAML file C<FTPstats.yml> in your C<cpan_home> directory. If no YAML module is configured or YAML not installed, then no stats are provided. =head2 mkmyconfig mkmyconfig() writes your own CPAN::MyConfig file into your ~/.cpan/ directory so that you can save your own preferences instead of the system wide ones. =head2 recent ***EXPERIMENTAL COMMAND*** The C<recent> command downloads a list of recent uploads to CPAN and displays them I<slowly>. While the command is running $SIG{INT} is defined to mean that the loop shall be left after having displayed the current item. B<Note>: This command requires XML::LibXML installed. B<Note>: This whole command currently is a bit klunky and will probably change in future versions of CPAN.pm but the general approach will likely stay. B<Note>: See also L<smoke> =head2 recompile recompile() is a very special command in that it takes no argument and runs the make/test/install cycle with brute force over all installed dynamically loadable extensions (aka XS modules) with 'force' in effect. The primary purpose of this command is to finish a network installation. Imagine, you have a common source tree for two different architectures. You decide to do a completely independent fresh installation. You start on one architecture with the help of a Bundle file produced earlier. CPAN installs the whole Bundle for you, but when you try to repeat the job on the second architecture, CPAN responds with a C<"Foo up to date"> message for all modules. So you invoke CPAN's recompile on the second architecture and you're done. Another popular use for C<recompile> is to act as a rescue in case your perl breaks binary compatibility. If one of the modules that CPAN uses is in turn depending on binary compatibility (so you cannot run CPAN commands), then you should try the CPAN::Nox module for recovery. =head2 report Bundle|Distribution|Module The C<report> command temporarily turns on the C<test_report> config variable, then runs the C<force test> command with the given arguments. The C<force> pragma is used to re-run the tests and repeat every step that might have failed before. =head2 smoke ***EXPERIMENTAL COMMAND*** B<*** WARNING: this command downloads and executes software from CPAN to your computer of completely unknown status. You should never do this with your normal account and better have a dedicated well separated and secured machine to do this. ***> The C<smoke> command takes the list of recent uploads to CPAN as provided by the C<recent> command and tests them all. While the command is running $SIG{INT} is defined to mean that the current item shall be skipped. B<Note>: This whole command currently is a bit klunky and will probably change in future versions of CPAN.pm but the general approach will likely stay. B<Note>: See also L<recent> =head2 upgrade [Module|/Regex/]... The C<upgrade> command first runs an C<r> command with the given arguments and then installs the newest versions of all modules that were listed by that. =head2 The four C<CPAN::*> Classes: Author, Bundle, Module, Distribution Although it may be considered internal, the class hierarchy does matter for both users and programmer. CPAN.pm deals with above mentioned four classes, and all those classes share a set of methods. A classical single polymorphism is in effect. A metaclass object registers all objects of all kinds and indexes them with a string. The strings referencing objects have a separated namespace (well, not completely separated): Namespace Class words containing a "/" (slash) Distribution words starting with Bundle:: Bundle everything else Module or Author Modules know their associated Distribution objects. They always refer to the most recent official release. Developers may mark their releases as unstable development versions (by inserting an underbar into the module version number which will also be reflected in the distribution name when you run 'make dist'), so the really hottest and newest distribution is not always the default. If a module Foo circulates on CPAN in both version 1.23 and 1.23_90, CPAN.pm offers a convenient way to install version 1.23 by saying install Foo This would install the complete distribution file (say BAR/Foo-1.23.tar.gz) with all accompanying material. But if you would like to install version 1.23_90, you need to know where the distribution file resides on CPAN relative to the authors/id/ directory. If the author is BAR, this might be BAR/Foo-1.23_90.tar.gz; so you would have to say install BAR/Foo-1.23_90.tar.gz The first example will be driven by an object of the class CPAN::Module, the second by an object of class CPAN::Distribution. =head2 Integrating local directories Note: this feature is still in alpha state and may change in future versions of CPAN.pm Distribution objects are normally distributions from the CPAN, but there is a slightly degenerate case for Distribution objects, too, of projects held on the local disk. These distribution objects have the same name as the local directory and end with a dot. A dot by itself is also allowed for the current directory at the time CPAN.pm was used. All actions such as C<make>, C<test>, and C<install> are applied directly to that directory. This gives the command C<cpan .> an interesting touch: while the normal mantra of installing a CPAN module without CPAN.pm is one of perl Makefile.PL perl Build.PL ( go and get prerequisites ) make ./Build make test ./Build test make install ./Build install the command C<cpan .> does all of this at once. It figures out which of the two mantras is appropriate, fetches and installs all prerequisites, cares for them recursively and finally finishes the installation of the module in the current directory, be it a CPAN module or not. The typical usage case is for private modules or working copies of projects from remote repositories on the local disk. =head1 CONFIGURATION When the CPAN module is used for the first time, a configuration dialog tries to determine a couple of site specific options. The result of the dialog is stored in a hash reference C< $CPAN::Config > in a file CPAN/Config.pm. The default values defined in the CPAN/Config.pm file can be overridden in a user specific file: CPAN/MyConfig.pm. Such a file is best placed in $HOME/.cpan/CPAN/MyConfig.pm, because $HOME/.cpan is added to the search path of the CPAN module before the use() or require() statements. The mkmyconfig command writes this file for you. The C<o conf> command has various bells and whistles: =over =item completion support If you have a ReadLine module installed, you can hit TAB at any point of the commandline and C<o conf> will offer you completion for the built-in subcommands and/or config variable names. =item displaying some help: o conf help Displays a short help =item displaying current values: o conf [KEY] Displays the current value(s) for this config variable. Without KEY displays all subcommands and config variables. Example: o conf shell If KEY starts and ends with a slash the string in between is interpreted as a regular expression and only keys matching this regex are displayed Example: o conf /color/ =item changing of scalar values: o conf KEY VALUE Sets the config variable KEY to VALUE. The empty string can be specified as usual in shells, with C<''> or C<""> Example: o conf wget /usr/bin/wget =item changing of list values: o conf KEY SHIFT|UNSHIFT|PUSH|POP|SPLICE|LIST If a config variable name ends with C<list>, it is a list. C<o conf KEY shift> removes the first element of the list, C<o conf KEY pop> removes the last element of the list. C<o conf KEYS unshift LIST> prepends a list of values to the list, C<o conf KEYS push LIST> appends a list of valued to the list. Likewise, C<o conf KEY splice LIST> passes the LIST to the according splice command. Finally, any other list of arguments is taken as a new list value for the KEY variable discarding the previous value. Examples: o conf urllist unshift http://cpan.dev.local/CPAN o conf urllist splice 3 1 o conf urllist http://cpan1.local http://cpan2.local ftp://ftp.perl.org =item reverting to saved: o conf defaults Reverts all config variables to the state in the saved config file. =item saving the config: o conf commit Saves all config variables to the current config file (CPAN/Config.pm or CPAN/MyConfig.pm that was loaded at start). =back The configuration dialog can be started any time later again by issuing the command C< o conf init > in the CPAN shell. A subset of the configuration dialog can be run by issuing C<o conf init WORD> where WORD is any valid config variable or a regular expression. =head2 Config Variables Currently the following keys in the hash reference $CPAN::Config are defined: applypatch path to external prg auto_commit commit all changes to config variables to disk build_cache size of cache for directories to build modules build_dir locally accessible directory to build modules build_dir_reuse boolean if distros in build_dir are persistent build_requires_install_policy to install or not to install when a module is only needed for building. yes|no|ask/yes|ask/no bzip2 path to external prg cache_metadata use serializer to cache metadata commands_quote prefered character to use for quoting external commands when running them. Defaults to double quote on Windows, single tick everywhere else; can be set to space to disable quoting check_sigs if signatures should be verified colorize_debug Term::ANSIColor attributes for debugging output colorize_output boolean if Term::ANSIColor should colorize output colorize_print Term::ANSIColor attributes for normal output colorize_warn Term::ANSIColor attributes for warnings commandnumber_in_prompt boolean if you want to see current command number cpan_home local directory reserved for this package curl path to external prg dontload_hash DEPRECATED dontload_list arrayref: modules in the list will not be loaded by the CPAN::has_inst() routine ftp path to external prg ftp_passive if set, the envariable FTP_PASSIVE is set for downloads ftp_proxy proxy host for ftp requests getcwd see below gpg path to external prg gzip location of external program gzip histfile file to maintain history between sessions histsize maximum number of lines to keep in histfile http_proxy proxy host for http requests inactivity_timeout breaks interactive Makefile.PLs or Build.PLs after this many seconds inactivity. Set to 0 to never break. index_expire after this many days refetch index files inhibit_startup_message if true, does not print the startup message keep_source_where directory in which to keep the source (if we do) load_module_verbosity report loading of optional modules used by CPAN.pm lynx path to external prg make location of external make program make_arg arguments that should always be passed to 'make' make_install_make_command the make command for running 'make install', for example 'sudo make' make_install_arg same as make_arg for 'make install' makepl_arg arguments passed to 'perl Makefile.PL' mbuild_arg arguments passed to './Build' mbuild_install_arg arguments passed to './Build install' mbuild_install_build_command command to use instead of './Build' when we are in the install stage, for example 'sudo ./Build' mbuildpl_arg arguments passed to 'perl Build.PL' ncftp path to external prg ncftpget path to external prg no_proxy don't proxy to these hosts/domains (comma separated list) pager location of external program more (or any pager) password your password if you CPAN server wants one patch path to external prg prefer_installer legal values are MB and EUMM: if a module comes with both a Makefile.PL and a Build.PL, use the former (EUMM) or the latter (MB); if the module comes with only one of the two, that one will be used in any case prerequisites_policy what to do if you are missing module prerequisites ('follow' automatically, 'ask' me, or 'ignore') prefs_dir local directory to store per-distro build options proxy_user username for accessing an authenticating proxy proxy_pass password for accessing an authenticating proxy randomize_urllist add some randomness to the sequence of the urllist scan_cache controls scanning of cache ('atstart' or 'never') shell your favorite shell show_unparsable_versions boolean if r command tells which modules are versionless show_upload_date boolean if commands should try to determine upload date show_zero_versions boolean if r command tells for which modules $version==0 tar location of external program tar tar_verbosity verbosity level for the tar command term_is_latin deprecated: if true Unicode is translated to ISO-8859-1 (and nonsense for characters outside latin range) term_ornaments boolean to turn ReadLine ornamenting on/off test_report email test reports (if CPAN::Reporter is installed) unzip location of external program unzip urllist arrayref to nearby CPAN sites (or equivalent locations) use_sqlite use CPAN::SQLite for metadata storage (fast and lean) username your username if you CPAN server wants one wait_list arrayref to a wait server to try (See CPAN::WAIT) wget path to external prg yaml_load_code enable YAML code deserialisation yaml_module which module to use to read/write YAML files You can set and query each of these options interactively in the cpan shell with the C<o conf> or the C<o conf init> command as specified below. =over 2 =item C<o conf E<lt>scalar optionE<gt>> prints the current value of the I<scalar option> =item C<o conf E<lt>scalar optionE<gt> E<lt>valueE<gt>> Sets the value of the I<scalar option> to I<value> =item C<o conf E<lt>list optionE<gt>> prints the current value of the I<list option> in MakeMaker's neatvalue format. =item C<o conf E<lt>list optionE<gt> [shift|pop]> shifts or pops the array in the I<list option> variable =item C<o conf E<lt>list optionE<gt> [unshift|push|splice] E<lt>listE<gt>> works like the corresponding perl commands. =item interactive editing: o conf init [MATCH|LIST] Runs an interactive configuration dialog for matching variables. Without argument runs the dialog over all supported config variables. To specify a MATCH the argument must be enclosed by slashes. Examples: o conf init ftp_passive ftp_proxy o conf init /color/ Note: this method of setting config variables often provides more explanation about the functioning of a variable than the manpage. =back =head2 CPAN::anycwd($path): Note on config variable getcwd CPAN.pm changes the current working directory often and needs to determine its own current working directory. Per default it uses Cwd::cwd but if this doesn't work on your system for some reason, alternatives can be configured according to the following table: =over 4 =item cwd Calls Cwd::cwd =item getcwd Calls Cwd::getcwd =item fastcwd Calls Cwd::fastcwd =item backtickcwd Calls the external command cwd. =back =head2 Note on the format of the urllist parameter urllist parameters are URLs according to RFC 1738. We do a little guessing if your URL is not compliant, but if you have problems with C<file> URLs, please try the correct format. Either: file://localhost/whatever/ftp/pub/CPAN/ or file:///home/ftp/pub/CPAN/ =head2 The urllist parameter has CD-ROM support The C<urllist> parameter of the configuration table contains a list of URLs that are to be used for downloading. If the list contains any C<file> URLs, CPAN always tries to get files from there first. This feature is disabled for index files. So the recommendation for the owner of a CD-ROM with CPAN contents is: include your local, possibly outdated CD-ROM as a C<file> URL at the end of urllist, e.g. o conf urllist push file://localhost/CDROM/CPAN CPAN.pm will then fetch the index files from one of the CPAN sites that come at the beginning of urllist. It will later check for each module if there is a local copy of the most recent version. Another peculiarity of urllist is that the site that we could successfully fetch the last file from automatically gets a preference token and is tried as the first site for the next request. So if you add a new site at runtime it may happen that the previously preferred site will be tried another time. This means that if you want to disallow a site for the next transfer, it must be explicitly removed from urllist. =head2 Maintaining the urllist parameter If you have YAML.pm (or some other YAML module configured in C<yaml_module>) installed, CPAN.pm collects a few statistical data about recent downloads. You can view the statistics with the C<hosts> command or inspect them directly by looking into the C<FTPstats.yml> file in your C<cpan_home> directory. To get some interesting statistics it is recommended to set the C<randomize_urllist> parameter that introduces some amount of randomness into the URL selection. =head2 The C<requires> and C<build_requires> dependency declarations Since CPAN.pm version 1.88_51 modules declared as C<build_requires> by a distribution are treated differently depending on the config variable C<build_requires_install_policy>. By setting C<build_requires_install_policy> to C<no> such a module is not being installed. It is only built and tested and then kept in the list of tested but uninstalled modules. As such it is available during the build of the dependent module by integrating the path to the C<blib/arch> and C<blib/lib> directories in the environment variable PERL5LIB. If C<build_requires_install_policy> is set ti C<yes>, then both modules declared as C<requires> and those declared as C<build_requires> are treated alike. By setting to C<ask/yes> or C<ask/no>, CPAN.pm asks the user and sets the default accordingly. =head2 Configuration for individual distributions (I<Distroprefs>) (B<Note:> This feature has been introduced in CPAN.pm 1.8854 and is still considered beta quality) Distributions on the CPAN usually behave according to what we call the CPAN mantra. Or since the event of Module::Build we should talk about two mantras: perl Makefile.PL perl Build.PL make ./Build make test ./Build test make install ./Build install But some modules cannot be built with this mantra. They try to get some extra data from the user via the environment, extra arguments or interactively thus disturbing the installation of large bundles like Phalanx100 or modules with many dependencies like Plagger. The distroprefs system of C<CPAN.pm> addresses this problem by allowing the user to specify extra informations and recipes in YAML files to either =over =item pass additional arguments to one of the four commands, =item set environment variables =item instantiate an Expect object that reads from the console, waits for some regular expressions and enters some answers =item temporarily override assorted C<CPAN.pm> configuration variables =item specify dependencies that the original maintainer forgot to specify =item disable the installation of an object altogether =back See the YAML and Data::Dumper files that come with the C<CPAN.pm> distribution in the C<distroprefs/> directory for examples. =head2 Filenames The YAML files themselves must have the C<.yml> extension, all other files are ignored (for two exceptions see I<Fallback Data::Dumper and Storable> below). The containing directory can be specified in C<CPAN.pm> in the C<prefs_dir> config variable. Try C<o conf init prefs_dir> in the CPAN shell to set and activate the distroprefs system. Every YAML file may contain arbitrary documents according to the YAML specification and every single document is treated as an entity that can specify the treatment of a single distribution. The names of the files can be picked freely, C<CPAN.pm> always reads all files (in alphabetical order) and takes the key C<match> (see below in I<Language Specs>) as a hashref containing match criteria that determine if the current distribution matches the YAML document or not. =head2 Fallback Data::Dumper and Storable If neither your configured C<yaml_module> nor YAML.pm is installed CPAN.pm falls back to using Data::Dumper and Storable and looks for files with the extensions C<.dd> or C<.st> in the C<prefs_dir> directory. These files are expected to contain one or more hashrefs. For Data::Dumper generated files, this is expected to be done with by defining C<$VAR1>, C<$VAR2>, etc. The YAML shell would produce these with the command ysh < somefile.yml > somefile.dd For Storable files the rule is that they must be constructed such that C<Storable::retrieve(file)> returns an array reference and the array elements represent one distropref object each. The conversion from YAML would look like so: perl -MYAML=LoadFile -MStorable=nstore -e ' @y=LoadFile(shift); nstore(\@y, shift)' somefile.yml somefile.st In bootstrapping situations it is usually sufficient to translate only a few YAML files to Data::Dumper for the crucial modules like C<YAML::Syck>, C<YAML.pm> and C<Expect.pm>. If you prefer Storable over Data::Dumper, remember to pull out a Storable version that writes an older format than all the other Storable versions that will need to read them. =head2 Blueprint The following example contains all supported keywords and structures with the exception of C<eexpect> which can be used instead of C<expect>. --- comment: "Demo" match: module: "Dancing::Queen" distribution: "^CHACHACHA/Dancing-" perl: "/usr/local/cariba-perl/bin/perl" perlconfig: archname: "freebsd" disabled: 1 cpanconfig: make: gmake pl: args: - "--somearg=specialcase" env: {} expect: - "Which is your favorite fruit" - "apple\n" make: args: - all - extra-all env: {} expect: [] commendline: "echo SKIPPING make" test: args: [] env: {} expect: [] install: args: [] env: WANT_TO_INSTALL: YES expect: - "Do you really want to install" - "y\n" patches: - "ABCDE/Fedcba-3.14-ABCDE-01.patch" depends: configure_requires: LWP: 5.8 build_requires: Test::Exception: 0.25 requires: Spiffy: 0.30 =head2 Language Specs Every YAML document represents a single hash reference. The valid keys in this hash are as follows: =over =item comment [scalar] A comment =item cpanconfig [hash] Temporarily override assorted C<CPAN.pm> configuration variables. Supported are: C<build_requires_install_policy>, C<check_sigs>, C<make>, C<make_install_make_command>, C<prefer_installer>, C<test_report>. Please report as a bug when you need another one supported. =item depends [hash] *** EXPERIMENTAL FEATURE *** All three types, namely C<configure_requires>, C<build_requires>, and C<requires> are supported in the way specified in the META.yml specification. The current implementation I<merges> the specified dependencies with those declared by the package maintainer. In a future implementation this may be changed to override the original declaration. =item disabled [boolean] Specifies that this distribution shall not be processed at all. =item goto [string] The canonical name of a delegate distribution that shall be installed instead. Useful when a new version, although it tests OK itself, breaks something else or a developer release or a fork is already uploaded that is better than the last released version. =item install [hash] Processing instructions for the C<make install> or C<./Build install> phase of the CPAN mantra. See below under I<Processiong Instructions>. =item make [hash] Processing instructions for the C<make> or C<./Build> phase of the CPAN mantra. See below under I<Processiong Instructions>. =item match [hash] A hashref with one or more of the keys C<distribution>, C<modules>, C<perl>, and C<perlconfig> that specify if a document is targeted at a specific CPAN distribution or installation. The corresponding values are interpreted as regular expressions. The C<distribution> related one will be matched against the canonical distribution name, e.g. "AUTHOR/Foo-Bar-3.14.tar.gz". The C<module> related one will be matched against I<all> modules contained in the distribution until one module matches. The C<perl> related one will be matched against C<$^X> (but with the absolute path). The value associated with C<perlconfig> is itself a hashref that is matched against corresponding values in the C<%Config::Config> hash living in the C< Config.pm > module. If more than one restriction of C<module>, C<distribution>, and C<perl> is specified, the results of the separately computed match values must all match. If this is the case then the hashref represented by the YAML document is returned as the preference structure for the current distribution. =item patches [array] An array of patches on CPAN or on the local disk to be applied in order via the external patch program. If the value for the C<-p> parameter is C<0> or C<1> is determined by reading the patch beforehand. Note: if the C<applypatch> program is installed and C<CPAN::Config> knows about it B<and> a patch is written by the C<makepatch> program, then C<CPAN.pm> lets C<applypatch> apply the patch. Both C<makepatch> and C<applypatch> are available from CPAN in the C<JV/makepatch-*> distribution. =item pl [hash] Processing instructions for the C<perl Makefile.PL> or C<perl Build.PL> phase of the CPAN mantra. See below under I<Processiong Instructions>. =item test [hash] Processing instructions for the C<make test> or C<./Build test> phase of the CPAN mantra. See below under I<Processiong Instructions>. =back =head2 Processing Instructions =over =item args [array] Arguments to be added to the command line =item commandline A full commandline that will be executed as it stands by a system call. During the execution the environment variable PERL will is set to $^X (but with an absolute path). If C<commandline> is specified, the content of C<args> is not used. =item eexpect [hash] Extended C<expect>. This is a hash reference with four allowed keys, C<mode>, C<timeout>, C<reuse>, and C<talk>. C<mode> may have the values C<deterministic> for the case where all questions come in the order written down and C<anyorder> for the case where the questions may come in any order. The default mode is C<deterministic>. C<timeout> denotes a timeout in seconds. Floating point timeouts are OK. In the case of a C<mode=deterministic> the timeout denotes the timeout per question, in the case of C<mode=anyorder> it denotes the timeout per byte received from the stream or questions. C<talk> is a reference to an array that contains alternating questions and answers. Questions are regular expressions and answers are literal strings. The Expect module will then watch the stream coming from the execution of the external program (C<perl Makefile.PL>, C<perl Build.PL>, C<make>, etc.). In the case of C<mode=deterministic> the CPAN.pm will inject the according answer as soon as the stream matches the regular expression. In the case of C<mode=anyorder> CPAN.pm will answer a question as soon as the timeout is reached for the next byte in the input stream. In this mode you can use the C<reuse> parameter to decide what shall happen with a question-answer pair after it has been used. In the default case (reuse=0) it is removed from the array, so it cannot be used again accidentally. In this case, if you want to answer the question C<Do you really want to do that> several times, then it must be included in the array at least as often as you want this answer to be given. Setting the parameter C<reuse> to 1 makes this repetition unnecessary. =item env [hash] Environment variables to be set during the command =item expect [array] C<< expect: <array> >> is a short notation for eexpect: mode: deterministic timeout: 15 talk: <array> =back =head2 Schema verification with C<Kwalify> If you have the C<Kwalify> module installed (which is part of the Bundle::CPANxxl), then all your distroprefs files are checked for syntactical correctness. =head2 Example Distroprefs Files C<CPAN.pm> comes with a collection of example YAML files. Note that these are really just examples and should not be used without care because they cannot fit everybody's purpose. After all the authors of the packages that ask questions had a need to ask, so you should watch their questions and adjust the examples to your environment and your needs. You have beend warned:-) =head1 PROGRAMMER'S INTERFACE If you do not enter the shell, the available shell commands are both available as methods (C<CPAN::Shell-E<gt>install(...)>) and as functions in the calling package (C<install(...)>). Before calling low-level commands it makes sense to initialize components of CPAN you need, e.g.: CPAN::HandleConfig->load; CPAN::Shell::setup_output; CPAN::Index->reload; High-level commands do such initializations automatically. There's currently only one class that has a stable interface - CPAN::Shell. All commands that are available in the CPAN shell are methods of the class CPAN::Shell. Each of the commands that produce listings of modules (C<r>, C<autobundle>, C<u>) also return a list of the IDs of all modules within the list. =over 2 =item expand($type,@things) The IDs of all objects available within a program are strings that can be expanded to the corresponding real objects with the C<CPAN::Shell-E<gt>expand("Module",@things)> method. Expand returns a list of CPAN::Module objects according to the C<@things> arguments given. In scalar context it only returns the first element of the list. =item expandany(@things) Like expand, but returns objects of the appropriate type, i.e. CPAN::Bundle objects for bundles, CPAN::Module objects for modules and CPAN::Distribution objects for distributions. Note: it does not expand to CPAN::Author objects. =item Programming Examples This enables the programmer to do operations that combine functionalities that are available in the shell. # install everything that is outdated on my disk: perl -MCPAN -e 'CPAN::Shell->install(CPAN::Shell->r)' # install my favorite programs if necessary: for $mod (qw(Net::FTP Digest::SHA Data::Dumper)) { CPAN::Shell->install($mod); } # list all modules on my disk that have no VERSION number for $mod (CPAN::Shell->expand("Module","/./")) { next unless $mod->inst_file; # MakeMaker convention for undefined $VERSION: next unless $mod->inst_version eq "undef"; print "No VERSION in ", $mod->id, "\n"; } # find out which distribution on CPAN contains a module: print CPAN::Shell->expand("Module","Apache::Constants")->cpan_file Or if you want to write a cronjob to watch The CPAN, you could list all modules that need updating. First a quick and dirty way: perl -e 'use CPAN; CPAN::Shell->r;' If you don't want to get any output in the case that all modules are up to date, you can parse the output of above command for the regular expression //modules are up to date// and decide to mail the output only if it doesn't match. Ick? If you prefer to do it more in a programmer style in one single process, maybe something like this suits you better: # list all modules on my disk that have newer versions on CPAN for $mod (CPAN::Shell->expand("Module","/./")) { next unless $mod->inst_file; next if $mod->uptodate; printf "Module %s is installed as %s, could be updated to %s from CPAN\n", $mod->id, $mod->inst_version, $mod->cpan_version; } If that gives you too much output every day, you maybe only want to watch for three modules. You can write for $mod (CPAN::Shell->expand("Module","/Apache|LWP|CGI/")) { as the first line instead. Or you can combine some of the above tricks: # watch only for a new mod_perl module $mod = CPAN::Shell->expand("Module","mod_perl"); exit if $mod->uptodate; # new mod_perl arrived, let me know all update recommendations CPAN::Shell->r; =back =head2 Methods in the other Classes =over 4 =item CPAN::Author::as_glimpse() Returns a one-line description of the author =item CPAN::Author::as_string() Returns a multi-line description of the author =item CPAN::Author::email() Returns the author's email address =item CPAN::Author::fullname() Returns the author's name =item CPAN::Author::name() An alias for fullname =item CPAN::Bundle::as_glimpse() Returns a one-line description of the bundle =item CPAN::Bundle::as_string() Returns a multi-line description of the bundle =item CPAN::Bundle::clean() Recursively runs the C<clean> method on all items contained in the bundle. =item CPAN::Bundle::contains() Returns a list of objects' IDs contained in a bundle. The associated objects may be bundles, modules or distributions. =item CPAN::Bundle::force($method,@args) Forces CPAN to perform a task that it normally would have refused to do. Force takes as arguments a method name to be called and any number of additional arguments that should be passed to the called method. The internals of the object get the needed changes so that CPAN.pm does not refuse to take the action. The C<force> is passed recursively to all contained objects. See also the section above on the C<force> and the C<fforce> pragma. =item CPAN::Bundle::get() Recursively runs the C<get> method on all items contained in the bundle =item CPAN::Bundle::inst_file() Returns the highest installed version of the bundle in either @INC or C<$CPAN::Config->{cpan_home}>. Note that this is different from CPAN::Module::inst_file. =item CPAN::Bundle::inst_version() Like CPAN::Bundle::inst_file, but returns the $VERSION =item CPAN::Bundle::uptodate() Returns 1 if the bundle itself and all its members are uptodate. =item CPAN::Bundle::install() Recursively runs the C<install> method on all items contained in the bundle =item CPAN::Bundle::make() Recursively runs the C<make> method on all items contained in the bundle =item CPAN::Bundle::readme() Recursively runs the C<readme> method on all items contained in the bundle =item CPAN::Bundle::test() Recursively runs the C<test> method on all items contained in the bundle =item CPAN::Distribution::as_glimpse() Returns a one-line description of the distribution =item CPAN::Distribution::as_string() Returns a multi-line description of the distribution =item CPAN::Distribution::author Returns the CPAN::Author object of the maintainer who uploaded this distribution =item CPAN::Distribution::pretty_id() Returns a string of the form "AUTHORID/TARBALL", where AUTHORID is the author's PAUSE ID and TARBALL is the distribution filename. =item CPAN::Distribution::base_id() Returns the distribution filename without any archive suffix. E.g "Foo-Bar-0.01" =item CPAN::Distribution::clean() Changes to the directory where the distribution has been unpacked and runs C<make clean> there. =item CPAN::Distribution::containsmods() Returns a list of IDs of modules contained in a distribution file. Only works for distributions listed in the 02packages.details.txt.gz file. This typically means that only the most recent version of a distribution is covered. =item CPAN::Distribution::cvs_import() Changes to the directory where the distribution has been unpacked and runs something like cvs -d $cvs_root import -m $cvs_log $cvs_dir $userid v$version there. =item CPAN::Distribution::dir() Returns the directory into which this distribution has been unpacked. =item CPAN::Distribution::force($method,@args) Forces CPAN to perform a task that it normally would have refused to do. Force takes as arguments a method name to be called and any number of additional arguments that should be passed to the called method. The internals of the object get the needed changes so that CPAN.pm does not refuse to take the action. See also the section above on the C<force> and the C<fforce> pragma. =item CPAN::Distribution::get() Downloads the distribution from CPAN and unpacks it. Does nothing if the distribution has already been downloaded and unpacked within the current session. =item CPAN::Distribution::install() Changes to the directory where the distribution has been unpacked and runs the external command C<make install> there. If C<make> has not yet been run, it will be run first. A C<make test> will be issued in any case and if this fails, the install will be canceled. The cancellation can be avoided by letting C<force> run the C<install> for you. This install method has only the power to install the distribution if there are no dependencies in the way. To install an object and all of its dependencies, use CPAN::Shell->install. Note that install() gives no meaningful return value. See uptodate(). =item CPAN::Distribution::install_tested() Install all the distributions that have been tested sucessfully but not yet installed. See also C<is_tested>. =item CPAN::Distribution::isa_perl() Returns 1 if this distribution file seems to be a perl distribution. Normally this is derived from the file name only, but the index from CPAN can contain a hint to achieve a return value of true for other filenames too. =item CPAN::Distribution::is_tested() List all the distributions that have been tested sucessfully but not yet installed. See also C<install_tested>. =item CPAN::Distribution::look() Changes to the directory where the distribution has been unpacked and opens a subshell there. Exiting the subshell returns. =item CPAN::Distribution::make() First runs the C<get> method to make sure the distribution is downloaded and unpacked. Changes to the directory where the distribution has been unpacked and runs the external commands C<perl Makefile.PL> or C<perl Build.PL> and C<make> there. =item CPAN::Distribution::perldoc() Downloads the pod documentation of the file associated with a distribution (in html format) and runs it through the external command lynx specified in C<$CPAN::Config->{lynx}>. If lynx isn't available, it converts it to plain text with external command html2text and runs it through the pager specified in C<$CPAN::Config->{pager}> =item CPAN::Distribution::prefs() Returns the hash reference from the first matching YAML file that the user has deposited in the C<prefs_dir/> directory. The first succeeding match wins. The files in the C<prefs_dir/> are processed alphabetically and the canonical distroname (e.g. AUTHOR/Foo-Bar-3.14.tar.gz) is matched against the regular expressions stored in the $root->{match}{distribution} attribute value. Additionally all module names contained in a distribution are matched agains the regular expressions in the $root->{match}{module} attribute value. The two match values are ANDed together. Each of the two attributes are optional. =item CPAN::Distribution::prereq_pm() Returns the hash reference that has been announced by a distribution as the the C<requires> and C<build_requires> elements. These can be declared either by the C<META.yml> (if authoritative) or can be deposited after the run of C<Build.PL> in the file C<./_build/prereqs> or after the run of C<Makfile.PL> written as the C<PREREQ_PM> hash in a comment in the produced C<Makefile>. I<Note>: this method only works after an attempt has been made to C<make> the distribution. Returns undef otherwise. =item CPAN::Distribution::readme() Downloads the README file associated with a distribution and runs it through the pager specified in C<$CPAN::Config->{pager}>. =item CPAN::Distribution::reports() Downloads report data for this distribution from cpantesters.perl.org and displays a subset of them. =item CPAN::Distribution::read_yaml() Returns the content of the META.yml of this distro as a hashref. Note: works only after an attempt has been made to C<make> the distribution. Returns undef otherwise. Also returns undef if the content of META.yml is not authoritative. (The rules about what exactly makes the content authoritative are still in flux.) =item CPAN::Distribution::test() Changes to the directory where the distribution has been unpacked and runs C<make test> there. =item CPAN::Distribution::uptodate() Returns 1 if all the modules contained in the distribution are uptodate. Relies on containsmods. =item CPAN::Index::force_reload() Forces a reload of all indices. =item CPAN::Index::reload() Reloads all indices if they have not been read for more than C<$CPAN::Config->{index_expire}> days. =item CPAN::InfoObj::dump() CPAN::Author, CPAN::Bundle, CPAN::Module, and CPAN::Distribution inherit this method. It prints the data structure associated with an object. Useful for debugging. Note: the data structure is considered internal and thus subject to change without notice. =item CPAN::Module::as_glimpse() Returns a one-line description of the module in four columns: The first column contains the word C<Module>, the second column consists of one character: an equals sign if this module is already installed and uptodate, a less-than sign if this module is installed but can be upgraded, and a space if the module is not installed. The third column is the name of the module and the fourth column gives maintainer or distribution information. =item CPAN::Module::as_string() Returns a multi-line description of the module =item CPAN::Module::clean() Runs a clean on the distribution associated with this module. =item CPAN::Module::cpan_file() Returns the filename on CPAN that is associated with the module. =item CPAN::Module::cpan_version() Returns the latest version of this module available on CPAN. =item CPAN::Module::cvs_import() Runs a cvs_import on the distribution associated with this module. =item CPAN::Module::description() Returns a 44 character description of this module. Only available for modules listed in The Module List (CPAN/modules/00modlist.long.html or 00modlist.long.txt.gz) =item CPAN::Module::distribution() Returns the CPAN::Distribution object that contains the current version of this module. =item CPAN::Module::dslip_status() Returns a hash reference. The keys of the hash are the letters C<D>, C<S>, C<L>, C<I>, and <P>, for development status, support level, language, interface and public licence respectively. The data for the DSLIP status are collected by pause.perl.org when authors register their namespaces. The values of the 5 hash elements are one-character words whose meaning is described in the table below. There are also 5 hash elements C<DV>, C<SV>, C<LV>, C<IV>, and <PV> that carry a more verbose value of the 5 status variables. Where the 'DSLIP' characters have the following meanings: D - Development Stage (Note: *NO IMPLIED TIMESCALES*): i - Idea, listed to gain consensus or as a placeholder c - under construction but pre-alpha (not yet released) a/b - Alpha/Beta testing R - Released M - Mature (no rigorous definition) S - Standard, supplied with Perl 5 S - Support Level: m - Mailing-list d - Developer u - Usenet newsgroup comp.lang.perl.modules n - None known, try comp.lang.perl.modules a - abandoned; volunteers welcome to take over maintainance L - Language Used: p - Perl-only, no compiler needed, should be platform independent c - C and perl, a C compiler will be needed h - Hybrid, written in perl with optional C code, no compiler needed + - C++ and perl, a C++ compiler will be needed o - perl and another language other than C or C++ I - Interface Style f - plain Functions, no references used h - hybrid, object and function interfaces available n - no interface at all (huh?) r - some use of unblessed References or ties O - Object oriented using blessed references and/or inheritance P - Public License p - Standard-Perl: user may choose between GPL and Artistic g - GPL: GNU General Public License l - LGPL: "GNU Lesser General Public License" (previously known as "GNU Library General Public License") b - BSD: The BSD License a - Artistic license alone 2 - Artistic license 2.0 or later o - open source: appoved by www.opensource.org d - allows distribution without restrictions r - restricted distribtion n - no license at all =item CPAN::Module::force($method,@args) Forces CPAN to perform a task that it normally would have refused to do. Force takes as arguments a method name to be called and any number of additional arguments that should be passed to the called method. The internals of the object get the needed changes so that CPAN.pm does not refuse to take the action. See also the section above on the C<force> and the C<fforce> pragma. =item CPAN::Module::get() Runs a get on the distribution associated with this module. =item CPAN::Module::inst_file() Returns the filename of the module found in @INC. The first file found is reported just like perl itself stops searching @INC when it finds a module. =item CPAN::Module::available_file() Returns the filename of the module found in PERL5LIB or @INC. The first file found is reported. The advantage of this method over C<inst_file> is that modules that have been tested but not yet installed are included because PERL5LIB keeps track of tested modules. =item CPAN::Module::inst_version() Returns the version number of the installed module in readable format. =item CPAN::Module::available_version() Returns the version number of the available module in readable format. =item CPAN::Module::install() Runs an C<install> on the distribution associated with this module. =item CPAN::Module::look() Changes to the directory where the distribution associated with this module has been unpacked and opens a subshell there. Exiting the subshell returns. =item CPAN::Module::make() Runs a C<make> on the distribution associated with this module. =item CPAN::Module::manpage_headline() If module is installed, peeks into the module's manpage, reads the headline and returns it. Moreover, if the module has been downloaded within this session, does the equivalent on the downloaded module even if it is not installed. =item CPAN::Module::perldoc() Runs a C<perldoc> on this module. =item CPAN::Module::readme() Runs a C<readme> on the distribution associated with this module. =item CPAN::Module::reports() Calls the reports() method on the associated distribution object. =item CPAN::Module::test() Runs a C<test> on the distribution associated with this module. =item CPAN::Module::uptodate() Returns 1 if the module is installed and up-to-date. =item CPAN::Module::userid() Returns the author's ID of the module. =back =head2 Cache Manager Currently the cache manager only keeps track of the build directory ($CPAN::Config->{build_dir}). It is a simple FIFO mechanism that deletes complete directories below C<build_dir> as soon as the size of all directories there gets bigger than $CPAN::Config->{build_cache} (in MB). The contents of this cache may be used for later re-installations that you intend to do manually, but will never be trusted by CPAN itself. This is due to the fact that the user might use these directories for building modules on different architectures. There is another directory ($CPAN::Config->{keep_source_where}) where the original distribution files are kept. This directory is not covered by the cache manager and must be controlled by the user. If you choose to have the same directory as build_dir and as keep_source_where directory, then your sources will be deleted with the same fifo mechanism. =head2 Bundles A bundle is just a perl module in the namespace Bundle:: that does not define any functions or methods. It usually only contains documentation. It starts like a perl module with a package declaration and a $VERSION variable. After that the pod section looks like any other pod with the only difference being that I<one special pod section> exists starting with (verbatim): =head1 CONTENTS In this pod section each line obeys the format Module_Name [Version_String] [- optional text] The only required part is the first field, the name of a module (e.g. Foo::Bar, ie. I<not> the name of the distribution file). The rest of the line is optional. The comment part is delimited by a dash just as in the man page header. The distribution of a bundle should follow the same convention as other distributions. Bundles are treated specially in the CPAN package. If you say 'install Bundle::Tkkit' (assuming such a bundle exists), CPAN will install all the modules in the CONTENTS section of the pod. You can install your own Bundles locally by placing a conformant Bundle file somewhere into your @INC path. The autobundle() command which is available in the shell interface does that for you by including all currently installed modules in a snapshot bundle file. =head1 PREREQUISITES If you have a local mirror of CPAN and can access all files with "file:" URLs, then you only need a perl better than perl5.003 to run this module. Otherwise Net::FTP is strongly recommended. LWP may be required for non-UNIX systems or if your nearest CPAN site is associated with a URL that is not C<ftp:>. If you have neither Net::FTP nor LWP, there is a fallback mechanism implemented for an external ftp command or for an external lynx command. =head1 UTILITIES =head2 Finding packages and VERSION This module presumes that all packages on CPAN =over 2 =item * declare their $VERSION variable in an easy to parse manner. This prerequisite can hardly be relaxed because it consumes far too much memory to load all packages into the running program just to determine the $VERSION variable. Currently all programs that are dealing with version use something like this perl -MExtUtils::MakeMaker -le \ 'print MM->parse_version(shift)' filename If you are author of a package and wonder if your $VERSION can be parsed, please try the above method. =item * come as compressed or gzipped tarfiles or as zip files and contain a C<Makefile.PL> or C<Build.PL> (well, we try to handle a bit more, but without much enthusiasm). =back =head2 Debugging The debugging of this module is a bit complex, because we have interferences of the software producing the indices on CPAN, of the mirroring process on CPAN, of packaging, of configuration, of synchronicity, and of bugs within CPAN.pm. For debugging the code of CPAN.pm itself in interactive mode some more or less useful debugging aid can be turned on for most packages within CPAN.pm with one of =over 2 =item o debug package... sets debug mode for packages. =item o debug -package... unsets debug mode for packages. =item o debug all turns debugging on for all packages. =item o debug number =back which sets the debugging packages directly. Note that C<o debug 0> turns debugging off. What seems quite a successful strategy is the combination of C<reload cpan> and the debugging switches. Add a new debug statement while running in the shell and then issue a C<reload cpan> and see the new debugging messages immediately without losing the current context. C<o debug> without an argument lists the valid package names and the current set of packages in debugging mode. C<o debug> has built-in completion support. For debugging of CPAN data there is the C<dump> command which takes the same arguments as make/test/install and outputs each object's Data::Dumper dump. If an argument looks like a perl variable and contains one of C<$>, C<@> or C<%>, it is eval()ed and fed to Data::Dumper directly. =head2 Floppy, Zip, Offline Mode CPAN.pm works nicely without network too. If you maintain machines that are not networked at all, you should consider working with file: URLs. Of course, you have to collect your modules somewhere first. So you might use CPAN.pm to put together all you need on a networked machine. Then copy the $CPAN::Config->{keep_source_where} (but not $CPAN::Config->{build_dir}) directory on a floppy. This floppy is kind of a personal CPAN. CPAN.pm on the non-networked machines works nicely with this floppy. See also below the paragraph about CD-ROM support. =head2 Basic Utilities for Programmers =over 2 =item has_inst($module) Returns true if the module is installed. Used to load all modules into the running CPAN.pm which are considered optional. The config variable C<dontload_list> can be used to intercept the C<has_inst()> call such that an optional module is not loaded despite being available. For example the following command will prevent that C<YAML.pm> is being loaded: cpan> o conf dontload_list push YAML See the source for details. =item has_usable($module) Returns true if the module is installed and is in a usable state. Only useful for a handful of modules that are used internally. See the source for details. =item instance($module) The constructor for all the singletons used to represent modules, distributions, authors and bundles. If the object already exists, this method returns the object, otherwise it calls the constructor. =back =head1 SECURITY There's no strong security layer in CPAN.pm. CPAN.pm helps you to install foreign, unmasked, unsigned code on your machine. We compare to a checksum that comes from the net just as the distribution file itself. But we try to make it easy to add security on demand: =head2 Cryptographically signed modules Since release 1.77 CPAN.pm has been able to verify cryptographically signed module distributions using Module::Signature. The CPAN modules can be signed by their authors, thus giving more security. The simple unsigned MD5 checksums that were used before by CPAN protect mainly against accidental file corruption. You will need to have Module::Signature installed, which in turn requires that you have at least one of Crypt::OpenPGP module or the command-line F<gpg> tool installed. You will also need to be able to connect over the Internet to the public keyservers, like pgp.mit.edu, and their port 11731 (the HKP protocol). The configuration parameter check_sigs is there to turn signature checking on or off. =head1 EXPORT Most functions in package CPAN are exported per default. The reason for this is that the primary use is intended for the cpan shell or for one-liners. =head1 ENVIRONMENT When the CPAN shell enters a subshell via the look command, it sets the environment CPAN_SHELL_LEVEL to 1 or increments it if it is already set. When CPAN runs, it sets the environment variable PERL5_CPAN_IS_RUNNING to the ID of the running process. It also sets PERL5_CPANPLUS_IS_RUNNING to prevent runaway processes which could happen with older versions of Module::Install. When running C<perl Makefile.PL>, the environment variable C<PERL5_CPAN_IS_EXECUTING> is set to the full path of the C<Makefile.PL> that is being executed. This prevents runaway processes with newer versions of Module::Install. When the config variable ftp_passive is set, all downloads will be run with the environment variable FTP_PASSIVE set to this value. This is in general a good idea as it influences both Net::FTP and LWP based connections. The same effect can be achieved by starting the cpan shell with this environment variable set. For Net::FTP alone, one can also always set passive mode by running libnetcfg. =head1 POPULATE AN INSTALLATION WITH LOTS OF MODULES Populating a freshly installed perl with my favorite modules is pretty easy if you maintain a private bundle definition file. To get a useful blueprint of a bundle definition file, the command autobundle can be used on the CPAN shell command line. This command writes a bundle definition file for all modules that are installed for the currently running perl interpreter. It's recommended to run this command only once and from then on maintain the file manually under a private name, say Bundle/my_bundle.pm. With a clever bundle file you can then simply say cpan> install Bundle::my_bundle then answer a few questions and then go out for a coffee. Maintaining a bundle definition file means keeping track of two things: dependencies and interactivity. CPAN.pm sometimes fails on calculating dependencies because not all modules define all MakeMaker attributes correctly, so a bundle definition file should specify prerequisites as early as possible. On the other hand, it's a bit annoying that many distributions need some interactive configuring. So what I try to accomplish in my private bundle file is to have the packages that need to be configured early in the file and the gentle ones later, so I can go out after a few minutes and leave CPAN.pm untended. =head1 WORKING WITH CPAN.pm BEHIND FIREWALLS Thanks to Graham Barr for contributing the following paragraphs about the interaction between perl, and various firewall configurations. For further information on firewalls, it is recommended to consult the documentation that comes with the ncftp program. If you are unable to go through the firewall with a simple Perl setup, it is very likely that you can configure ncftp so that it works for your firewall. =head2 Three basic types of firewalls Firewalls can be categorized into three basic types. =over 4 =item http firewall This is where the firewall machine runs a web server and to access the outside world you must do it via the web server. If you set environment variables like http_proxy or ftp_proxy to a values beginning with http:// or in your web browser you have to set proxy information then you know you are running an http firewall. To access servers outside these types of firewalls with perl (even for ftp) you will need to use LWP. =item ftp firewall This where the firewall machine runs an ftp server. This kind of firewall will only let you access ftp servers outside the firewall. This is usually done by connecting to the firewall with ftp, then entering a username like "user@outside.host.com" To access servers outside these type of firewalls with perl you will need to use Net::FTP. =item One way visibility I say one way visibility as these firewalls try to make themselves look invisible to the users inside the firewall. An FTP data connection is normally created by sending the remote server your IP address and then listening for the connection. But the remote server will not be able to connect to you because of the firewall. So for these types of firewall FTP connections need to be done in a passive mode. There are two that I can think off. =over 4 =item SOCKS If you are using a SOCKS firewall you will need to compile perl and link it with the SOCKS library, this is what is normally called a 'socksified' perl. With this executable you will be able to connect to servers outside the firewall as if it is not there. =item IP Masquerade This is the firewall implemented in the Linux kernel, it allows you to hide a complete network behind one IP address. With this firewall no special compiling is needed as you can access hosts directly. For accessing ftp servers behind such firewalls you usually need to set the environment variable C<FTP_PASSIVE> or the config variable ftp_passive to a true value. =back =back =head2 Configuring lynx or ncftp for going through a firewall If you can go through your firewall with e.g. lynx, presumably with a command such as /usr/local/bin/lynx -pscott:tiger then you would configure CPAN.pm with the command o conf lynx "/usr/local/bin/lynx -pscott:tiger" That's all. Similarly for ncftp or ftp, you would configure something like o conf ncftp "/usr/bin/ncftp -f /home/scott/ncftplogin.cfg" Your mileage may vary... =head1 FAQ =over 4 =item 1) I installed a new version of module X but CPAN keeps saying, I have the old version installed Most probably you B<do> have the old version installed. This can happen if a module installs itself into a different directory in the @INC path than it was previously installed. This is not really a CPAN.pm problem, you would have the same problem when installing the module manually. The easiest way to prevent this behaviour is to add the argument C<UNINST=1> to the C<make install> call, and that is why many people add this argument permanently by configuring o conf make_install_arg UNINST=1 =item 2) So why is UNINST=1 not the default? Because there are people who have their precise expectations about who may install where in the @INC path and who uses which @INC array. In fine tuned environments C<UNINST=1> can cause damage. =item 3) I want to clean up my mess, and install a new perl along with all modules I have. How do I go about it? Run the autobundle command for your old perl and optionally rename the resulting bundle file (e.g. Bundle/mybundle.pm), install the new perl with the Configure option prefix, e.g. ./Configure -Dprefix=/usr/local/perl-5.6.78.9 Install the bundle file you produced in the first step with something like cpan> install Bundle::mybundle and you're done. =item 4) When I install bundles or multiple modules with one command there is too much output to keep track of. You may want to configure something like o conf make_arg "| tee -ai /root/.cpan/logs/make.out" o conf make_install_arg "| tee -ai /root/.cpan/logs/make_install.out" so that STDOUT is captured in a file for later inspection. =item 5) I am not root, how can I install a module in a personal directory? First of all, you will want to use your own configuration, not the one that your root user installed. If you do not have permission to write in the cpan directory that root has configured, you will be asked if you want to create your own config. Answering "yes" will bring you into CPAN's configuration stage, using the system config for all defaults except things that have to do with CPAN's work directory, saving your choices to your MyConfig.pm file. You can also manually initiate this process with the following command: % perl -MCPAN -e 'mkmyconfig' or by running mkmyconfig from the CPAN shell. You will most probably also want to configure something like this: o conf makepl_arg "LIB=~/myperl/lib \ INSTALLMAN1DIR=~/myperl/man/man1 \ INSTALLMAN3DIR=~/myperl/man/man3 \ INSTALLSCRIPT=~/myperl/bin \ INSTALLBIN=~/myperl/bin" and then (oh joy) the equivalent command for Module::Build. That would be o conf mbuildpl_arg "--lib=~/myperl/lib \ --installman1dir=~/myperl/man/man1 \ --installman3dir=~/myperl/man/man3 \ --installscript=~/myperl/bin \ --installbin=~/myperl/bin" You can make this setting permanent like all C<o conf> settings with C<o conf commit> or by setting C<auto_commit> beforehand. You will have to add ~/myperl/man to the MANPATH environment variable and also tell your perl programs to look into ~/myperl/lib, e.g. by including use lib "$ENV{HOME}/myperl/lib"; or setting the PERL5LIB environment variable. While we're speaking about $ENV{HOME}, it might be worth mentioning, that for Windows we use the File::HomeDir module that provides an equivalent to the concept of the home directory on Unix. Another thing you should bear in mind is that the UNINST parameter can be dangerous when you are installing into a private area because you might accidentally remove modules that other people depend on that are not using the private area. =item 6) How to get a package, unwrap it, and make a change before building it? Have a look at the C<look> (!) command. =item 7) I installed a Bundle and had a couple of fails. When I retried, everything resolved nicely. Can this be fixed to work on first try? The reason for this is that CPAN does not know the dependencies of all modules when it starts out. To decide about the additional items to install, it just uses data found in the META.yml file or the generated Makefile. An undetected missing piece breaks the process. But it may well be that your Bundle installs some prerequisite later than some depending item and thus your second try is able to resolve everything. Please note, CPAN.pm does not know the dependency tree in advance and cannot sort the queue of things to install in a topologically correct order. It resolves perfectly well IF all modules declare the prerequisites correctly with the PREREQ_PM attribute to MakeMaker or the C<requires> stanza of Module::Build. For bundles which fail and you need to install often, it is recommended to sort the Bundle definition file manually. =item 8) In our intranet we have many modules for internal use. How can I integrate these modules with CPAN.pm but without uploading the modules to CPAN? Have a look at the CPAN::Site module. =item 9) When I run CPAN's shell, I get an error message about things in my /etc/inputrc (or ~/.inputrc) file. These are readline issues and can only be fixed by studying readline configuration on your architecture and adjusting the referenced file accordingly. Please make a backup of the /etc/inputrc or ~/.inputrc and edit them. Quite often harmless changes like uppercasing or lowercasing some arguments solves the problem. =item 10) Some authors have strange characters in their names. Internally CPAN.pm uses the UTF-8 charset. If your terminal is expecting ISO-8859-1 charset, a converter can be activated by setting term_is_latin to a true value in your config file. One way of doing so would be cpan> o conf term_is_latin 1 If other charset support is needed, please file a bugreport against CPAN.pm at rt.cpan.org and describe your needs. Maybe we can extend the support or maybe UTF-8 terminals become widely available. Note: this config variable is deprecated and will be removed in a future version of CPAN.pm. It will be replaced with the conventions around the family of $LANG and $LC_* environment variables. =item 11) When an install fails for some reason and then I correct the error condition and retry, CPAN.pm refuses to install the module, saying C<Already tried without success>. Use the force pragma like so force install Foo::Bar Or you can use look Foo::Bar and then 'make install' directly in the subshell. =item 12) How do I install a "DEVELOPER RELEASE" of a module? By default, CPAN will install the latest non-developer release of a module. If you want to install a dev release, you have to specify the partial path starting with the author id to the tarball you wish to install, like so: cpan> install KWILLIAMS/Module-Build-0.27_07.tar.gz Note that you can use the C<ls> command to get this path listed. =item 13) How do I install a module and all its dependencies from the commandline, without being prompted for anything, despite my CPAN configuration (or lack thereof)? CPAN uses ExtUtils::MakeMaker's prompt() function to ask its questions, so if you set the PERL_MM_USE_DEFAULT environment variable, you shouldn't be asked any questions at all (assuming the modules you are installing are nice about obeying that variable as well): % PERL_MM_USE_DEFAULT=1 perl -MCPAN -e 'install My::Module' =item 14) How do I create a Module::Build based Build.PL derived from an ExtUtils::MakeMaker focused Makefile.PL? http://search.cpan.org/search?query=Module::Build::Convert http://www.refcnt.org/papers/module-build-convert =item 15) What's the best CPAN site for me? The urllist config parameter is yours. You can add and remove sites at will. You should find out which sites have the best uptodateness, bandwidth, reliability, etc. and are topologically close to you. Some people prefer fast downloads, others uptodateness, others reliability. You decide which to try in which order. Henk P. Penning maintains a site that collects data about CPAN sites: http://www.cs.uu.nl/people/henkp/mirmon/cpan.html =item 16) Why do I get asked the same questions every time I start the shell? You can make your configuration changes permanent by calling the command C<o conf commit>. Alternatively set the C<auto_commit> variable to true by running C<o conf init auto_commit> and answering the following question with yes. =back =head1 COMPATIBILITY =head2 OLD PERL VERSIONS CPAN.pm is regularly tested to run under 5.004, 5.005, and assorted newer versions. It is getting more and more difficult to get the minimal prerequisites working on older perls. It is close to impossible to get the whole Bundle::CPAN working there. If you're in the position to have only these old versions, be advised that CPAN is designed to work fine without the Bundle::CPAN installed. To get things going, note that GBARR/Scalar-List-Utils-1.18.tar.gz is compatible with ancient perls and that File::Temp is listed as a prerequisite but CPAN has reasonable workarounds if it is missing. =head2 CPANPLUS This module and its competitor, the CPANPLUS module, are both much cooler than the other. CPAN.pm is older. CPANPLUS was designed to be more modular but it was never tried to make it compatible with CPAN.pm. =head1 SECURITY ADVICE This software enables you to upgrade software on your computer and so is inherently dangerous because the newly installed software may contain bugs and may alter the way your computer works or even make it unusable. Please consider backing up your data before every upgrade. =head1 BUGS Please report bugs via L<http://rt.cpan.org/> Before submitting a bug, please make sure that the traditional method of building a Perl module package from a shell by following the installation instructions of that package still works in your environment. =head1 AUTHOR Andreas Koenig C<< <andk@cpan.org> >> =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L<http://www.perl.com/perl/misc/Artistic.html> =head1 TRANSLATIONS Kawai,Takanori provides a Japanese translation of this manpage at L<http://homepage3.nifty.com/hippo2000/perltips/CPAN.htm> =head1 SEE ALSO L<cpan>, L<CPAN::Nox>, L<CPAN::Version> =cut
35.20979
125
0.524537
edc604c1330924dcf61683580fa8a5dca4aa24a3
1,731
pm
Perl
t/lib/t/MusicBrainz/Server/Controller/WS/2/LookupSeries.pm
kellnerd/musicbrainz-server
9e058e10219ea6b8942cfd64160ffe19769f747b
[ "BSD-2-Clause" ]
577
2015-01-15T12:18:50.000Z
2022-03-16T20:41:57.000Z
t/lib/t/MusicBrainz/Server/Controller/WS/2/LookupSeries.pm
kellnerd/musicbrainz-server
9e058e10219ea6b8942cfd64160ffe19769f747b
[ "BSD-2-Clause" ]
1,227
2015-04-16T01:00:29.000Z
2022-03-30T15:08:46.000Z
t/lib/t/MusicBrainz/Server/Controller/WS/2/LookupSeries.pm
kellnerd/musicbrainz-server
9e058e10219ea6b8942cfd64160ffe19769f747b
[ "BSD-2-Clause" ]
280
2015-01-04T08:39:41.000Z
2022-03-10T17:09:59.000Z
package t::MusicBrainz::Server::Controller::WS::2::LookupSeries; use Test::Routine; use Test::More; with 't::Mechanize', 't::Context'; use utf8; use Test::XML::SemanticCompare; use MusicBrainz::Server::Test ws_test => { version => 2 }; test all => sub { my $test = shift; my $c = $test->c; my $mech = $test->mech; $mech->default_header('Accept' => 'application/xml'); MusicBrainz::Server::Test->prepare_test_database($c, '+webservice'); MusicBrainz::Server::Test->prepare_test_database($c, '+webservice_annotation'); $mech->get('/ws/2/series/d977f7fd-96c9-4e3e-83b5-eb484a9e6582?inc=coffee'); is($mech->status, 400); is_xml_same($mech->content, q{<?xml version="1.0"?> <error> <text>coffee is not a valid inc parameter for the series resource.</text> <text>For usage, please see: https://musicbrainz.org/development/mmd</text> </error>}); ws_test 'basic series lookup', '/series/d977f7fd-96c9-4e3e-83b5-eb484a9e6582' => '<?xml version="1.0" encoding="UTF-8"?> <metadata xmlns="http://musicbrainz.org/ns/mmd-2.0#"> <series type="Catalogue" type-id="49482ff0-fc9e-3b8c-a2d0-30e84d9df002" id="d977f7fd-96c9-4e3e-83b5-eb484a9e6582"> <name>Bach-Werke-Verzeichnis</name> </series> </metadata>'; ws_test 'series lookup, inc=aliases', '/series/d977f7fd-96c9-4e3e-83b5-eb484a9e6582?inc=aliases' => '<?xml version="1.0" encoding="UTF-8"?> <metadata xmlns="http://musicbrainz.org/ns/mmd-2.0#"> <series type="Catalogue" type-id="49482ff0-fc9e-3b8c-a2d0-30e84d9df002" id="d977f7fd-96c9-4e3e-83b5-eb484a9e6582"> <name>Bach-Werke-Verzeichnis</name> <alias-list count="1"> <alias sort-name="BWV">BWV</alias> </alias-list> </series> </metadata>'; }; 1;
30.910714
118
0.679376
ed5edc0dc9b06da4e128582dbe7651695e657da6
4,040
pm
Perl
users/modules/EnsEMBL/Users/Command/Account/User/Add.pm
CristiGuijarro/public-plugins
060930ad6b4b47784e53c2fd9b6cd38e635f1d76
[ "Apache-2.0" ]
null
null
null
users/modules/EnsEMBL/Users/Command/Account/User/Add.pm
CristiGuijarro/public-plugins
060930ad6b4b47784e53c2fd9b6cd38e635f1d76
[ "Apache-2.0" ]
null
null
null
users/modules/EnsEMBL/Users/Command/Account/User/Add.pm
CristiGuijarro/public-plugins
060930ad6b4b47784e53c2fd9b6cd38e635f1d76
[ "Apache-2.0" ]
null
null
null
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2018] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut package EnsEMBL::Users::Command::Account::User::Add; ### Command module to add a user and a local login object to the database after successful local registration ### @author hr5 use strict; use warnings; use EnsEMBL::Users::Messages qw(MESSAGE_EMAIL_INVALID MESSAGE_NAME_MISSING MESSAGE_ALREADY_REGISTERED MESSAGE_ACCOUNT_PENDING MESSAGE_ACCOUNT_DISABLED MESSAGE_UNKNOWN_ERROR MESSAGE_VERIFICATION_SENT MESSAGE_VERIFICATION_NOT_SENT MESSAGE_CONSENT_REQUIRED); use parent qw(EnsEMBL::Users::Command::Account); sub process { my $self = shift; my $hub = $self->hub; my $object = $self->object; # validation my $fields = $self->validate_fields({ map {$_ => $hub->param($_) || ''} qw(email name) }); return $self->redirect_register($fields->{'invalid'} eq 'email' ? MESSAGE_EMAIL_INVALID : MESSAGE_NAME_MISSING, { map {$_ => $hub->param($_) || ''} qw(email name organisation country) }) if $fields->{'invalid'}; ## Sanity check that consent box has been ticked, to avoid JavaScript exploits #warn ">>> CONSENTED ".$hub->param('accounts_consent'); unless ($hub->param('accounts_consent')) { return $self->redirect_register(MESSAGE_CONSENT_REQUIRED); } my $email = $fields->{'email'}; my $login = $object->fetch_login_account($email); if ($login) { my $message; if ($login->status eq 'pending') { #warn '!!! ACCOUNT PENDING'; return $self->redirect_register(MESSAGE_ACCOUNT_PENDING, {'email' => $email}); } elsif ($login->status eq 'active') { #warn "!!! ALREADY REGISTERED"; return $self->redirect_login(MESSAGE_ALREADY_REGISTERED, {'email' => $email}); } elsif ($login->status eq 'disabled') { return $self->redirect_register(MESSAGE_ACCOUNT_DISABLED, {'email' => $email}); } else { return $self->redirect_register(MESSAGE_UNKNOWN_ERROR, {'email' => $email}); } } my $user = $object->fetch_user_by_email($email); #warn ">>> EMAIL $email"; if ($user) { ## This shouldn't get triggered if there's no login, but let's be thorough! return $self->redirect_login(MESSAGE_ALREADY_REGISTERED, {'email' => $email}); } else { warn "### CREATING NEW LOGIN OBJECT"; $login = $object->new_login_account({ 'type' => 'local', 'status' => 'pending', 'identity' => $email, }); $login->subscription([ $hub->param('subscription') ]); $login->reset_salt; $login->update_consent($hub->species_defs->GDPR_VERSION); ## Add these directly to the user table, not the login table ## otherwise they won't be updated by the web interface $user = $object->new_user_account({'email' => $email, 'name' => $fields->{'name'}}); $user->$_($hub->param($_) || '') for qw(organisation country); ## Finish setting up user object, and save it $user->add_logins([$login]); $user->add_memberships([ map { group_id => $_, status => 'active', member_status => 'active' }, @{$hub->species_defs->ENSEMBL_DEFAULT_USER_GROUPS||[]} ]); $user->save; # Send verification email my $sent = $self->mailer->send_verification_email($login); if ($sent) { return $self->redirect_message(MESSAGE_VERIFICATION_SENT, {'email' => $email}); } else { return $self->redirect_message(MESSAGE_VERIFICATION_NOT_SENT); } } } 1;
36.727273
255
0.683663
ed7d7e83efd080232fb3d38571ffc57ba1bcebd0
9,985
pl
Perl
nlp/tools/bin/geneclipse.pl
jmvallet/viky-ai
89408d38bb7a7d0900acbfa0687caca1474b89fe
[ "MIT" ]
35
2019-11-21T15:03:06.000Z
2021-11-02T15:26:40.000Z
nlp/tools/bin/geneclipse.pl
odespesse/viky-ai
de617b2798e49698e756eec0e0d6add89b57d0e0
[ "MIT" ]
54
2019-12-02T13:10:12.000Z
2021-05-23T19:57:06.000Z
nlp/tools/bin/geneclipse.pl
odespesse/viky-ai
de617b2798e49698e756eec0e0d6add89b57d0e0
[ "MIT" ]
12
2019-11-22T14:29:18.000Z
2021-05-17T20:11:19.000Z
#!/usr/bin/perl -w # # Generate Eclipse CDT project config # sub printUsage { (my $name = $0) =~ s/.*\/(.*)$/$1/; print <<END; Generate Eclipse CDT configuration from manifest.xml Usage: $name [options] TARGET PROJECT_DIR Required: TARGET Platform target to build Code::Blocks project config PROJECT_DIR Directory of the project you want to generate Eclipse CDT conf for Must contain makefile.xml (if not given, take current dir) Use 'all' to generate all components (see sources/manifest.xml) Options: -verbose Prints some more or less useful warnings and infos about process END exit; } use strict; use XML::DOM; use XML::XQL; use XML::XQL::DOM; use Getopt::Long; use Data::Dumper; use Path::Class; use lib "$ENV{OG_TOOL_PATH}/bin"; use ogutil; use File::Basename; use Cwd qw( realpath ); sub parseComponentsManifest ($); sub genNBP ($); sub parseMakefileDesc ($); sub buildIncludeString (); sub applyTemplate ($$); my @PLATFORMS = ("win32", "linux32", "linux64"); #TODO: move to ogutil.pm ? my %CBPLATFORMS = ("win32" => "Windows", "linux32" => "Unix", "linux64" => "Unix"); my $OG_TOOL_PATH; my $OG_REPO_PATH = dir(OgPathToList($ENV{OG_REPO_PATH})); my ($OS, $ARCH); my $platform; my $projectType; my $projectName; my $projectDir; my $projectDir_new; my $projectSourceDir; my $projectId; my $projectBranch; my $number_of_cpus = 4; my $outputDebug = ""; my $outputRelease = ""; my @includeList; my $includeString; my @sourceList; my $parser = new XML::DOM::Parser; my $VERBOSE = 0; GetOptions('help' => \&printUsage, 'verbose' => \$VERBOSE, ); # Check Env Var unless(exists($ENV{OG_REPO_PATH})) { print("Erreur, la variable d'environnement OG_REPO_PATH n'existe pas\n"); exit(1); } # Getting parameters unless(scalar(@ARGV) >= 1) { print("Error: Missing parameter\n"); printUsage(); } ($OG_TOOL_PATH = "$ENV{OG_TOOL_PATH}") =~ s/\\/\//g; $platform = $ARGV[0]; $projectDir = (scalar(@ARGV) > 1) ? $ARGV[1] : "."; ($OS, $ARCH) = OgParsePlatform($platform); # Checking parameters if(scalar(grep(/^$platform$/, @PLATFORMS)) == 0) { print("Error: Need a valid platform (" . join(", ", @PLATFORMS) . ")\n"); printUsage(); } if($projectDir eq "all") { print("Generating all components\n"); my @componentList = parseComponentsManifest(file("$OG_REPO_PATH","sources","manifest.xml")); for(my $i = 0; $i < scalar(@componentList); $i++) { genNBP(file("$OG_REPO_PATH","sources", $componentList[$i]{name})); } } else { genNBP($projectDir); } exit(0); # # Functions # ## @fn value parseComponentsManifest($filePath) # Open component manifest file and parse it # # \param configPath manifest file path # sub parseComponentsManifest ($) { my ($filePath) = @_; # Read config file unless(-f $filePath) { die("Error: Component manifest $filePath doesn't exist"); } # dtd check config OgCheckDTD( file("$OG_REPO_PATH", "products"), $filePath ) or warn "invalid $filePath"; # parse config my $doc = $parser->parsefile($filePath); # get all Components my @componentNodeList = $doc->xql("components_manifest/component"); if (scalar(@componentNodeList) == 0) { die("Error, empty component list in file $filePath\n"); } my @componentList = (); foreach my $item (@componentNodeList) { push(@componentList, { name => $item->getAttribute("name") }); } # free memory $doc->dispose; return(wantarray ? @componentList : \@componentList); } sub genNBP ($) { my ($projectDir) = @_; $projectDir_new = $projectDir; unless(parseMakefileDesc(file("$projectDir_new","makefile.xml")) == 0) { return(-1); } if($projectType eq "extern") { printf("Skip $projectDir_new (extern component)\n"); return(0); } $projectBranch = "viki.ai-nlp"; print("Gen viky.ai-nlp-${projectName}_${projectType} ($projectDir_new) : Eclipse CDT config.\n"); # Debug if($VERBOSE) { print "- type\n"; print Dumper($projectType); print "- project_name\n"; print Dumper($projectName); print "- sources\n"; print Dumper(@sourceList); print "- includes\n"; print Dumper(@includeList); } if($projectType ne "lib" && $projectType ne "prog") { warn("Need a valid project type ($projectType) in $projectDir/makefile.xml"); return(-1); } # generate makefile `genmake.pl $platform $projectDir`; $includeString = buildIncludeString(); if (! -e "$projectDir_new/.settings") { `mkdir $projectDir_new/.settings`; } # Generate a random id between 1000000000 and 9999999999 $projectId = int(rand(9000000000)) + 1000000000 - 1; my $conf_template = file($ENV{OG_TOOL_PATH}, "template", "eclipse", "project.xml"); my $conf_target = file("$projectDir_new", ".project"); applyTemplate($conf_template, $conf_target); $conf_template = file($ENV{OG_TOOL_PATH}, "template", "eclipse", "cproject.xml"); $conf_target = file("$projectDir_new", ".cproject"); applyTemplate($conf_template, $conf_target); $conf_template = file($ENV{OG_TOOL_PATH}, "template", "eclipse", "language.settings.xml"); $conf_target = file("$projectDir_new", ".settings", "language.settings.xml"); applyTemplate($conf_template, $conf_target); # include conf if(${projectType} =~ /lib/ ) { my $module_name = "viky.ai-nlp-${projectName}_${projectType}"; # create project file my $include_cproject_file = "${OG_REPO_PATH}/sources/include/.cproject"; unless ( -e $include_cproject_file) { $projectName = "viki.ai-nlp-include"; $conf_template = file($ENV{OG_TOOL_PATH}, "template", "eclipse", "cproject.xml"); $conf_target = file($include_cproject_file); applyTemplate($conf_template, $conf_target); # disable build on include my $sed_cmd_1 = "sed -i -e 's|enableCleanBuild=\"true\" enabledIncrementalBuild=\"true\"|enableCleanBuild=\"false\" enabledIncrementalBuild=\"false\"|' ${include_cproject_file}"; system($sed_cmd_1); } # create project file my $include_project_file = "${OG_REPO_PATH}/sources/include/.project"; unless ( -e $include_project_file) { $projectName = "viki.ai-nlp-include"; $conf_template = file($ENV{OG_TOOL_PATH}, "template", "eclipse", "project.xml"); $conf_target = file($include_project_file); applyTemplate($conf_template, $conf_target); } # update reference projects list my $module_already_in_file = `grep \"<project>${module_name}</project>\" ${include_project_file} | wc -l`; if ($module_already_in_file == 0) { my $sed_cmd_2 = "sed -i -e 's|</projects>| <project>${module_name}</project>\\n </projects>|' ${include_project_file}"; system($sed_cmd_2); } } return(0); } sub applyTemplate ($$) { my ($template, $target) = @_; unless(open(TPL, "<$template") != 0) { warn("Cannot open $template"); return(-1); } unless(open(TGT, ">$target") != 0) { warn("Cannot open $target"); close(TPL); return(-1); } my $module_name = "viky.ai-nlp-${projectName}_${projectType}"; if ($projectName =~ /include/ ) { $module_name = "viky.ai-nlp-include"; } while(<TPL>) { s/____MODULE_ID____/$projectId/g; s/____MODULE_NAME____/$module_name/g; s/____MAKEFILE____/makefile.$platform/g; s/____INCLUDES____/$includeString/g; s/____NUMBER_OF_CPUS____/$number_of_cpus/g; s/____SOURCESPATH____/$projectSourceDir/g; print TGT "$_"; } close(TPL); close(TGT); return(0); } sub parseMakefileDesc ($) { my ($makefileDesc) = @_; # Read config file unless(-f $makefileDesc) { # TODO: exception warn("File $makefileDesc doesn't exist"); $projectType = ""; $projectName = ""; @sourceList = (); return(-1); } # dtd check config OgCheckDTD( file($ENV{OG_TOOL_PATH}, "makefile"), $makefileDesc) or warn "invalid $makefileDesc"; # parse config my $doc = $parser->parsefile($makefileDesc); unless(length($doc) != 0) { warn("Empty makefile description"); $projectType = ""; $projectName = ""; @sourceList = (); return(-1); } my @r = $doc->xql("makefile/type"); $projectType = OgXmlGetNodeText($r[0]); @r = $doc->xql("makefile/project_name"); $projectName = OgXmlGetNodeText($r[0]); if ( $projectType eq "extern" ) { print "Skipping external project $projectName\n"; return(0); } $projectSourceDir = ""; my @fileList = $doc->xql("makefile/sources/file"); @sourceList = (); foreach my $src (@fileList) { push(@sourceList, OgXmlGetNodeText($src)); } @includeList = ( join("/", OgPathToList($ENV{OG_REPO_PATH}), "sources", "include"), join("/", OgPathToList($ENV{OG_REPO_PATH}), "sources", "include", "glib-2.0") ); # add specific platforms sources my $strOs = OgOsString($OS); @fileList = $doc->xql("makefile/platforms/platform[\@name='$strOs']/sources/file"); foreach my $src (@fileList) { push(@sourceList, OgXmlGetNodeText($src)); } my $ext = ""; if ($projectType eq "lib") { if ($OS == ogutil::OS_WINDOWS) { $ext = ".dll"; } elsif ($OS == ogutil::OS_LINUX) { $ext = ".so"; } } elsif ($projectType eq "prog") { if ($OS == ogutil::OS_WINDOWS) { $ext = ".exe"; } elsif ($OS == ogutil::OS_LINUX) { $ext = ""; } } my @out = $doc->xql("makefile/platforms/platform[\@name='$strOs']/option[\@name='NAME']"); if (scalar(@out) != 0) { my $outputFile = OgXmlGetNodeText($out[0]); $outputDebug = join("/", OgPathToList($ENV{OG_REPO_PATH}), "build", "debug", "bin", $outputFile . $ext); $outputRelease = join("/", OgPathToList($ENV{OG_REPO_PATH}), "build", "release", "bin", $outputFile . $ext); #FIXME: windows support } $doc->dispose; return(0); } sub buildIncludeString () { my $string = ""; foreach my $inc (@includeList) { $string .= " <entry kind=\"includePath\" name=\"$inc\"/>\n"; } return($string); }
25.935065
184
0.638057
ed89fa43f57450fd9f15bc860e737fd811854701
2,201
pm
Perl
GitPortable/App/Git/lib/perl5/5.8.8/TAP/Parser/Result/Plan.pm
garethflowers/git-portable
2dc793c7db2100afbd4dfad38dd9095e9619973d
[ "MIT" ]
12
2015-09-13T22:25:49.000Z
2020-07-15T09:16:00.000Z
GitPortable/App/Git/lib/perl5/5.8.8/TAP/Parser/Result/Plan.pm
garethflowers/git-portable
2dc793c7db2100afbd4dfad38dd9095e9619973d
[ "MIT" ]
1
2018-04-24T15:30:47.000Z
2018-04-24T15:30:47.000Z
GitPortable/App/Git/lib/perl5/5.8.8/TAP/Parser/Result/Plan.pm
garethflowers/git-portable
2dc793c7db2100afbd4dfad38dd9095e9619973d
[ "MIT" ]
4
2016-03-17T11:55:36.000Z
2018-07-19T01:30:01.000Z
package TAP::Parser::Result::Plan; use strict; use vars qw($VERSION @ISA); use TAP::Parser::Result; @ISA = 'TAP::Parser::Result'; =head1 NAME TAP::Parser::Result::Plan - Plan result token. =head1 VERSION Version 3.23 =cut $VERSION = '3.23'; =head1 DESCRIPTION This is a subclass of L<TAP::Parser::Result>. A token of this class will be returned if a plan line is encountered. 1..1 ok 1 - woo hooo! C<1..1> is the plan. Gotta have a plan. =head1 OVERRIDDEN METHODS Mainly listed here to shut up the pitiful screams of the pod coverage tests. They keep me awake at night. =over 4 =item * C<as_string> =item * C<raw> =back =cut ############################################################################## =head2 Instance Methods =head3 C<plan> if ( $result->is_plan ) { print $result->plan; } This is merely a synonym for C<as_string>. =cut sub plan { '1..' . shift->{tests_planned} } ############################################################################## =head3 C<tests_planned> my $planned = $result->tests_planned; Returns the number of tests planned. For example, a plan of C<1..17> will cause this method to return '17'. =cut sub tests_planned { shift->{tests_planned} } ############################################################################## =head3 C<directive> my $directive = $plan->directive; If a SKIP directive is included with the plan, this method will return it. 1..0 # SKIP: why bother? =cut sub directive { shift->{directive} } ############################################################################## =head3 C<has_skip> if ( $result->has_skip ) { ... } Returns a boolean value indicating whether or not this test has a SKIP directive. =head3 C<explanation> my $explanation = $plan->explanation; If a SKIP directive was included with the plan, this method will return the explanation, if any. =cut sub explanation { shift->{explanation} } =head3 C<todo_list> my $todo = $result->todo_list; for ( @$todo ) { ... } =cut sub todo_list { shift->{todo_list} } 1;
18.190083
79
0.54657
edd3cb65c8f0a6b56f5c1fc7cfdd4000256cc5f6
457
pm
Perl
lib/SemanticWeb/Schema/BodyOfWater.pm
robrwo/LDF-JSON-LD
2745fa73562625ab217b7094a812bfc1f4be8cbc
[ "ClArtistic" ]
null
null
null
lib/SemanticWeb/Schema/BodyOfWater.pm
robrwo/LDF-JSON-LD
2745fa73562625ab217b7094a812bfc1f4be8cbc
[ "ClArtistic" ]
null
null
null
lib/SemanticWeb/Schema/BodyOfWater.pm
robrwo/LDF-JSON-LD
2745fa73562625ab217b7094a812bfc1f4be8cbc
[ "ClArtistic" ]
null
null
null
use utf8; package SemanticWeb::Schema::BodyOfWater; # ABSTRACT: A body of water use Moo; extends qw/ SemanticWeb::Schema::Landform /; use MooX::JSON_LD 'BodyOfWater'; use Ref::Util qw/ is_plain_hashref /; # RECOMMEND PREREQ: Ref::Util::XS use namespace::autoclean; our $VERSION = 'v14.0.1'; =encoding utf8 =head1 DESCRIPTION A body of water, such as a sea, ocean, or lake. =cut =head1 SEE ALSO L<SemanticWeb::Schema::Landform> =cut 1;
11.146341
47
0.702407
ede1c7b034bb9fdef56136d400c53b0b788cf26d
5,573
pm
Perl
t/lib/Neo4j_Test/Sim.pm
johannessen/neo4j-driver-perl
c0902a7dd196c92d5bbf289f0e520c5fc3c9233d
[ "Artistic-2.0" ]
5
2018-04-26T01:42:37.000Z
2021-08-31T12:12:39.000Z
t/lib/Neo4j_Test/Sim.pm
johannessen/neo4j-driver-perl
c0902a7dd196c92d5bbf289f0e520c5fc3c9233d
[ "Artistic-2.0" ]
13
2018-11-28T15:07:37.000Z
2022-01-25T13:10:39.000Z
t/lib/Neo4j_Test/Sim.pm
johannessen/neo4j-driver-perl
c0902a7dd196c92d5bbf289f0e520c5fc3c9233d
[ "Artistic-2.0" ]
1
2018-11-28T11:57:22.000Z
2018-11-28T11:57:22.000Z
package Neo4j_Test::Sim; use strict; use warnings; use Carp qw(croak); use JSON::PP qw(decode_json); use Digest::MD5; use File::Basename qw(dirname); use File::Slurp; use URI; use Neo4j_Test; my $path = (dirname dirname dirname __FILE__) . "/simulator"; my $hash_url = 0; # not 100% sure if 0 produces correct results, but it might increase maintainability ... and it _looks_ okay! sub new { my ($class, $options) = @_; $options->{cypher_params_v2} = 1; # sim uses old param syntax return $class if ref $class; # if the net_module is an object, it'll a pre-configured Neo4j_Test::Sim my $self = bless { auth => $options->{auth} // 1, }, $class; return $self; } sub result_handlers {} sub request { my ($self, $method, $url, $content) = @_; $content = $self->json_coder->encode($content) if $content; $url = "$url"; return $self->not_authenticated() unless $self->{auth}; if ($method eq 'DELETE') { $self->{status} = 204; # HTTP: No Content return $self; } return $self->GET($url) if $method eq 'GET'; return $self->not_implemented($method, $url) unless $method eq 'POST'; return $self->not_found($url) if $url !~ m(^/db/(?:data|neo4j|system)/(?:transaction|tx)\b); my $hash = request_hash($url, $content); my $file = "$path/$hash.json"; if (! -f $file || ! -r $file) { return $self->not_implemented($method, $url, $file); } $self->{json} = File::Slurp::read_file $file; $self->{status} = 201; # HTTP: Created # always use 201 so that the Location header is picked up by the Transaction } sub GET { my ($self, $url, $headers) = @_; if ($url ne '/') { return $self->not_implemented('GET', $url); } my $neo4j_version = '"neo4j_version":"0.0.0"'; my $transaction = '"transaction":"/db/data/transaction"'; $self->{json} = "{$neo4j_version,$transaction}"; $self->{status} = 200; # HTTP: OK } sub not_found { my ($self, $url) = @_; $self->{json} = "{\"error\":\"$url not found in Neo4j simulator.\"}"; $self->{status} = 404; # HTTP: Not Found } sub not_authenticated { my ($self, $method, $url, $file) = @_; $self->{json} = "{\"error\":\"Neo4j simulator unauthenticated.\"}"; $self->{status} = 401; # HTTP: Unauthorized } sub not_implemented { my ($self, $method, $url, $file) = @_; $self->{json} = "{\"error\":\"$method to $url not implemented in Neo4j simulator.\"}"; $self->{json} = "{\"error\":\"Query not implemented (file '$file' not found).\"}" if $file; $self->{status} = 501; # HTTP: Not Implemented } sub fetch_all { my ($self) = @_; return $self->{json}; } sub http_header { my ($self) = @_; my $loc = ''; eval { $loc = decode_json($self->{json})->{commit} // '' }; $loc =~ s|/commit$||; return { content_type => 'application/json', location => $loc, status => $self->{status}, success => scalar $self->{status} =~ m/^2/, }; } sub date_header { return ''; } sub uri { return "http://" . Neo4j_Test->server_address; } sub store { my (undef, $url, $request, $response, $write_txt) = @_; return if $Neo4j_Test::sim; # don't overwrite the files while we're reading from them $request = json_coder()->encode($request); my $hash = request_hash("$url", $request); $response //= ''; $response =~ s/{"expires":"[A-Za-z0-9 :,+-]+"}/{"expires":"Tue, 01 Jan 2999 00:00:00 +0000"}/; File::Slurp::write_file "$path/$hash.txt", "$url\n\n\n$request" if $write_txt; # useful for debugging File::Slurp::write_file "$path/$hash.json", $response; } sub request_hash ($$) { my ($url, $content) = @_; return Digest::MD5::md5_hex $url . ($content // '') if $hash_url; return Digest::MD5::md5_hex $content // ''; } sub json_coder { return shift->{json_coder} //= json_coder() if @_; return JSON::PP->new->utf8->pretty->sort_by(sub { return -1 if $JSON::PP::a eq 'statements'; return 1 if $JSON::PP::b eq 'statements'; return $JSON::PP::a cmp $JSON::PP::b; }); } sub http_reason { my $status = shift->{status}; return "Bad Request" if $status == 400; return "Unauthorized" if $status == 401; return "Not Found" if $status == 404; return "Not Implemented"; } sub protocol { return "Neo4j_Test::Sim"; } package Neo4j_Test::Sim::Store; use parent 'Neo4j::Driver::Net::HTTP::LWP'; sub new { my ($class, $driver) = @_; $driver->{jolt} = 0; # sim currently only supports JSON $driver->{cypher_params_v2} = 1; # sim uses old param syntax return $class->SUPER::new($driver); } sub request { my ($self, $method, $url, $json, $accept) = @_; $self->SUPER::request($method, $url, $json, $accept); Neo4j_Test::Sim->store($url, $json, $self->fetch_all, 0) if $method eq 'POST'; } 1; __END__ This module implements enough parts of the net_module interface that it can be used to simulate an active transactional HTTP connection to a Neo4j server. To do so, it replays canned copies of earlier real responses from a live Neo4j server that have been stored in a repository. To populate the repository of canned responses used by the simulator, run the following command once against a live Neo4j 4 server: TEST_NEO4J_NETMODULE=Neo4j_Test::Sim::Store prove The simulator operates most efficiently when repeated identical queries are reused for multiple _autocommit_ transactions. The tests should be tailored accordingly. When writing tests, care must be taken to not repeat identical queries on _explicit_ transactions. While some of these cases are handled by the simulator when the $hash_url option is turned on, frequently the wrong response is returned by mistake, which leads to test failures being reported that can be difficult to debug.
27.318627
128
0.660147
ed9f7ff9eee215ae7646825e7b6c3dfe340009d9
843
pl
Perl
bin/compileemptyclass.pl
dlgroupuoft/PScout
b7ca635892a6717f5bdc7106e67af9ed08bec05e
[ "MIT" ]
12
2018-08-16T02:03:01.000Z
2022-03-26T12:00:24.000Z
lib/PScout/bin/compileemptyclass.pl
USC-NSL/SIF
570135075c9e24dbda42e596773bf0430b679fba
[ "Apache-2.0" ]
1
2018-07-04T15:50:12.000Z
2020-07-15T11:36:01.000Z
bin/compileemptyclass.pl
dlgroupuoft/PScout
b7ca635892a6717f5bdc7106e67af9ed08bec05e
[ "MIT" ]
5
2019-01-07T14:41:22.000Z
2021-06-28T23:41:33.000Z
#!/usr/bin/perl #$missingclass = "com.android.internal.telephony.gsm.GSMPhone\$1"; $missingclass = $ARGV[0]; if ($#ARGV != 0) { print "Usage: compileemptyclass.pl <package.class>\n"; exit(0); } $missingclass =~ m/(.*)\.([^.]*)$/; $pkg = $1; $class = $2; open FILE, ">$class.java" or die $!; print FILE "package $pkg;\n"; print FILE "public class $class {\n"; print FILE "public static void main(String[] args) {\n"; print FILE "}\n"; print FILE "}\n"; close FILE; system("javac '$class.java'"); $pkg =~ s/\./\//g; if (-e "./$pkg/$class.class") { print "Replace existing $class.class? <Y/N> "; $decision = <stdin>; if ($decision eq "Y\n" || $decision eq "y\n") { system("mv '$class.class' ./$pkg/"); } else { system("rm -f '$class.class'"); } } else { system("mv '$class.class' ./$pkg/"); } system("rm -f '$class.java'");
21.075
66
0.582444
edec53cd31660bb5673e7148e09b57bdb514c1e1
9,352
pm
Perl
lib/Convos/Plugin/Cms.pm
Huijaaja42/convos
f4be68508490bff5c356a43e6a000d22f1f2ee3c
[ "Artistic-2.0" ]
null
null
null
lib/Convos/Plugin/Cms.pm
Huijaaja42/convos
f4be68508490bff5c356a43e6a000d22f1f2ee3c
[ "Artistic-2.0" ]
null
null
null
lib/Convos/Plugin/Cms.pm
Huijaaja42/convos
f4be68508490bff5c356a43e6a000d22f1f2ee3c
[ "Artistic-2.0" ]
null
null
null
package Convos::Plugin::Cms; use Mojo::Base 'Convos::Plugin', -async_await; use Convos::Date 'dt'; use Mojo::ByteStream; use Mojo::Cache; use Mojo::Collection; use Mojo::DOM; use Mojo::URL; use Mojo::Util qw(decode slugify trim); use Pod::Simple::Search; use Pod::Simple::XHTML; use Scalar::Util 'blessed'; use Text::Markdown::Hoedown; $ENV{CONVOS_CMS_SCAN_INTERVAL} ||= 15; has _cache => sub { Mojo::Cache->new(max_keys => 20) }; sub register { my ($self, $app, $config) = @_; $app->defaults('cms.blogs' => Mojo::Collection->new); $app->config( 'cms.paths' => [$app->core->home->child('content'), $app->asset->engine->assets_dir]); unshift @{$app->static->paths}, $app->core->home->child(qw(content public))->to_string; unshift @{$app->renderer->paths}, $app->core->home->child(qw(content templates))->to_string; $app->helper('cms.blogs_p' => sub { $self->_blogs_p(@_) }); $app->helper('cms.document_p' => sub { $self->_document_p(@_) }); $app->helper('cms.perldoc' => sub { $self->_perldoc(@_) }); $app->helper('cms.scan_for_blogs_p' => sub { $self->_scan_for_blogs_p(shift->app) }); Mojo::IOLoop->recurring($ENV{CONVOS_CMS_SCAN_INTERVAL} => sub { $app->cms->scan_for_blogs_p }); } sub _blogs_p { my ($self, $c, $params) = @_; my $blogs = $c->stash('cms.blogs'); return @$blogs ? Mojo::Promise->resolve($blogs) : $self->_scan_for_blogs_p($c->app); } sub _document_p { my ($self, $c, $path) = @_; # Normalize input $path = [@$path]; my $format = $path->[-1] =~ s!\.(html|txt|yaml)$!! ? $1 : 'html'; $path->[-1] .= '.md'; my $file; for my $dir (@{$c->app->config('cms.paths')}) { $file = $dir->child(@$path); last if -r $file; } my $p = Mojo::Promise->new; eval { $p->resolve({}) unless -r $file; $p->resolve({body => $file->slurp, format => $format}) if $format eq 'txt'; my $doc = $self->_get_cached_document($file) || $self->_parse_document($file, {}); $doc->{format} = $format; $self->_rewrite_href($c, $doc) if $format eq 'html'; $p->resolve($doc); } or do { $p->reject($@); }; return $p; } sub _extract_excerpt { my ($self, $dom, $doc) = @_; my $p = $dom->at('p:is(:root)') or return; $doc->{excerpt} = $p->all_text; $doc->{meta}{description} ||= length($doc->{excerpt}) > 150 ? substr($doc->{excerpt}, 0, 160) . '...' : $doc->{excerpt}; $doc->{meta}{description} =~ s!\r?\n! !g; } sub _extract_heading { my ($self, $dom, $doc) = @_; my $h1 = $dom->at('h1:is(:root)') or return; $doc->{meta}{heading} = trim $h1->all_text; $doc->{meta}{title} ||= trim $h1->all_text; $h1->remove; } sub _get_cached_document { my ($self, $file) = @_; return undef if $ENV{CONVOS_CMS_NO_CACHE}; my $doc = $self->_cache->get("$file"); my $mtime = $file->stat->mtime; return $doc if $doc and $doc->{mtime} == $mtime; } sub _markdown { state $extensions = HOEDOWN_EXT_AUTOLINK | HOEDOWN_EXT_MATH | HOEDOWN_EXT_SUPERSCRIPT | HOEDOWN_EXT_SPACE_HEADERS | HOEDOWN_EXT_TABLES; return markdown($_[0], extensions => $extensions); } sub _parse_document { my ($self, $file, $params) = @_; my $doc = { after_content => '', before_content => '', custom_css => '', excerpt => '', meta => {}, mtime => $file->stat->mtime, }; my ($body, $FH) = ('', $file->open); while (readline $FH) { $_ = decode 'UTF-8', $_; $body .= $_ and last if $. == 1 and !/^---/; # meta header has to start with "---" last if $. > 1 and /^---/; # meta header stops with "----" $doc->{meta}{$1} = $2 if /^\s*(\w+)\s*:\s*(.+)/; } $body .= $_ while readline $FH; $body = Mojo::DOM->new(decode 'UTF-8', $body); $self->_parse_markdown($body, $doc); $self->_rewrite_document($body, $doc) unless $params->{scan}; $self->_extract_excerpt($body, $doc); $self->_extract_heading($body, $doc); my $dt = dt $file->basename =~ m!(\d{4}-\d{2}-\d{2})! ? "${1}T00:00:00" : $doc->{mtime}; $doc->{ts} = $dt->epoch; $doc->{meta}{name} = $file->basename; $doc->{meta}{name} =~ s!^\d{4}-\d{2}-\d{2}-!!; $doc->{meta}{name} =~ s!\.md$!!; $doc->{meta}{$_} ||= $dt->$_ for qw(mday mon year); $doc->{meta}{date} ||= sprintf '%s. %s, %s', $dt->mday, $dt->month, $dt->year; $doc->{meta}{title} ||= $file->basename; $doc->{path} = "$file"; $self->_cache->set("$file" => $doc); return $doc; } sub _parse_markdown { my ($self, $dom) = @_; $dom->find('[markdown]')->each(sub { my $tag = shift; my $markdown = $tag->content; my $indent = $markdown =~ s!^([ ]+)!!m ? $1 : ''; $markdown =~ s!^$indent!!mg; $tag->content(_markdown($markdown)); }); $dom->child_nodes->each(sub { my $tag = shift; $tag->replace(_markdown($tag->content)) if $tag->type eq 'text' or $tag->type eq 'raw'; }); $dom->find('p:empty')->each('remove'); } sub _perldoc { my ($self, $c, $pod) = @_; my $dom = Mojo::DOM->new(_perldoc_to_html($pod)); my $doc = {body => $dom, meta => {}}; my $base_url = $c->url_for('/doc/'); $_->{href} =~ s!^https://metacpan\.org/pod/!$base_url! and $_->{href} =~ s!::!/!gi for $dom->find('a[href]')->map('attr')->each; my @toc; $dom->find('h1, h2, h3')->each(sub { my $tag = shift; $tag->{id} = slugify(trim $tag->all_text); if ($tag->{id} eq 'name' and $tag->next and $tag->next->tag eq 'p') { my $next = $tag->next; $next->tag('h1'); $tag->remove; } else { $tag->tag('h' . ($1 + 1)) if $tag->tag =~ m!(\d+)!; push @toc, [trim($tag->all_text), $tag->{id}, []] if $tag->tag eq 'h2'; push @{$toc[-1][2]}, [trim($tag->all_text), $tag->{id}, []] if @toc and $tag->tag eq 'h3'; } }); for my $e ($dom->find('pre > code')->each) { next if (my $str = $e->content) =~ /^\s*(?:\$|Usage:)\s+/m; next unless $str =~ /[\$\@\%]\w|-&gt;\w|^use\s+\w/m; my $attrs = $e->attr; my $class = $attrs->{class}; } $dom->find('p:empty')->each('remove'); $self->_extract_excerpt($dom, $doc); $self->_extract_heading($dom, $doc); $doc->{toc} = \@toc; return $doc; } # Heavily inspired by Mojolicious::Plugin::MojoDocs sub _perldoc_to_html { my ($pod) = @_; my $parser = Pod::Simple::XHTML->new; $parser->perldoc_url_prefix('https://metacpan.org/pod/'); $parser->$_('') for qw(html_header html_footer); $parser->anchor_items(1); $parser->strip_verbatim_indent(sub { (sort map {/^(\s+)/} @{shift()})[0]; }); $parser->output_string(\(my $output)); return $@ unless eval { $parser->parse_string_document("$pod"); 1 }; return $output; } sub _rewrite_href { my ($self, $c, $md) = @_; for my $section (grep { $md->{$_} } qw(after_content before_content body)) { next unless $md->{$section}; $md->{$section}->find('a[href^="/"]')->each(sub { $_[0]->{href} = $c->url_for($_[0]->{href}) }); $md->{$section}->find('img[src^="/"]')->each(sub { $_[0]->{src} = $c->url_for($_[0]->{src}) }); } } sub _rewrite_document { my ($self, $dom, $doc) = @_; my @toc; $dom->find('h1, h2, h3')->each(sub { my $tag = shift; $tag->{id} = slugify(trim $tag->all_text); return if $tag->tag eq 'h1'; push @toc, [trim($tag->all_text), $tag->{id}, []] if $tag->tag eq 'h2'; push @{$toc[-1][2]}, [trim($tag->all_text), $tag->{id}, []] if @toc and $tag->tag eq 'h3'; }); $dom->find('img[alt="fas"], img[alt="fab"]')->each(sub { my $tag = shift; $tag->tag('i'); $tag->{class} = join ' ', delete $tag->{alt}, 'fa-' . delete $tag->{src}; }); $dom->find('pre')->each(sub { my $tag = shift; my $pre_text = $tag->all_text; $pre_text =~ s![\r\n]+$!!s; $tag->content($pre_text); }); $dom->find('style:not(.inline)')->each(sub { my $tag = shift; $doc->{custom_css} .= $tag->all_text . "\n"; $tag->remove; }); $dom->find('.is-after-content, .is-before-content')->each(sub { my $tag = shift; my $key = $tag->attr('class') =~ /is-after/ ? 'after_content' : 'before_content'; $doc->{$key} .= "$tag"; $tag->remove; }); $doc->{custom_css} =~ s!</?\w+>!!g; # Remove <p> tags inside <style> $doc->{body} = $dom; $doc->{after_content} = $doc->{after_content} ? Mojo::DOM->new($doc->{after_content}) : undef; $doc->{before_content} = $doc->{before_content} ? Mojo::DOM->new($doc->{before_content}) : undef; $doc->{toc} = \@toc; } async sub _scan_for_blogs_p { my ($self, $app) = @_; my $blogs = await Mojo::IOLoop->subprocess->run_p(sub { my @blogs; for my $year ($app->core->home->child(qw(content blog))->list({dir => 1})->each) { return unless $year->basename =~ m!^(\d{4})$!; push @blogs, $year->list->map(sub { $self->_parse_document(shift, {scan => 1}) })->each; } return [sort { $b->{ts} <=> $a->{ts} } @blogs]; }); $blogs = Mojo::Collection->new(@$blogs); $app->defaults('cms.blogs' => $blogs); return $blogs; } 1; =encoding utf8 =head1 NAME Convos::Plugin::Cms - Plugin for rendering custom content =head1 DESCRIPTION L<Convos::Plugin::Cms> is a L<Convos::Plugin> for rendering custom content. =head1 METHODS =head2 register $cms->register($app, \%config); Used to register this plugin i L<Convos>. =head1 SEE ALSO L<Convos>. =cut
29.316614
100
0.55047
ed77743310a0d427c84bf68ae6e73dbad1a3b0b2
536
pm
Perl
lib/MetaCPAN/Document/Package/Set.pm
twins2020/metacpan-api
ed27c320b743993214dc8d3e76adfbb9cd4c334b
[ "Artistic-1.0" ]
113
2016-08-10T08:54:18.000Z
2022-03-20T01:39:53.000Z
lib/MetaCPAN/Document/Package/Set.pm
twins2020/metacpan-api
ed27c320b743993214dc8d3e76adfbb9cd4c334b
[ "Artistic-1.0" ]
347
2016-07-04T14:37:39.000Z
2022-03-20T12:57:12.000Z
lib/MetaCPAN/Document/Package/Set.pm
twins2020/metacpan-api
ed27c320b743993214dc8d3e76adfbb9cd4c334b
[ "Artistic-1.0" ]
110
2016-11-14T22:27:09.000Z
2022-03-20T06:41:33.000Z
package MetaCPAN::Document::Package::Set; use Moose; use MetaCPAN::Query::Package (); extends 'ElasticSearchX::Model::Document::Set'; has query_package => ( is => 'ro', isa => 'MetaCPAN::Query::Package', lazy => 1, builder => '_build_query_package', handles => [qw< get_modules >], ); sub _build_query_package { my $self = shift; return MetaCPAN::Query::Package->new( es => $self->es, index_name => $self->index->name, ); } __PACKAGE__->meta->make_immutable; 1;
19.851852
47
0.597015
edaf048cdf0345c9fc0d11d1abffaae296dda9a4
8,795
pm
Perl
apps/tomcat/web/mode/memory.pm
nribault/centreon-plugins
e99276ba80ba202392791e78d72b00f1306d1a99
[ "Apache-2.0" ]
null
null
null
apps/tomcat/web/mode/memory.pm
nribault/centreon-plugins
e99276ba80ba202392791e78d72b00f1306d1a99
[ "Apache-2.0" ]
null
null
null
apps/tomcat/web/mode/memory.pm
nribault/centreon-plugins
e99276ba80ba202392791e78d72b00f1306d1a99
[ "Apache-2.0" ]
null
null
null
# # Copyright 2020 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package apps::tomcat::web::mode::memory; use base qw(centreon::plugins::templates::counter); use strict; use warnings; use centreon::plugins::http; use XML::XPath; sub custom_memory_output { my ($self, %options) = @_; my $msg = sprintf("Memory Total: %s %s Used: %s %s (%.2f%%) Free: %s %s (%.2f%%)", $self->{perfdata}->change_bytes(value => $self->{result_values}->{total}), $self->{perfdata}->change_bytes(value => $self->{result_values}->{used}), $self->{result_values}->{prct_used}, $self->{perfdata}->change_bytes(value => $self->{result_values}->{free}), $self->{result_values}->{prct_free}); return $msg; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'global', type => 0, skipped_code => { -10 => 1 } }, ]; $self->{maps_counters}->{global} = [ { label => 'usage', nlabel => 'memory.usage.bytes', set => { key_values => [ { name => 'used' }, { name => 'free' }, { name => 'prct_used' }, { name => 'prct_free' }, { name => 'total' } ], closure_custom_output => $self->can('custom_memory_output'), perfdatas => [ { value => 'used', template => '%d', min => 0, max => 'total', unit => 'B', cast_int => 1 }, ], } }, { label => 'usage-free', display_ok => 0, nlabel => 'memory.free.bytes', set => { key_values => [ { name => 'free' }, { name => 'used' }, { name => 'prct_used' }, { name => 'prct_free' }, { name => 'total' } ], closure_custom_output => $self->can('custom_memory_output'), perfdatas => [ { value => 'free', template => '%d', min => 0, max => 'total', unit => 'B', cast_int => 1 }, ], } }, { label => 'usage-prct', display_ok => 0, nlabel => 'memory.usage.percentage', set => { key_values => [ { name => 'prct_used' } ], output_template => 'Memory Used : %.2f %%', perfdatas => [ { value => 'prct_used', template => '%.2f', min => 0, max => 100, unit => '%' }, ], } }, ]; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options, force_new_perfdata => 1); bless $self, $class; $options{options}->add_options(arguments => { 'hostname:s' => { name => 'hostname' }, 'port:s' => { name => 'port', default => '8080' }, 'proto:s' => { name => 'proto' }, 'credentials' => { name => 'credentials' }, 'basic' => { name => 'basic' }, 'username:s' => { name => 'username' }, 'password:s' => { name => 'password' }, 'timeout:s' => { name => 'timeout' }, 'urlpath:s' => { name => 'url_path', default => '/manager/status?XML=true' }, }); $self->{http} = centreon::plugins::http->new(%options); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); $self->{http}->set_options(%{$self->{option_results}}); } my %xpath_to_check = ( memMax => '/status/jvm/memory/@max', memFree => '/status/jvm/memory/@free', memTotal => '/status/jvm/memory/@total', ); sub manage_selection { my ($self, %options) = @_; my $webcontent = $self->{http}->request(); #EXAMPLE 1: #<status> # <connector name="http-0"> # <threadInfo currentThreadCount="0" currentThreadsBusy="0" maxThreads="200"/> # <requestInfo bytesReceived="0" bytesSent="0" errorCount="0" maxTime="0" processingTime="0" requestCount="0"/> # <workers></workers> # </connector> # <connector name="http-8080"> # <threadInfo currentThreadCount="158" currentThreadsBusy="10" maxThreads="200"/> # <requestInfo bytesReceived="297" bytesSent="19350704517" errorCount="192504" maxTime="249349" processingTime="2242513592" requestCount="983650"/> # <workers> # </workers> # </connector> #</status> #EXAMPLE 2: #<status> #<jvm> # <memory free='409303928' total='518979584' max='518979584'/> # <memorypool name='Eden Space' type='Heap memory' usageInit='143130624' usageCommitted='143130624' usageMax='143130624' usageUsed='56881560'/> # <memorypool name='Survivor Space' type='Heap memory' usageInit='17891328' usageCommitted='17891328' usageMax='17891328' usageUsed='17891328'/> # <memorypool name='Tenured Gen' type='Heap memory' usageInit='357957632' usageCommitted='357957632' usageMax='357957632' usageUsed='34902768'/> # <memorypool name='Code Cache' type='Non-heap memory' usageInit='2555904' usageCommitted='2555904' usageMax='50331648' usageUsed='1899840'/> # <memorypool name='Perm Gen' type='Non-heap memory' usageInit='21757952' usageCommitted='21757952' usageMax='85983232' usageUsed='21372688'/> #</jvm> #<connector name='"http-bio-10.1.80.149-22002"'><threadInfo maxThreads="5" currentThreadCount="2" currentThreadsBusy="1" /> # <requestInfo maxTime="1216" processingTime="1216" requestCount="1" errorCount="1" bytesReceived="0" bytesSent="2474" /> # <workers> # <worker stage="S" requestProcessingTime="23" requestBytesSent="0" requestBytesReceived="0" remoteAddr="10.1.80.149" virtualHost="examplehost" method="GET" currentUri="/manager/status" currentQueryString="XML=true" protocol="HTTP/1.1" /> # </workers> #</connector> #<connector name='"ajp-bio-10.1.80.149-22001"'><threadInfo maxThreads="150" currentThreadCount="0" currentThreadsBusy="0" /> # <requestInfo maxTime="0" processingTime="0" requestCount="0" errorCount="0" bytesReceived="0" bytesSent="0" /> # <workers> # </workers> #</connector> #</status> my $result = {}; my $xpath = XML::XPath->new(xml => $webcontent); foreach my $xpath_check (keys %xpath_to_check) { my $nodeset = $xpath->find($xpath_to_check{$xpath_check}); foreach my $node ($nodeset->get_nodelist()) { my $value = $node->string_value(); if ($value =~ /^"?([0-9.]+)"?$/) { $result->{$xpath_check} = $1; } }; }; if (!defined($result->{memTotal}) || !defined($result->{memFree})) { $self->{output}->add_option_msg(short_msg => "some informations missing."); $self->{output}->option_exit(); } my $total = $result->{memTotal}; $self->{global} = { total => $total, free => $result->{memFree}, used => $total - $result->{memFree}, prct_free => $result->{memFree} * 100 / $total, prct_used => ($result->{memTotal} - $result->{memFree}) * 100 / $total, }; }; 1; __END__ =head1 MODE Check Tomcat Application Servers Memory Usage =over 8 =item B<--hostname> IP Address or FQDN of the Tomcat Application Server =item B<--port> Port used by Tomcat =item B<--proto> Protocol used http or https =item B<--credentials> Specify this option if you access server-status page with authentication =item B<--username> Specify username for authentication (Mandatory if --credentials is specified) =item B<--password> Specify password for authentication (Mandatory if --credentials is specified) =item B<--basic> Specify this option if you access server-status page over basic authentication and don't want a '401 UNAUTHORIZED' error to be logged on your webserver. Specify this option if you access server-status page over hidden basic authentication or you'll get a '404 NOT FOUND' error. (Use with --credentials) =item B<--timeout> Threshold for HTTP timeout =item B<--urlpath> Path to the Tomcat Manager XML (Default: '/manager/status?XML=true') =item B<--warning-*> B<--critical-*> Thresholds. Can be: 'usage' (B), 'usage-free' (B), 'usage-prct' (%). =back =cut
36.342975
250
0.596475
eda10fb6187a7268e1fd1e02ab7cd2563765d82e
4,145
pl
Perl
crawl-board.pl
gugod/p5-ptt-crawler
ffdfd2749767d21dd2588e23f5c06810fbdbbf49
[ "CC0-1.0" ]
1
2015-09-20T07:06:02.000Z
2015-09-20T07:06:02.000Z
crawl-board.pl
gugod/p5-ptt-crawler
ffdfd2749767d21dd2588e23f5c06810fbdbbf49
[ "CC0-1.0" ]
null
null
null
crawl-board.pl
gugod/p5-ptt-crawler
ffdfd2749767d21dd2588e23f5c06810fbdbbf49
[ "CC0-1.0" ]
null
null
null
use v5.18; use File::Path qw(make_path); use Mojo::IOLoop; use Mojo::UserAgent; use Mojo::UserAgent::CookieJar; use constant PTT_URL => "https://www.ptt.cc"; sub ptt_get { my ($url, $cb) = @_; state $ua ||= Mojo::UserAgent->new( cookie_jar => Mojo::UserAgent::CookieJar->new, max_connections => 5, max_redirects => 2, ); if ($cb) { $ua->get( $url, sub { my ($ua, $tx) = @_; if (my $dom = $tx->res->dom->at("form[action='/ask/over18']")) { $tx = $ua->post( PTT_URL . '/ask/over18', form => { from => $dom->at("input[name='from']")->attr("value"), yes => "yes" }, $cb ); } else { $cb->($ua, $tx); } } ); return; } my $tx = $ua->get($url); if (my $dom = $tx->res->dom->at("form[action='/ask/over18']")) { $tx = $ua->post( PTT_URL . '/ask/over18', form => { from => $dom->at("input[name='from']")->attr("value"), yes => "yes" } ); } return $tx; } sub harvest_articles { my ($url_board_index, $board_name, $cb) = @_; my $tx = ptt_get($url_board_index); my @articles; $tx->res->dom->find("a[href*='/bbs/${board_name}/']")->each( sub { return unless (my $href = $_->attr("href")) =~ m{ / ( M \. [0-9]+ \. A \. [A-Z0-9]{3} ) \.html$}x; my $subject = $_->text; my $article_id = $1; my $article_url = PTT_URL . $href; push @articles, { subject => $subject, url => $article_url, id => $article_id }; } ); return \@articles; } sub harvest_board_indices { my ($url_board_index, $board_name) = @_; my $tx = ptt_get($url_board_index); my @boards; $tx->res->dom->find("a[href*='/bbs/${board_name}/index']")->each( sub { return unless (my $href = $_->attr("href")) =~ m{/bbs/${board_name}/index([0-9]+)\.html}x; push @boards, { page_number => $1, url => PTT_URL . $href }; } ); @boards = @boards[1,0] if $boards[0]{page_number} > $boards[1]{page_number}; push @boards, map { +{ page_number => $_, url => PTT_URL . "/bbs/${board_name}/index" . $_ . ".html" } } ( $boards[0]{page_number}+1 .. $boards[1]{page_number}-1 ); push @boards, { page_number => $boards[1]{page_number} + 1, url => $url_board_index }; return \@boards; } sub download_articles { my ($articles, $output_dir) = @_; my $delay = Mojo::IOLoop->delay(); my $c = 0; for (@$articles) { my $save_as = "${output_dir}/" . $_->{id} . ".html"; next if -f $save_as; $c++; my $end = $delay->begin; ptt_get( $_->{url}, sub { my ($ua, $tx) = @_; if ((my $res = $tx->res)->code eq '200') { $res->content->asset->move_to($save_as); say "[$$] ==> $save_as"; } $end->(); } ); if ($c > 4) { $delay->wait; $c = 0; } } $delay->wait; } sub main { my ($board_name, $output_dir) = @_; my $board_url = PTT_URL . "/bbs/${board_name}/index.html"; my $output_board_dir = "${output_dir}/${board_name}"; make_path($output_board_dir); my $board_indices = harvest_board_indices($board_url, $board_name); for (sort { $b->{page_number} <=> $a->{page_number} } @$board_indices) { say "# $_->{url}"; my $articles = harvest_articles($_->{url}, $board_name); download_articles( $articles, $output_board_dir ); } Mojo::IOLoop->start unless Mojo::IOLoop->is_running; } main(@ARGV);
27.450331
110
0.436429
ed41cfd33fcb29c24654f018e3f75814a91a791d
6,350
pm
Perl
lib/AsposeSlidesCloud/Object/ResourceBase.pm
rizwanniazigroupdocs/aspose-slides-cloud-perl
71ec0139d276aeacbce02fbd944208e30a38e269
[ "MIT" ]
null
null
null
lib/AsposeSlidesCloud/Object/ResourceBase.pm
rizwanniazigroupdocs/aspose-slides-cloud-perl
71ec0139d276aeacbce02fbd944208e30a38e269
[ "MIT" ]
null
null
null
lib/AsposeSlidesCloud/Object/ResourceBase.pm
rizwanniazigroupdocs/aspose-slides-cloud-perl
71ec0139d276aeacbce02fbd944208e30a38e269
[ "MIT" ]
1
2021-01-04T07:31:42.000Z
2021-01-04T07:31:42.000Z
=begin comment Copyright (c) 2019 Aspose Pty Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =end comment =cut package AsposeSlidesCloud::Object::ResourceBase; require 5.6.0; use strict; use warnings; use utf8; use JSON qw(decode_json); use Data::Dumper; use Module::Runtime qw(use_module); use Log::Any qw($log); use Date::Parse; use DateTime; use AsposeSlidesCloud::Object::ResourceUri; use base ("Class::Accessor", "Class::Data::Inheritable"); # #Base class for all Slide&#39;s DTO objects # # NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. # REF: https://github.com/swagger-api/swagger-codegen # =begin comment Copyright (c) 2019 Aspose Pty Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =end comment =cut # # NOTE: This class is auto generated by the swagger code generator program. # Do not edit the class manually. # Ref: https://github.com/swagger-api/swagger-codegen # __PACKAGE__->mk_classdata('attribute_map' => {}); __PACKAGE__->mk_classdata('swagger_types' => {}); __PACKAGE__->mk_classdata('method_documentation' => {}); __PACKAGE__->mk_classdata('class_documentation' => {}); # new object sub new { my ($class, %args) = @_; my $self = bless {}, $class; foreach my $attribute (keys %{$class->attribute_map}) { my $args_key = $class->attribute_map->{$attribute}; $self->$attribute( $args{ $args_key } ); } return $self; } # return perl hash sub to_hash { return decode_json(JSON->new->convert_blessed->encode( shift )); } # used by JSON for serialization sub TO_JSON { my $self = shift; my $_data = {}; foreach my $_key (keys %{$self->attribute_map}) { if (defined $self->{$_key}) { $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; } } return $_data; } # from Perl hashref sub from_hash { my ($self, $hash) = @_; # loop through attributes and use swagger_types to deserialize the data while ( my ($_key, $_type) = each %{$self->swagger_types} ) { my $_json_attribute = $self->attribute_map->{$_key}; if ($_type =~ /^array\[/i) { # array my $_subclass = substr($_type, 6, -1); my @_array = (); foreach my $_element (@{$hash->{$_json_attribute}}) { push @_array, $self->_deserialize($_subclass, $_element); } foreach my $_element (@{$hash->{$_json_attribute}}) { push @_array, $self->_deserialize(lcfirst($_subclass), $_element); } $self->{$_key} = \@_array; } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); } elsif (exists $hash->{lcfirst($_json_attribute)}) { #hash(model), primitive, datetime $self->{$_key} = $self->_deserialize($_type, $hash->{lcfirst($_json_attribute)}); } } return $self; } # deserialize non-array data sub _deserialize { my ($self, $type, $data) = @_; if ($type eq 'DateTime') { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { return $data; } else { # hash(model) my $_instance = eval "AsposeSlidesCloud::Object::$type->new()"; return $_instance->from_hash($data); } } __PACKAGE__->class_documentation({description => 'Base class for all Slide&#39;s DTO objects ', class => 'ResourceBase', required => [], # TODO } ); __PACKAGE__->method_documentation({ 'self_uri' => { datatype => 'ResourceUri', base_name => 'SelfUri', description => 'Gets or sets the link to this resource.', format => '', read_only => '', }, 'alternate_links' => { datatype => 'ARRAY[ResourceUri]', base_name => 'AlternateLinks', description => 'List of alternate links.', format => '', read_only => '', }, }); __PACKAGE__->swagger_types( { 'self_uri' => 'ResourceUri', 'alternate_links' => 'ARRAY[ResourceUri]' } ); __PACKAGE__->attribute_map( { 'self_uri' => 'SelfUri', 'alternate_links' => 'AlternateLinks' } ); __PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); 1;
32.233503
107
0.667717
edbc49ae8addd1afb0e12d38f0ad061397482b38
100,828
al
Perl
Apps/IN/INTaxBase/app/src/page/BankReceiptVoucher.page.al
Microsoft/ALAppExtensions
c49a3f05eef4bc88a38b5f4b888b96933ac01309
[ "MIT" ]
127
2018-04-17T18:03:03.000Z
2019-05-06T18:54:17.000Z
Apps/IN/INTaxBase/app/src/page/BankReceiptVoucher.page.al
Microsoft/ALAppExtensions
c49a3f05eef4bc88a38b5f4b888b96933ac01309
[ "MIT" ]
2,279
2018-09-12T12:01:49.000Z
2019-05-06T13:59:35.000Z
Apps/IN/INTaxBase/app/src/page/BankReceiptVoucher.page.al
Microsoft/ALAppExtensions
c49a3f05eef4bc88a38b5f4b888b96933ac01309
[ "MIT" ]
41
2018-05-17T11:19:52.000Z
2019-04-30T17:30:38.000Z
page 18553 "Bank Receipt Voucher" { ApplicationArea = Basic, Suite; AutoSplitKey = true; Caption = 'Bank Receipt Voucher'; DelayedInsert = true; PageType = Worksheet; PromotedActionCategories = 'New,Process,Report,Bank,Application,Payroll,Approve,Page,Post/Print,Line,Account'; SaveValues = true; SourceTable = "Gen. Journal Line"; UsageCategory = Tasks; layout { area(content) { group(Control120) { ShowCaption = false; field("Current Jnl Batch Name"; CurrentJnlBatchName) { ApplicationArea = Basic, Suite; Caption = 'Batch Name'; Lookup = true; ToolTip = 'Specifies the name of the journal batch.'; trigger OnLookup(var Text: Text): Boolean begin CurrPage.SaveRecord(); GenJnlManagement.LookupName(CurrentJnlBatchName, Rec); SetControlAppearanceFromBatch(); SetDataForSimpleModeOnBatchChange(); CurrPage.Update(false); end; trigger OnValidate() begin GenJnlManagement.CheckName(CurrentJnlBatchName, Rec); CurrentJnlBatchNameOnAfterVali(); SetDataForSimpleModeOnBatchChange(); end; } field("<Document No. Simple Page>"; CurrentDocNo) { ApplicationArea = Basic, Suite; Caption = 'Document No.'; ToolTip = 'Specifies a document number for the journal line.'; Visible = IsSimplePage; trigger OnValidate() begin if not IsSimplePage then exit; if CurrentDocNo = '' then CurrentDocNo := "Document No."; if CurrentDocNo = "Document No." then exit; if Count() = 0 then "Document No." := CurrentDocNo; IsChangingDocNo := true; SetDocumentNumberFilter(CurrentDocNo); CurrPage.Update(false); end; } field("<CurrentPostingDate>"; CurrentPostingDate) { ApplicationArea = Basic, Suite; Caption = 'Posting Date'; ClosingDates = true; ToolTip = 'Specifies the entry''s posting date.'; Visible = IsSimplePage; trigger OnValidate() begin UpdateCurrencyFactor(FieldNo("Posting Date")); end; } field("<CurrentCurrencyCode>"; CurrentCurrencyCode) { ApplicationArea = Basic, Suite; Caption = 'Currency Code'; TableRelation = Currency.Code; ToolTip = 'Specifies the code of the currency for the amounts on the journal line.'; Visible = IsSimplePage; trigger OnValidate() begin VoucherFunctions.CheckCurrencyCode(CurrentCurrencyCode); UpdateCurrencyFactor(FieldNo("Currency Code")); end; } } repeater(Control1) { ShowCaption = false; field("Posting Date"; Rec."Posting Date") { ApplicationArea = Basic, Suite; StyleExpr = StyleTxt; ToolTip = 'Specifies the entry''s posting date.'; Visible = not IsSimplePage; } field("Document Date"; Rec."Document Date") { ApplicationArea = Basic, Suite; StyleExpr = StyleTxt; ToolTip = 'Specifies the date on the document that provides the basis for the entry on the journal line.'; Visible = false; } field("Document Type"; Rec."Document Type") { ApplicationArea = Basic, Suite; StyleExpr = StyleTxt; ToolTip = 'Specifies the type of document that the entry on the journal line is.'; Visible = not IsSimplePage; } field("Check Printed"; Rec."Check Printed") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies if cheque is printed for the journal entry.'; } field("Document No."; Rec."Document No.") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies a document number for the journal line.'; Visible = not IsSimplePage; } field("Incoming Document Entry No."; Rec."Incoming Document Entry No.") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the number of the incoming document that this Bank Receipt Voucher line is created for.'; Visible = false; trigger OnAssistEdit() begin if "Incoming Document Entry No." > 0 then Hyperlink(GetIncomingDocumentURL()); end; } field("External Document No."; Rec."External Document No.") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies a document number that refers to the customer''s or vendor''s numbering system.'; Visible = false; } field("Applies-to Ext. Doc. No."; Rec."Applies-to Ext. Doc. No.") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the external document number that will be exported in the payment file.'; Visible = false; } field("Account Type"; Rec."Account Type") { ApplicationArea = Basic, Suite; StyleExpr = StyleTxt; ToolTip = 'Specifies the type of account that the entry on the journal line will be posted to.'; Visible = not IsSimplePage; trigger OnValidate() begin GenJnlManagement.GetAccounts(Rec, AccName, BalAccName); SetUserInteractions(); EnableApplyEntriesAction(); CurrPage.SaveRecord(); end; } field("Account No."; Rec."Account No.") { ApplicationArea = Basic, Suite; StyleExpr = StyleTxt; ToolTip = 'Specifies the account number that the entry on the journal line will be posted to.'; trigger OnValidate() begin GenJnlManagement.GetAccounts(Rec, AccName, BalAccName); ShowShortcutDimCode(ShortcutDimCode); SetUserInteractions(); if IsSimplePage then Validate("Currency Code", CurrentCurrencyCode); CurrPage.SaveRecord(); end; } field(AccountName; AccName) { ApplicationArea = Basic, Suite; Caption = 'Account Name'; Editable = false; ToolTip = 'Specifies the account name that the entry on the journal line will be posted to.'; } field(Description; Description) { ApplicationArea = Basic, Suite; StyleExpr = StyleTxt; ToolTip = 'Specifies a description of the entry.'; } field("Payer Information"; Rec."Payer Information") { ApplicationArea = Basic, Suite; StyleExpr = StyleTxt; ToolTip = 'Specifies payer information that is imported with the bank statement file.'; Visible = false; } field("Transaction Information"; Rec."Transaction Information") { ApplicationArea = Basic, Suite; StyleExpr = StyleTxt; ToolTip = 'Specifies transaction information that is imported with the bank statement file.'; Visible = false; } field("Business Unit Code"; Rec."Business Unit Code") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the code of the business unit that the entry derives from in a consolidated company.'; Visible = false; } field("Salespers./Purch. Code"; Rec."Salespers./Purch. Code") { ApplicationArea = Suite; ToolTip = 'Specifies the salesperson or purchaser who is linked to the journal line.'; Visible = false; } field("Campaign No."; Rec."Campaign No.") { ApplicationArea = RelationshipMgmt; ToolTip = 'Specifies the number of the campaign the journal line is linked to.'; Visible = false; } field("Currency Code"; Rec."Currency Code") { ApplicationArea = Suite; AssistEdit = true; ToolTip = 'Specifies the code of the currency for the amounts on the journal line.'; Visible = not IsSimplePage; trigger OnAssistEdit() var ChangeExchangeRate: Page "Change Exchange Rate"; begin ChangeExchangeRate.SetParameter("Currency Code", "Currency Factor", "Posting Date"); if ChangeExchangeRate.RunModal() = Action::OK then Validate("Currency Factor", ChangeExchangeRate.GetParameter()); Clear(ChangeExchangeRate); end; } field("EU 3-Party Trade"; Rec."EU 3-Party Trade") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies whether the entry was part of a 3-party trade. If it was, there is a check mark in the field.'; Visible = not IsSimplePage; } field("Gen. Posting Type"; Rec."Gen. Posting Type") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the general posting type that will be used when you post the entry on this journal line.'; Visible = not IsSimplePage; } field("Gen. Bus. Posting Group"; Rec."Gen. Bus. Posting Group") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the vendor''s or customer''s trade type to link transactions made for this business partner with the appropriate general ledger account according to the general posting setup.'; Visible = not IsSimplePage; } field("Gen. Prod. Posting Group"; Rec."Gen. Prod. Posting Group") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the item''s product type to link transactions made for this item with the appropriate general ledger account according to the general posting setup.'; Visible = not IsSimplePage; } field("VAT Bus. Posting Group"; Rec."VAT Bus. Posting Group") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the VAT business posting group code that will be used when you post the entry on the journal line.'; Visible = false; } field("VAT Prod. Posting Group"; Rec."VAT Prod. Posting Group") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the VAT product posting group. Links business transactions made for the item, resource, or G/L account with the general ledger, to account for VAT amounts resulting from trade with that record.'; Visible = false; } field(Quantity; Quantity) { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the quantity of items to be included on the journal line.'; Visible = false; } field(Amount; Amount) { ApplicationArea = Basic, Suite; StyleExpr = StyleTxt; ToolTip = 'Specifies the total amount (including VAT) that the journal line consists of.'; Visible = AmountVisible; } field("Amount (LCY)"; Rec."Amount (LCY)") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the total amount in local currency (including VAT) that the journal line consists of.'; Visible = AmountVisible; } field("Debit Amount"; Rec."Debit Amount") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the total amount (including VAT) that the journal line consists of, if it is a debit amount.'; Visible = DebitCreditVisible; } field("Credit Amount"; Rec."Credit Amount") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the total amount (including VAT) that the journal line consists of, if it is a credit amount.'; Visible = DebitCreditVisible; } field("VAT Amount"; Rec."VAT Amount") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the amount of VAT included in the total amount.'; Visible = false; } field("VAT Difference"; Rec."VAT Difference") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the difference between the calculate VAT amount and the VAT amount that you have entered manually.'; Visible = false; } field("Bal. VAT Amount"; Rec."Bal. VAT Amount") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the amount of Bal. VAT included in the total amount.'; Visible = false; } field("Bal. VAT Difference"; Rec."Bal. VAT Difference") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the difference between the calculate VAT amount and the VAT amount that you have entered manually.'; Visible = false; } field("Bal. Account Type"; Rec."Bal. Account Type") { ApplicationArea = Basic, Suite; StyleExpr = StyleTxt; ToolTip = 'Specifies the code for the balancing account type that should be used in this journal line.'; Visible = not IsSimplePage; trigger OnValidate() begin EnableApplyEntriesAction(); end; } field("Bal. Account No."; Rec."Bal. Account No.") { ApplicationArea = Basic, Suite; StyleExpr = StyleTxt; ToolTip = 'Specifies the number of the general ledger, customer, vendor, or bank account to which a balancing entry for the journal line will posted (for example, a cash account for cash purchases).'; Visible = not IsSimplePage; trigger OnValidate() begin GenJnlManagement.GetAccounts(Rec, AccName, BalAccName); ShowShortcutDimCode(ShortcutDimCode); end; } field("Bal. Gen. Posting Type"; Rec."Bal. Gen. Posting Type") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the general posting type associated with the balancing account that will be used when you post the entry on the journal line.'; Visible = not IsSimplePage; } field("Bal. Gen. Bus. Posting Group"; Rec."Bal. Gen. Bus. Posting Group") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the general business posting group code associated with the balancing account that will be used when you post the entry.'; Visible = not IsSimplePage; } field("Bal. Gen. Prod. Posting Group"; Rec."Bal. Gen. Prod. Posting Group") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the general product posting group code associated with the balancing account that will be used when you post the entry.'; Visible = not IsSimplePage; } field("Deferral Code"; Rec."Deferral Code") { ApplicationArea = Suite; ToolTip = 'Specifies the deferral template that governs how expenses or revenue are deferred to the different accounting periods when the expenses or revenue were incurred.'; Visible = not IsSimplePage; } field("Job Queue Status"; Rec."Job Queue Status") { ApplicationArea = Basic, Suite; Importance = Additional; ToolTip = 'Specifies the status of a job queue entry or task that handles the posting of Bank Receipt Vouchers.'; Visible = JobQueuesUsed; trigger OnDrillDown() var JobQueueEntry: Record "Job Queue Entry"; begin if "Job Queue Status" = "Job Queue Status"::" " then exit; JobQueueEntry.ShowStatusMsg("Job Queue Entry ID"); end; } field("Bal. VAT Bus. Posting Group"; Rec."Bal. VAT Bus. Posting Group") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the code of the VAT business posting group that will be used when you post the entry on the journal line.'; Visible = false; } field("Bal. VAT Prod. Posting Group"; Rec."Bal. VAT Prod. Posting Group") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the code of the VAT product posting group that will be used when you post the entry on the journal line.'; Visible = false; } field("Bill-to/Pay-to No."; Rec."Bill-to/Pay-to No.") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the number of the bill-to customer or pay-to vendor that the entry is linked to.'; Visible = false; } field("Ship-to/Order Address Code"; Rec."Ship-to/Order Address Code") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the address code of the ship-to customer or order-from vendor that the entry is linked to.'; Visible = false; } field("Payment Terms Code"; Rec."Payment Terms Code") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the code that represents the payments terms that apply to the entry on the journal line.'; Visible = false; } field("Applied Automatically"; Rec."Applied Automatically") { ApplicationArea = Basic, Suite; Editable = false; ToolTip = 'Specifies that the Bank Receipt Voucher line has been automatically applied with a matching payment using the Apply Automatically function.'; Visible = false; } field(Applied; IsApplied()) { ApplicationArea = Basic, Suite; Caption = 'Applied'; ToolTip = 'Specifies if the record on the line has been applied.'; Visible = false; } field("Applies-to Doc. Type"; Rec."Applies-to Doc. Type") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the type of the posted document that this document or journal line will be applied to when you post, for example to register payment.'; Visible = false; } field("Applies-to Doc. No."; Rec."Applies-to Doc. No.") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the number of the posted document that this document or journal line will be applied to when you post, for example to register payment.'; Visible = false; } field("Applies-to ID"; Rec."Applies-to ID") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the ID of entries that will be applied to when you choose the Apply Entries action.'; Visible = false; } field("On Hold"; Rec."On Hold") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies if the journal line has been invoiced, and you execute the payment suggestions batch job, or you create a finance charge memo or reminder.'; Visible = false; } field("Bank Payment Type"; Rec."Bank Payment Type") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the code for the payment type to be used for the entry on the payment journal line.'; Visible = false; } field("Reason Code"; Rec."Reason Code") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the reason code that has been entered on the journal lines.'; Visible = false; } field(Correction; Correction) { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the entry as a corrective entry. You can use the field if you need to post a corrective entry to an account.'; Visible = not IsSimplePage; } field(Comment; Comment) { ApplicationArea = Comments; ToolTip = 'Specifies a comment about the activity on the journal line. Note that the comment is not carried forward to posted entries.'; Visible = not IsSimplePage; } field("Direct Debit Mandate ID"; Rec."Direct Debit Mandate ID") { ApplicationArea = Basic, Suite; ToolTip = 'Specifies the identification of the direct-debit mandate that is being used on the journal lines to process a direct debit collection.'; Visible = false; } field("Shortcut Dimension 1 Code"; Rec."Shortcut Dimension 1 Code") { ApplicationArea = Dimensions; ToolTip = 'Specifies the code for Shortcut Dimension 1, which is one of two global dimension codes that you set up in the General Ledger Setup window.'; Visible = DimVisible1; } field("Shortcut Dimension 2 Code"; Rec."Shortcut Dimension 2 Code") { ApplicationArea = Dimensions; ToolTip = 'Specifies the code for Shortcut Dimension 2, which is one of two global dimension codes that you set up in the General Ledger Setup window.'; Visible = DimVisible2; } field(ShortcutDimCode3; ShortcutDimCode[3]) { ToolTip = 'Specifies the code for Shortcut Dimension 3, which is one of two global dimension codes that you set up in the General Ledger Setup window.'; ApplicationArea = Dimensions; CaptionClass = '1,2,3'; TableRelation = "Dimension Value".Code where("Global Dimension No." = const(3), "Dimension Value Type" = const(Standard), Blocked = const(false)); Visible = DimVisible3; trigger OnValidate() begin ValidateShortcutDimCode(3, ShortcutDimCode[3]); VoucherFunctions.OnAfterValidateShortcutDimCode(Rec, ShortcutDimCode, 3); end; } field(ShortcutDimCode4; ShortcutDimCode[4]) { ToolTip = 'Specifies the code for Shortcut Dimension 4, which is one of two global dimension codes that you set up in the General Ledger Setup window.'; ApplicationArea = Dimensions; CaptionClass = '1,2,4'; TableRelation = "Dimension Value".Code where("Global Dimension No." = const(4), "Dimension Value Type" = const(Standard), Blocked = const(false)); Visible = DimVisible4; trigger OnValidate() begin ValidateShortcutDimCode(4, ShortcutDimCode[4]); VoucherFunctions.OnAfterValidateShortcutDimCode(Rec, ShortcutDimCode, 4); end; } field(ShortcutDimCode5; ShortcutDimCode[5]) { ToolTip = 'Specifies the code for Shortcut Dimension 5, which is one of two global dimension codes that you set up in the General Ledger Setup window.'; ApplicationArea = Dimensions; CaptionClass = '1,2,5'; TableRelation = "Dimension Value".Code where("Global Dimension No." = const(5), "Dimension Value Type" = const(Standard), Blocked = const(false)); Visible = DimVisible5; trigger OnValidate() begin ValidateShortcutDimCode(5, ShortcutDimCode[5]); VoucherFunctions.OnAfterValidateShortcutDimCode(Rec, ShortcutDimCode, 5); end; } field(ShortcutDimCode6; ShortcutDimCode[6]) { ToolTip = 'Specifies the code for Shortcut Dimension 6, which is one of two global dimension codes that you set up in the General Ledger Setup window.'; ApplicationArea = Dimensions; CaptionClass = '1,2,6'; TableRelation = "Dimension Value".Code where("Global Dimension No." = const(6), "Dimension Value Type" = const(Standard), Blocked = const(false)); Visible = DimVisible6; trigger OnValidate() begin ValidateShortcutDimCode(6, ShortcutDimCode[6]); VoucherFunctions.OnAfterValidateShortcutDimCode(Rec, ShortcutDimCode, 6); end; } field(ShortcutDimCode7; ShortcutDimCode[7]) { ToolTip = 'Specifies the code for Shortcut Dimension 7, which is one of two global dimension codes that you set up in the General Ledger Setup window.'; ApplicationArea = Dimensions; CaptionClass = '1,2,7'; TableRelation = "Dimension Value".Code where("Global Dimension No." = const(7), "Dimension Value Type" = const(Standard), Blocked = const(false)); Visible = DimVisible7; trigger OnValidate() begin ValidateShortcutDimCode(7, ShortcutDimCode[7]); VoucherFunctions.OnAfterValidateShortcutDimCode(Rec, ShortcutDimCode, 7); end; } field(ShortcutDimCode8; ShortcutDimCode[8]) { ToolTip = 'Specifies the code for Shortcut Dimension 8, which is one of two global dimension codes that you set up in the General Ledger Setup window.'; ApplicationArea = Dimensions; CaptionClass = '1,2,8'; TableRelation = "Dimension Value".Code where("Global Dimension No." = const(8), "Dimension Value Type" = const(Standard), Blocked = const(false)); Visible = DimVisible8; trigger OnValidate() begin ValidateShortcutDimCode(8, ShortcutDimCode[8]); VoucherFunctions.OnAfterValidateShortcutDimCode(Rec, ShortcutDimCode, 8); end; } } group(Narration) { Caption = 'Voucher Narration'; field("Narration "; NarrationText) { ApplicationArea = Basic, Suite; ShowCaption = false; Editable = true; MultiLine = true; ToolTip = 'Specifies the Voucher Narration for the current document'; trigger OnValidate() begin Error('Voucher Narration should be entered from Process - >Voucher Narration tab.'); end; } } group(Control30) { ShowCaption = false; fixed(Control1901776101) { ShowCaption = false; group("Number of Lines") { Caption = 'Number of Lines'; field(NumberOfJournalRecords; Count()) { ApplicationArea = Basic, Suite; AutoFormatType = 1; ShowCaption = false; Editable = false; ToolTip = 'Specifies the number of lines in the current journal batch.'; } } group("Account Name") { Caption = 'Account Name'; field("Acc Name"; AccName) { ApplicationArea = Basic, Suite; Editable = false; ShowCaption = false; ToolTip = 'Specifies the name of the account.'; } } group("Bal. Account Name") { Caption = 'Bal. Account Name'; Visible = not IsSimplePage; field("Bal Acc Name"; BalAccName) { ApplicationArea = Basic, Suite; Caption = 'Bal. Account Name'; Editable = false; ToolTip = 'Specifies the name of the balancing account that has been entered on the journal line.'; } } group("Total Debit") { Caption = 'Total Debit'; Visible = IsSimplePage; field(DisplayTotalDebit; GetTotalDebitAmt()) { ApplicationArea = Basic, Suite; Caption = 'Total Debit'; Editable = false; ToolTip = 'Specifies the total debit amount in the Bank Receipt Voucher.'; } } group("Total Credit") { Caption = 'Total Credit'; Visible = IsSimplePage; field(DisplayTotalCredit; GetTotalCreditAmt()) { ApplicationArea = Basic, Suite; Caption = 'Total Credit'; Editable = false; ToolTip = 'Specifies the total credit amount in the Bank Receipt Voucher.'; } } group(Control1902759701) { Caption = 'Balance'; field("Balance."; Balance + "Balance (LCY)" - xRec."Balance (LCY)") { ApplicationArea = Basic, Suite; AutoFormatType = 1; Caption = 'Balance'; Editable = false; ToolTip = 'Specifies the balance that has accumulated in the Bank Receipt Voucher on the line where the cursor is.'; Visible = BalanceVisible; } } group("Total Balance") { Caption = 'Total Balance'; field("Total Balance."; TotalBalance + "Balance (LCY)" - xRec."Balance (LCY)") { ApplicationArea = Basic, Suite; AutoFormatType = 1; Caption = 'Total Balance'; Editable = false; ToolTip = 'Specifies the total balance in the Bank Receipt Voucher.'; Visible = TotalBalanceVisible; } } } } } area(factboxes) { part(TaxInformation; "Tax Information Factbox") { ApplicationArea = Basic, Suite; SubPageLink = "Table ID Filter" = const(81), "Template Name Filter" = field("Journal Template Name"), "Batch Name Filter" = field("Journal Batch Name"), "Line No. Filter" = field("Line No."); } part(Control1900919607; "Dimension Set Entries FactBox") { ApplicationArea = Basic, Suite; SubPageLink = "Dimension Set ID" = field("Dimension Set ID"); } part(IncomingDocAttachFactBox; "Incoming Doc. Attach. FactBox") { ApplicationArea = Basic, Suite; ShowFilter = false; } part(WorkflowStatusBatch; "Workflow Status FactBox") { ApplicationArea = Suite; Caption = 'Batch Workflows'; Editable = false; Enabled = false; ShowFilter = false; Visible = ShowWorkflowStatusOnBatch; } part(WorkflowStatusLine; "Workflow Status FactBox") { ApplicationArea = Suite; Caption = 'Line Workflows'; Editable = false; Enabled = false; ShowFilter = false; Visible = ShowWorkflowStatusOnLine; } systempart(Control1900383207; Links) { ApplicationArea = RecordLinks; Visible = false; } systempart(Control1905767507; Notes) { ApplicationArea = Notes; Visible = false; } } } actions { area(navigation) { group("&Line") { Caption = '&Line'; Image = Line; action(Dimensions) { PromotedOnly = true; AccessByPermission = TableData Dimension = R; ApplicationArea = Dimensions; Caption = 'Dimensions'; Image = Dimensions; Promoted = true; PromotedCategory = Category10; ShortCutKey = 'Alt+D'; ToolTip = 'View or edit dimensions, such as area, project, or department, that you can assign to sales and purchase documents to distribute costs and analyze transaction history.'; trigger OnAction() begin ShowDimensions(); CurrPage.SaveRecord(); end; } action("Line Narration") { ApplicationArea = Basic, Suite; Caption = 'Line Narration'; Image = LineDescription; Promoted = true; PromotedCategory = Process; ToolTip = 'Select this option to enter narration for a particular line.'; trigger OnAction() var GenNarration: Record "Gen. Journal Narration"; LineNarrationPage: Page "Line Narration"; begin GenNarration.Reset(); GenNarration.SetRange("Journal Template Name", "Journal Template Name"); GenNarration.SetRange("Journal Batch Name", "Journal Batch Name"); GenNarration.SetRange("Document No.", "Document No."); GenNarration.SetRange("Gen. Journal Line No.", "Line No."); LineNarrationPage.SetTableView(GenNarration); LineNarrationPage.RunModal(); // ShowOldNarration(); VoucherFunctions.ShowOldNarration(Rec); CurrPage.Update(true); end; } action("Voucher Narration") { ApplicationArea = Basic, Suite; Caption = 'Voucher Narration'; Image = LineDescription; Promoted = true; PromotedCategory = Process; ToolTip = 'Select this option to enter narration for the voucher.'; trigger OnAction() var GenNarration: Record "Gen. Journal Narration"; VoucherNarration: Page "Voucher Narration"; begin GenNarration.Reset(); GenNarration.SetRange("Journal Template Name", "Journal Template Name"); GenNarration.SetRange("Journal Batch Name", "Journal Batch Name"); GenNarration.SetRange("Document No.", "Document No."); GenNarration.SetFilter("Gen. Journal Line No.", '%1', 0); VoucherNarration.SetTableView(GenNarration); VoucherNarration.RunModal(); // ShowOldNarration(); VoucherFunctions.ShowOldNarration(Rec); CurrPage.Update(true); end; } } group("A&ccount") { Caption = 'A&ccount'; Image = ChartOfAccounts; action(Card) { PromotedOnly = true; ApplicationArea = Basic, Suite; Caption = 'Card'; Image = EditLines; Promoted = true; PromotedCategory = Category11; RunObject = Codeunit "Gen. Jnl.-Show Card"; ShortCutKey = 'Shift+F7'; ToolTip = 'View or change detailed information about the record on the document or journal line.'; } action("Ledger E&ntries") { ApplicationArea = Basic, Suite; Caption = 'Ledger E&ntries'; Image = GLRegisters; Promoted = true; PromotedCategory = Category11; RunObject = Codeunit "Gen. Jnl.-Show Entries"; ShortCutKey = 'Ctrl+F7'; ToolTip = 'View the history of transactions that have been posted for the selected record.'; } } action(Approvals) { PromotedOnly = true; AccessByPermission = TableData "Approval Entry" = R; ApplicationArea = Suite; Caption = 'Approvals'; Image = Approvals; Promoted = true; PromotedCategory = Category10; ToolTip = 'View a list of the records that are waiting to be approved. For example, you can see who requested the record to be approved, when it was sent, and when it is due to be approved.'; trigger OnAction() var GenJournalLine: Record "Gen. Journal Line"; ApprovalsMgmt: Codeunit "Approvals Mgmt."; begin GetCurrentlySelectedLines(GenJournalLine); ApprovalsMgmt.ShowJournalApprovalEntries(GenJournalLine); end; } } area(processing) { group("F&unctions") { Caption = 'F&unctions'; Image = "Action"; action("Renumber Document Numbers") { ApplicationArea = Basic, Suite; Caption = 'Renumber Document Numbers'; Image = EditLines; ToolTip = 'Resort the numbers in the Document No. column to avoid posting errors because the document numbers are not in sequence. Entry applications and line groupings are preserved.'; Visible = not IsSimplePage; trigger OnAction() begin RenumberDocumentNo() end; } action("Insert Conv. LCY Rndg. Lines") { ApplicationArea = Basic, Suite; Caption = 'Insert Conv. LCY Rndg. Lines'; Image = InsertCurrency; RunObject = Codeunit "Adjust Gen. Journal Balance"; ToolTip = 'Insert a rounding correction line in the journal. This rounding correction line will balance in LCY when amounts in the foreign currency also balance. You can then post the journal.'; } separator("-") { Caption = '-'; } action(GetStandardJournals) { ApplicationArea = Suite; Caption = '&Get Standard Journals'; Ellipsis = true; Image = GetStandardJournal; Promoted = true; PromotedCategory = Process; ToolTip = 'Select a standard Bank Receipt Voucher to be inserted.'; trigger OnAction() var StdGenJnl: Record "Standard General Journal"; begin StdGenJnl.FilterGroup := 2; StdGenJnl.SetRange("Journal Template Name", "Journal Template Name"); StdGenJnl.FilterGroup := 0; if Page.RunModal(Page::"Standard General Journals", StdGenJnl) = Action::LookupOK then begin if IsSimplePage then // If this page is opend in simple mode then use the current doc no. for every G/L lines that are created // from standard journal. StdGenJnl.CreateGenJnlFromStdJnlWithDocNo(StdGenJnl, CurrentJnlBatchName, CurrentDocNo, 0D) else StdGenJnl.CreateGenJnlFromStdJnl(StdGenJnl, CurrentJnlBatchName); Message(BankPaymentInsertedMsg, StdGenJnl.Code); end; CurrPage.Update(true); end; } action(SaveAsStandardJournal) { ApplicationArea = Suite; Caption = '&Save as Standard Journal'; Ellipsis = true; Image = SaveasStandardJournal; ToolTip = 'Define the journal lines that you want to use later as a standard journal before you post the journal.'; trigger OnAction() var GenJnlBatch: Record "Gen. Journal Batch"; GeneralJnlLines: Record "Gen. Journal Line"; StdGenJnl: Record "Standard General Journal"; SaveAsStdGenJnl: Report "Save as Standard Gen. Journal"; begin GeneralJnlLines.SetFilter("Journal Template Name", "Journal Template Name"); GeneralJnlLines.SetFilter("Journal Batch Name", CurrentJnlBatchName); CurrPage.SetSelectionFilter(GeneralJnlLines); GeneralJnlLines.CopyFilters(Rec); GenJnlBatch.Get("Journal Template Name", CurrentJnlBatchName); SaveAsStdGenJnl.Initialise(GeneralJnlLines, GenJnlBatch); SaveAsStdGenJnl.RunModal(); if not SaveAsStdGenJnl.GetStdGeneralJournal(StdGenJnl) then exit; Message(GeneralJournalCreatedMsg, StdGenJnl.Code); end; } action("Test Report") { ApplicationArea = Basic, Suite; Caption = 'Test Report'; Ellipsis = true; Image = TestReport; ToolTip = 'View a test report so that you can find and correct any errors before you perform the actual posting of the journal or document.'; trigger OnAction() var ReportPrint: Codeunit "Test Report-Print"; begin ReportPrint.PrintGenJnlLine(Rec); end; } action(Post) { ApplicationArea = Basic, Suite; Caption = 'P&ost'; Image = PostOrder; Promoted = true; PromotedCategory = Category9; PromotedIsBig = true; ShortCutKey = 'F9'; ToolTip = 'Finalize the document or journal by posting the amounts and quantities to the related accounts in your company books.'; trigger OnAction() begin Codeunit.Run(Codeunit::"Gen. Jnl.-Post", Rec); CurrentJnlBatchName := GetRangeMax("Journal Batch Name"); if IsSimplePage then if GeneralLedgerSetup."Post with Job Queue" then NewDocumentNo() else SetDataForSimpleModeOnPost(); SetJobQueueVisibility(); CurrPage.Update(false); end; } action(Preview) { ApplicationArea = Basic, Suite; Caption = 'Preview Posting'; Image = ViewPostedOrder; Promoted = true; PromotedCategory = Category9; ShortCutKey = 'Ctrl+Alt+F9'; ToolTip = 'Review the different types of entries that will be created when you post the document or journal.'; trigger OnAction() var GenJnlPost: Codeunit "Gen. Jnl.-Post"; begin GenJnlPost.Preview(Rec); end; } action(PostAndPrint) { ApplicationArea = Basic, Suite; Caption = 'Post and &Print'; Image = PostPrint; Promoted = true; PromotedCategory = Category9; PromotedIsBig = true; ShortCutKey = 'Shift+F9'; ToolTip = 'Finalize and prepare to print the document or journal. The values and quantities are posted to the related accounts. A report request window where you can specify what to include on the print-out.'; trigger OnAction() begin Codeunit.Run(Codeunit::"Gen. Jnl.-Post+Print", Rec); CurrentJnlBatchName := GetRangeMax("Journal Batch Name"); if GeneralLedgerSetup."Post & Print with Job Queue" then NewDocumentNo() else SetDataForSimpleModeOnPost(); SetJobQueueVisibility(); CurrPage.Update(false); end; } action("Remove From Job Queue") { ApplicationArea = Basic, Suite; Caption = 'Remove From Job Queue'; Image = RemoveLine; Promoted = true; PromotedCategory = Category9; PromotedIsBig = true; ToolTip = 'Remove the scheduled processing of this record from the job queue.'; Visible = JobQueueVisible; trigger OnAction() begin CancelBackgroundPosting(); SetJobQueueVisibility(); CurrPage.Update(false); end; } group(IncomingDocument) { Caption = 'Incoming Document'; Image = Documents; action(IncomingDocCard) { ApplicationArea = Basic, Suite; Caption = 'View Incoming Document'; Enabled = HasIncomingDocument; Image = ViewOrder; ToolTip = 'View any incoming document records and file attachments that exist for the entry or document.'; trigger OnAction() var IncomingDocument: Record "Incoming Document"; begin IncomingDocument.ShowCardFromEntryNo("Incoming Document Entry No."); end; } action(SelectIncomingDoc) { AccessByPermission = TableData "Incoming Document" = R; ApplicationArea = Basic, Suite; Caption = 'Select Incoming Document'; Image = SelectLineToApply; ToolTip = 'Select an incoming document record and file attachment that you want to link to the entry or document.'; trigger OnAction() var IncomingDocument: Record "Incoming Document"; begin Validate("Incoming Document Entry No.", IncomingDocument.SelectIncomingDocument("Incoming Document Entry No.", RecordId())); end; } action(IncomingDocAttachFile) { ApplicationArea = Basic, Suite; Caption = 'Create Incoming Document from File'; Ellipsis = true; Enabled = not HasIncomingDocument; Image = Attach; ToolTip = 'Create an incoming document record by selecting a file to attach, and then link the incoming document record to the entry or document.'; trigger OnAction() var IncomingDocumentAttachment: Record "Incoming Document Attachment"; begin IncomingDocumentAttachment.NewAttachmentFromGenJnlLine(Rec); end; } action(RemoveIncomingDoc) { ApplicationArea = Basic, Suite; Caption = 'Remove Incoming Document'; Enabled = HasIncomingDocument; Image = RemoveLine; ToolTip = 'Remove any incoming document records and file attachments.'; trigger OnAction() var IncomingDocument: Record "Incoming Document"; begin if IncomingDocument.Get("Incoming Document Entry No.") then IncomingDocument.RemoveLinkToRelatedRecord(); "Incoming Document Entry No." := 0; Modify(true); end; } } } group("B&ank") { Caption = 'B&ank'; action(ImportBankStatement) { ApplicationArea = Basic, Suite; Caption = 'Import Bank Statement'; Image = Import; Promoted = true; PromotedCategory = Category4; PromotedIsBig = true; ToolTip = 'Import electronic bank statements from your bank to populate with data about actual bank transactions.'; Visible = false; trigger OnAction() begin if FindLast() then; ImportBankStatement(); end; } action(ShowStatementLineDetails) { ApplicationArea = Basic, Suite; Caption = 'Bank Statement Details'; Image = ExternalDocument; Promoted = true; PromotedCategory = Category4; PromotedIsBig = true; RunObject = Page "Bank Statement Line Details"; RunPageLink = "Data Exch. No." = field("Data Exch. Entry No."), "Line No." = field("Data Exch. Line No."); ToolTip = 'View the content of the imported bank statement file, such as account number, posting date, and amounts.'; Visible = false; } action(Reconcile) { PromotedOnly = true; ApplicationArea = Basic, Suite; Caption = 'Reconcile'; Image = Reconcile; Promoted = true; PromotedCategory = Process; PromotedIsBig = true; ShortCutKey = 'Ctrl+F11'; ToolTip = 'View the balances on bank accounts that are marked for reconciliation, usually liquid accounts.'; trigger OnAction() var GLReconcile: Page Reconciliation; begin GLReconcile.SetGenJnlLine(Rec); GLReconcile.Run(); end; } } group(Application) { Caption = 'Application'; action("Apply Entries") { PromotedOnly = true; ApplicationArea = Basic, Suite; Caption = 'Apply Entries'; Ellipsis = true; Enabled = ApplyEntriesActionEnabled; Image = ApplyEntries; Promoted = true; PromotedCategory = Process; RunObject = Codeunit "Gen. Jnl.-Apply"; ShortCutKey = 'Shift+F11'; ToolTip = 'Apply the payment amount on a journal line to a sales or purchase document that was already posted for a customer or vendor. This updates the amount on the posted document, and the document can either be partially paid, or closed as paid or refunded.'; } action(Match) { ApplicationArea = Basic, Suite; Caption = 'Apply Automatically'; Image = MapAccounts; Promoted = true; PromotedCategory = Category5; PromotedIsBig = true; RunObject = Codeunit "Match General Journal Lines"; ToolTip = 'Apply payments to their related open entries based on data matches between bank transaction text and entry information.'; Visible = false; } action(AddMappingRule) { ApplicationArea = Basic, Suite; Caption = 'Map Text to Account'; Image = CheckRulesSyntax; Promoted = true; PromotedCategory = Category5; PromotedIsBig = true; ToolTip = 'Associate text on payments with debit, credit, and balancing accounts, so payments are posted to the accounts when you post payments. The payments are not applied to invoices or credit memos, and are suited for recurring cash receipts or expenses.'; Visible = false; trigger OnAction() var TextToAccMapping: Record "Text-to-Account Mapping"; begin TextToAccMapping.InsertRec(Rec); end; } } group("Request Approval") { Caption = 'Request Approval'; group(SendApprovalRequest) { Caption = 'Send Approval Request'; Image = SendApprovalRequest; action(SendApprovalRequestJournalBatch) { ApplicationArea = Basic, Suite; Caption = 'Journal Batch'; Enabled = not OpenApprovalEntriesOnBatchOrAnyJnlLineExist AND CanRequestFlowApprovalForBatchAndAllLines; Image = SendApprovalRequest; ToolTip = 'Send all journal lines for approval, also those that you may not see because of filters.'; trigger OnAction() var ApprovalsMgmt: Codeunit "Approvals Mgmt."; begin ApprovalsMgmt.TrySendJournalBatchApprovalRequest(Rec); SetControlAppearanceFromBatch(); SetControlAppearance(); end; } action(SendApprovalRequestJournalLine) { ApplicationArea = Basic, Suite; Caption = 'Selected Journal Lines'; Enabled = not OpenApprovalEntriesOnBatchOrCurrJnlLineExist AND CanRequestFlowApprovalForBatchAndCurrentLine; Image = SendApprovalRequest; ToolTip = 'Send selected journal lines for approval.'; trigger OnAction() var GenJournalLine: Record "Gen. Journal Line"; ApprovalsMgmt: Codeunit "Approvals Mgmt."; begin GetCurrentlySelectedLines(GenJournalLine); ApprovalsMgmt.TrySendJournalLineApprovalRequests(GenJournalLine); SetControlAppearanceFromBatch(); end; } } group(CancelApprovalRequest) { Caption = 'Cancel Approval Request'; Image = Cancel; action(CancelApprovalRequestJournalBatch) { ApplicationArea = Basic, Suite; Caption = 'Journal Batch'; Enabled = CanCancelApprovalForJnlBatch OR CanCancelFlowApprovalForBatch; Image = CancelApprovalRequest; ToolTip = 'Cancel sending all journal lines for approval, also those that you may not see because of filters.'; trigger OnAction() var ApprovalsMgmt: Codeunit "Approvals Mgmt."; begin ApprovalsMgmt.TryCancelJournalBatchApprovalRequest(Rec); SetControlAppearance(); SetControlAppearanceFromBatch(); end; } action(CancelApprovalRequestJournalLine) { ApplicationArea = Basic, Suite; Caption = 'Selected Journal Lines'; Enabled = CanCancelApprovalForJnlLine OR CanCancelFlowApprovalForLine; Image = CancelApprovalRequest; ToolTip = 'Cancel sending selected journal lines for approval.'; trigger OnAction() var GenJournalLine: Record "Gen. Journal Line"; ApprovalsMgmt: Codeunit "Approvals Mgmt."; begin GetCurrentlySelectedLines(GenJournalLine); ApprovalsMgmt.TryCancelJournalLineApprovalRequests(GenJournalLine); end; } } action(CreateFlow) { ApplicationArea = Basic, Suite; Caption = 'Create a Flow'; Image = Flow; ToolTip = 'Create a new Flow from a list of relevant Flow templates.'; Visible = IsSaaS; trigger OnAction() var FlowServiceManagement: Codeunit "Flow Service Management"; FlowTemplateSelector: Page "Flow Template Selector"; begin // Opens page 6400 where the user can use filtered templates to create new flows. FlowTemplateSelector.SetSearchText(FlowServiceManagement.GetJournalTemplateFilter()); FlowTemplateSelector.Run(); end; } action(SeeFlows) { ApplicationArea = Basic, Suite; Caption = 'See my Flows'; Image = Flow; RunObject = Page "Flow Selector"; ToolTip = 'View and configure Flows that you created.'; } } group(Approval) { Caption = 'Approval'; action(Approve) { ApplicationArea = Basic, Suite; Caption = 'Approve'; Image = Approve; Promoted = true; PromotedCategory = Category7; PromotedIsBig = true; PromotedOnly = true; ToolTip = 'Approve the requested changes.'; Visible = OpenApprovalEntriesExistForCurrUser; trigger OnAction() var ApprovalsMgmt: Codeunit "Approvals Mgmt."; begin ApprovalsMgmt.ApproveGenJournalLineRequest(Rec); end; } action(Reject) { ApplicationArea = Basic, Suite; Caption = 'Reject'; Image = Reject; Promoted = true; PromotedCategory = Category7; PromotedIsBig = true; PromotedOnly = true; ToolTip = 'Reject the approval request.'; Visible = OpenApprovalEntriesExistForCurrUser; trigger OnAction() var ApprovalsMgmt: Codeunit "Approvals Mgmt."; begin ApprovalsMgmt.RejectGenJournalLineRequest(Rec); end; } action(Delegate) { ApplicationArea = Basic, Suite; Caption = 'Delegate'; Image = Delegate; Promoted = true; PromotedCategory = Category7; PromotedOnly = true; ToolTip = 'Delegate the approval to a substitute approver.'; Visible = OpenApprovalEntriesExistForCurrUser; trigger OnAction() var ApprovalsMgmt: Codeunit "Approvals Mgmt."; begin ApprovalsMgmt.DelegateGenJournalLineRequest(Rec); end; } action(Comments) { ApplicationArea = Basic, Suite; Caption = 'Comments'; Image = ViewComments; Promoted = true; PromotedCategory = Category7; PromotedOnly = true; ToolTip = 'View or add comments for the record.'; Visible = OpenApprovalEntriesExistForCurrUser; trigger OnAction() var GenJournalBatch: Record "Gen. Journal Batch"; ApprovalsMgmt: Codeunit "Approvals Mgmt."; begin if OpenApprovalEntriesOnJnlLineExist then ApprovalsMgmt.GetApprovalComment(Rec) else if OpenApprovalEntriesOnJnlBatchExist then if GenJournalBatch.Get("Journal Template Name", "Journal Batch Name") then ApprovalsMgmt.GetApprovalComment(GenJournalBatch); end; } } group("Opening Balance") { Caption = 'Opening Balance'; group("Prepare journal") { Caption = 'Prepare journal'; Image = Journals; action("G/L Accounts Opening balance ") { ApplicationArea = Basic, Suite; Caption = 'G/L Accounts Opening balance'; Image = TransferToGeneralJournal; ToolTip = 'Creates Bank Receipt Voucher line per G/L account to enable manual entry of G/L account open balances during the setup of a new company'; trigger OnAction() var GLAccount: Record "G/L Account"; CreateGLAccJournalLines: Report "Create G/L Acc. Journal Lines"; DocumentTypes: Option; begin GLAccount.SetRange("Account Type", GLAccount."Account Type"::Posting); GLAccount.SetRange("Income/Balance", GLAccount."Income/Balance"::"Balance Sheet"); GLAccount.SetRange("Direct Posting", true); GLAccount.SetRange(Blocked, false); CreateGLAccJournalLines.SetTableView(GLAccount); CreateGLAccJournalLines.InitializeRequest(DocumentTypes, Today(), "Journal Template Name", "Journal Batch Name", ''); CreateGLAccJournalLines.UseRequestPage(false); CreateGLAccJournalLines.SetDefaultDocumentNo(CurrentDocNo); Commit(); // Commit is required for Create Lines. CreateGLAccJournalLines.Run(); end; } action("Customers Opening balance") { ApplicationArea = Basic, Suite; Caption = 'Customers Opening balance'; Image = TransferToGeneralJournal; ToolTip = 'Creates Bank Receipt Voucher line per Customer to enable manual entry of Customer open balances during the setup of a new company'; trigger OnAction() var Customer: Record Customer; CreateCustomerJournalLines: Report "Create Customer Journal Lines"; DocumentTypes: Option; begin Customer.SetRange(Blocked, Customer.Blocked::" "); CreateCustomerJournalLines.SetTableView(Customer); CreateCustomerJournalLines.InitializeRequest(DocumentTypes, Today(), Today()); CreateCustomerJournalLines.InitializeRequestTemplate("Journal Template Name", "Journal Batch Name", ''); CreateCustomerJournalLines.UseRequestPage(false); CreateCustomerJournalLines.SetDefaultDocumentNo(CurrentDocNo); Commit(); // Commit is required for Create Lines. CreateCustomerJournalLines.Run(); end; } action("Vendors Opening balance") { ApplicationArea = Basic, Suite; Caption = 'Vendors Opening balance'; Image = TransferToGeneralJournal; ToolTip = 'Creates a Bank Receipt Voucher line for each vendor. This lets you manually enter open balances for vendors when you set up a new company.'; trigger OnAction() var Vendor: Record Vendor; CreateVendorJournalLines: Report "Create Vendor Journal Lines"; DocumentTypes: Option; begin Vendor.SetRange(Blocked, Vendor.Blocked::" "); CreateVendorJournalLines.SetTableView(Vendor); CreateVendorJournalLines.InitializeRequest(DocumentTypes, Today(), Today()); CreateVendorJournalLines.InitializeRequestTemplate("Journal Template Name", "Journal Batch Name", ''); CreateVendorJournalLines.UseRequestPage(false); CreateVendorJournalLines.SetDefaultDocumentNo(CurrentDocNo); Commit(); // Commit is required for Create Lines. CreateVendorJournalLines.Run(); end; } } } group("Page") { Caption = 'Page'; action(EditInExcel) { ApplicationArea = Basic, Suite; Caption = 'Edit in Excel'; Image = Excel; Promoted = true; PromotedCategory = Category8; PromotedIsBig = true; PromotedOnly = true; ToolTip = 'Send the data in the journal to an Excel file for analysis or editing.'; Visible = IsSaasExcelAddinEnabled; trigger OnAction() var ODataUtility: Codeunit ODataUtility; begin ODataUtility.EditJournalWorksheetInExcel(CurrPage.Caption(), CurrPage.ObjectId(false), "Journal Batch Name", "Journal Template Name"); end; } action(PreviousDocNumberTrx) { ApplicationArea = Basic, Suite; Caption = 'Previous Doc No.'; Image = PreviousRecord; Promoted = true; PromotedCategory = Category8; PromotedIsBig = true; PromotedOnly = true; ToolTip = 'Navigate to previous document number for current batch.'; Visible = IsSimplePage; trigger OnAction() begin IterateDocNumbers('+', -1); end; } action(NextDocNumberTrx) { ApplicationArea = Basic, Suite; Caption = 'Next Doc No.'; Image = NextRecord; Promoted = true; PromotedCategory = Category8; PromotedIsBig = true; PromotedOnly = true; ToolTip = 'Navigate to next document number for current batch.'; Visible = IsSimplePage; trigger OnAction() begin IterateDocNumbers('-', 1); end; } action(ClassicView) { ApplicationArea = Basic, Suite; Caption = 'Show More Columns'; Image = SetupColumns; Promoted = true; PromotedCategory = Category8; PromotedIsBig = true; PromotedOnly = true; ToolTip = 'View all available fields. Fields not frequently used are currently hidden.'; Visible = IsSimplePage; trigger OnAction() begin // set journal preference for this page to be not simple mode (classic mode) CurrPage.Close(); GenJnlManagement.SetJournalSimplePageModePreference(false, Page::"Bank Receipt Voucher"); GenJnlManagement.SetLastViewedJournalBatchName(Page::"Bank Receipt Voucher", CurrentJnlBatchName); Page.Run(Page::"Bank Receipt Voucher"); end; } action(SimpleView) { ApplicationArea = Basic, Suite; Caption = 'Show Fewer Columns'; Image = SetupList; Promoted = true; PromotedCategory = Category8; PromotedIsBig = true; PromotedOnly = true; ToolTip = 'Hide fields that are not frequently used.'; Visible = not IsSimplePage; trigger OnAction() begin // set journal preference for this page to be simple mode CurrPage.Close(); GenJnlManagement.SetJournalSimplePageModePreference(true, Page::"Bank Receipt Voucher"); GenJnlManagement.SetLastViewedJournalBatchName(Page::"Bank Receipt Voucher", CurrentJnlBatchName); Page.Run(Page::"Bank Receipt Voucher"); end; } action("New Doc No.") { ApplicationArea = Basic, Suite; Caption = 'New Document Number'; Image = New; Promoted = true; PromotedCategory = Category8; PromotedIsBig = true; PromotedOnly = true; ToolTip = 'Creates a new document number.'; Visible = IsSimplePage; trigger OnAction() begin NewDocumentNo(); end; } } } } trigger OnAfterGetCurrRecord() var ClientTypeManagement: Codeunit "Client Type Management"; begin GenJnlManagement.GetAccounts(Rec, AccName, BalAccName); if ClientTypeManagement.GetCurrentClientType() <> ClientType::ODataV4 then UpdateBalance(); EnableApplyEntriesAction(); SetControlAppearance(); // PostedFromSimplePage is set to TRUE when 'POST' / 'POST+PRINT' action is executed in simple page mode. // It gets set to FALSE when OnNewRecord is called in the simple mode. // After posting we try to find the first record and filter on its document number // Executing LoaddataFromRecord for incomingDocAttachFactbox is also forcing this (PAG39) page to update // and for some reason after posting this page doesn't refresh with the filter set by POST / POST-PRINT action in simple mode. // To resolve this only call LoaddataFromRecord if PostedFromSimplePage is FALSE. if not PostedFromSimplePage then CurrPage.IncomingDocAttachFactBox.Page.LoadDataFromRecord(Rec); SetJobQueueVisibility(); end; trigger OnAfterGetRecord() begin GenJnlManagement.GetAccounts(Rec, AccName, BalAccName); ShowShortcutDimCode(ShortcutDimCode); HasIncomingDocument := "Incoming Document Entry No." <> 0; CurrPage.IncomingDocAttachFactBox.Page.SetCurrentRecordID(RecordId()); SetUserInteractions(); // ShowOldNarration(); NarrationText := VoucherFunctions.ShowOldNarration(Rec); end; trigger OnInit() var LocalClientTypeManagement: Codeunit "Client Type Management"; begin TotalBalanceVisible := true; BalanceVisible := true; AmountVisible := true; // Get simple / classic mode for this page except when called from a webservices (SOAP or ODATA) if LocalClientTypeManagement.GetCurrentClientType() in [ClientType::SOAP, ClientType::OData, ClientType::ODataV4] then IsSimplePage := false else IsSimplePage := GenJnlManagement.GetJournalSimplePageModePreference(Page::"Bank Receipt Voucher"); GeneralLedgerSetup.Get(); SetJobQueueVisibility(); end; trigger OnInsertRecord(BelowxRec: Boolean): Boolean begin CurrPage.IncomingDocAttachFactBox.Page.SetCurrentRecordID(RecordId()); end; trigger OnModifyRecord(): Boolean begin SetUserInteractions(); end; trigger OnNewRecord(BelowxRec: Boolean) begin UpdateBalance(); EnableApplyEntriesAction(); SetUpNewLine(xRec, Balance, BelowxRec); // set values from header for currency code, doc no. and posting date // for show less columns or simple page mode if IsSimplePage then begin PostedFromSimplePage := false; SetDataForSimpleModeOnNewRecord(); end; Clear(ShortcutDimCode); Clear(AccName); SetUserInteractions(); end; trigger OnOpenPage() var ServerSetting: Codeunit "Server Setting"; EnvironmentInfo: Codeunit "Environment Information"; ClientTypeManagement: Codeunit "Client Type Management"; JnlSelected: Boolean; LastGenJnlBatch: Code[10]; VoucherEnum: Enum "Gen. Journal Template Type"; begin NarrationText := ''; IsSaasExcelAddinEnabled := ServerSetting.GetIsSaasExcelAddinEnabled(); if ClientTypeManagement.GetCurrentClientType() = ClientType::ODataV4 then exit; BalAccName := ''; SetControlVisibility(); SetDimensionVisibility(); if IsOpenedFromBatch() then begin CurrentJnlBatchName := "Journal Batch Name"; GenJnlManagement.OpenJnl(CurrentJnlBatchName, Rec); SetControlAppearanceFromBatch(); SetDataForSimpleModeOnOpen(); exit; end; VoucherFunctions.VoucherTemplateSelection(Page::"Bank Receipt Voucher", VoucherEnum::"Bank Receipt Voucher", false, Rec, JnlSelected); if not JnlSelected then Error(''); LastGenJnlBatch := GenJnlManagement.GetLastViewedJournalBatchName(Page::"Bank Payment Voucher"); if LastGenJnlBatch <> '' then CurrentJnlBatchName := LastGenJnlBatch; GenJnlManagement.OpenJnl(CurrentJnlBatchName, Rec); SetControlAppearanceFromBatch(); IsSaaS := EnvironmentInfo.IsSaaS(); SetDataForSimpleModeOnOpen(); NarrationText := ''; end; var GeneralLedgerSetup: Record "General Ledger Setup"; GenJnlManagement: Codeunit GenJnlManagement; VoucherFunctions: Codeunit "Voucher Functions"; CurrentJnlBatchName: Code[10]; AccName: Text[100]; BalAccName: Text[100]; Balance: Decimal; TotalBalance: Decimal; ShortcutDimCode: array[8] of Code[20]; HasIncomingDocument: Boolean; ApplyEntriesActionEnabled: Boolean; [InDataSet] BalanceVisible: Boolean; [InDataSet] TotalBalanceVisible: Boolean; StyleTxt: Text; OpenApprovalEntriesExistForCurrUser: Boolean; OpenApprovalEntriesOnJnlBatchExist: Boolean; OpenApprovalEntriesOnJnlLineExist: Boolean; OpenApprovalEntriesOnBatchOrCurrJnlLineExist: Boolean; OpenApprovalEntriesOnBatchOrAnyJnlLineExist: Boolean; ShowWorkflowStatusOnBatch: Boolean; ShowWorkflowStatusOnLine: Boolean; CanCancelApprovalForJnlBatch: Boolean; CanCancelApprovalForJnlLine: Boolean; IsSaasExcelAddinEnabled: Boolean; CanRequestFlowApprovalForBatch: Boolean; CanRequestFlowApprovalForBatchAndAllLines: Boolean; CanRequestFlowApprovalForBatchAndCurrentLine: Boolean; CanCancelFlowApprovalForBatch: Boolean; CanCancelFlowApprovalForLine: Boolean; AmountVisible: Boolean; DebitCreditVisible: Boolean; IsSaaS: Boolean; IsSimplePage: Boolean; JobQueuesUsed: Boolean; JobQueueVisible: Boolean; CurrentDocNo: Code[20]; CurrentPostingDate: Date; CurrentCurrencyCode: Code[10]; IsChangingDocNo: Boolean; DimVisible1: Boolean; DimVisible2: Boolean; DimVisible3: Boolean; DimVisible4: Boolean; DimVisible5: Boolean; DimVisible6: Boolean; DimVisible7: Boolean; DimVisible8: Boolean; PostedFromSimplePage: Boolean; NarrationText: Text[2000]; BankPaymentInsertedMsg: Label 'Bank Payment Voucher lines have been successfully inserted from Standard Bank Payment Voucher %1.', Comment = '%1 = Standard General Journal.Code'; GeneralJournalCreatedMsg: Label 'Standard General Journal %1 has been successfully created.', Comment = '%1 = Standard General Journal.Code'; MissingExchangeRatesQst: Label 'There are no exchange rates for currency %1 and date %2. Do you want to add them now? Otherwise, the last change you made will be reverted.', Comment = '%1 - currency code, %2 - posting date'; procedure SetUserInteractions() begin StyleTxt := GetStyle(); end; procedure NewDocumentNo() var GenJournalLine: Record "Gen. Journal Line"; GenJnlBatch: Record "Gen. Journal Batch"; NoSeriesMgt: Codeunit NoSeriesManagement; LastDocNo: Code[20]; begin if Count() = 0 then exit; GenJnlBatch.Get("Journal Template Name", CurrentJnlBatchName); GenJournalLine.Reset(); GenJournalLine.SetCurrentKey("Document No."); GenJournalLine.SetRange("Journal Template Name", "Journal Template Name"); GenJournalLine.SetRange("Journal Batch Name", "Journal Batch Name"); if GenJournalLine.FindLast() then begin LastDocNo := GenJournalLine."Document No."; IncrementDocumentNo(GenJnlBatch, LastDocNo); end else LastDocNo := NoSeriesMgt.TryGetNextNo(GenJnlBatch."No. Series", "Posting Date"); CurrentDocNo := LastDocNo; SetDocumentNumberFilter(CurrentDocNo); end; local procedure UpdateBalance() var ShowBalance: Boolean; ShowTotalBalance: Boolean; begin GenJnlManagement.CalcBalance(Rec, xRec, Balance, TotalBalance, ShowBalance, ShowTotalBalance); BalanceVisible := ShowBalance; TotalBalanceVisible := ShowTotalBalance; end; local procedure EnableApplyEntriesAction() begin ApplyEntriesActionEnabled := ("Account Type" in ["Account Type"::Customer, "Account Type"::Vendor, "Account Type"::Employee]) or ("Bal. Account Type" in ["Bal. Account Type"::Customer, "Bal. Account Type"::Vendor, "Bal. Account Type"::Employee]); end; local procedure CurrentJnlBatchNameOnAfterVali() begin CurrPage.SaveRecord(); GenJnlManagement.SetName(CurrentJnlBatchName, Rec); SetControlAppearanceFromBatch(); CurrPage.Update(false); end; local procedure GetCurrentlySelectedLines(var GenJournalLine: Record "Gen. Journal Line"): Boolean begin CurrPage.SetSelectionFilter(GenJournalLine); exit(GenJournalLine.FindSet()); end; local procedure SetControlAppearance() var ApprovalsMgmt: Codeunit "Approvals Mgmt."; WorkflowWebhookManagement: Codeunit "Workflow Webhook Management"; CanRequestFlowApprovalForLine: Boolean; begin OpenApprovalEntriesExistForCurrUser := OpenApprovalEntriesExistForCurrUser or ApprovalsMgmt.HasOpenApprovalEntriesForCurrentUser(RecordId()); OpenApprovalEntriesOnJnlLineExist := ApprovalsMgmt.HasOpenApprovalEntries(RecordId()); OpenApprovalEntriesOnBatchOrCurrJnlLineExist := OpenApprovalEntriesOnJnlBatchExist or OpenApprovalEntriesOnJnlLineExist; ShowWorkflowStatusOnLine := CurrPage.WorkflowStatusLine.Page.SetFilterOnWorkflowRecord(RecordId()); CanCancelApprovalForJnlLine := ApprovalsMgmt.CanCancelApprovalForRecord(RecordId()); VoucherFunctions.SetPayrollAppearance(); WorkflowWebhookManagement.GetCanRequestAndCanCancel(RecordId(), CanRequestFlowApprovalForLine, CanCancelFlowApprovalForLine); CanRequestFlowApprovalForBatchAndCurrentLine := CanRequestFlowApprovalForBatch and CanRequestFlowApprovalForLine; end; local procedure IterateDocNumbers(FindTxt: Text; NextNum: Integer) var GenJournalLine: Record "Gen. Journal Line"; CurrentDocNoWasFound: Boolean; NoLines: Boolean; begin if Count() = 0 then NoLines := true; GenJournalLine.Reset(); GenJournalLine.SetCurrentKey("Document No.", "Line No."); GenJournalLine.SetRange("Journal Template Name", "Journal Template Name"); GenJournalLine.SetRange("Journal Batch Name", "Journal Batch Name"); if GenJournalLine.Find(FindTxt) then repeat if NoLines then begin SetDataForSimpleMode(GenJournalLine); exit; end; // Find the rec for current doc no. if not CurrentDocNoWasFound and (GenJournalLine."Document No." = CurrentDocNo) then CurrentDocNoWasFound := true; if CurrentDocNoWasFound and (GenJournalLine."Document No." <> CurrentDocNo) then begin SetDataForSimpleMode(GenJournalLine); exit; end; until GenJournalLine.Next(NextNum) = 0; end; local procedure SetControlAppearanceFromBatch() var GenJournalBatch: Record "Gen. Journal Batch"; ApprovalsMgmt: Codeunit "Approvals Mgmt."; WorkflowWebhookManagement: Codeunit "Workflow Webhook Management"; CanRequestFlowApprovalForAllLines: Boolean; begin if ("Journal Template Name" <> '') and ("Journal Batch Name" <> '') then GenJournalBatch.Get("Journal Template Name", "Journal Batch Name") else if not GenJournalBatch.Get(GetRangeMax("Journal Template Name"), CurrentJnlBatchName) then exit; ShowWorkflowStatusOnBatch := CurrPage.WorkflowStatusBatch.Page.SetFilterOnWorkflowRecord(GenJournalBatch.RecordId()); OpenApprovalEntriesExistForCurrUser := ApprovalsMgmt.HasOpenApprovalEntriesForCurrentUser(GenJournalBatch.RecordId()); OpenApprovalEntriesOnJnlBatchExist := ApprovalsMgmt.HasOpenApprovalEntries(GenJournalBatch.RecordId()); OpenApprovalEntriesOnBatchOrAnyJnlLineExist := OpenApprovalEntriesOnJnlBatchExist or ApprovalsMgmt.HasAnyOpenJournalLineApprovalEntries("Journal Template Name", "Journal Batch Name"); CanCancelApprovalForJnlBatch := ApprovalsMgmt.CanCancelApprovalForRecord(GenJournalBatch.RecordId()); WorkflowWebhookManagement.GetCanRequestAndCanCancelJournalBatch( GenJournalBatch, CanRequestFlowApprovalForBatch, CanCancelFlowApprovalForBatch, CanRequestFlowApprovalForAllLines); CanRequestFlowApprovalForBatchAndAllLines := CanRequestFlowApprovalForBatch and CanRequestFlowApprovalForAllLines; end; local procedure SetControlVisibility() var GLSetup: Record "General Ledger Setup"; begin GLSetup.Get(); if IsSimplePage then begin AmountVisible := false; DebitCreditVisible := true; end else begin AmountVisible := not (GLSetup."Show Amounts" = GLSetup."Show Amounts"::"Debit/Credit Only"); DebitCreditVisible := not (GLSetup."Show Amounts" = GLSetup."Show Amounts"::"Amount Only"); end; end; local procedure SetDocumentNumberFilter(DocNoToSet: Code[20]) var OriginalFilterGroup: Integer; begin OriginalFilterGroup := FilterGroup(); FilterGroup := 25; SetFilter("Document No.", DocNoToSet); FilterGroup := OriginalFilterGroup; end; local procedure SetDimensionVisibility() var DimMgt: Codeunit DimensionManagement; begin DimVisible1 := false; DimVisible2 := false; DimVisible3 := false; DimVisible4 := false; DimVisible5 := false; DimVisible6 := false; DimVisible7 := false; DimVisible8 := false; if not IsSimplePage then DimMgt.UseShortcutDims( DimVisible1, DimVisible2, DimVisible3, DimVisible4, DimVisible5, DimVisible6, DimVisible7, DimVisible8); Clear(DimMgt); end; local procedure GetTotalDebitAmt(): Decimal var GenJournalLine: Record "Gen. Journal Line"; begin if IsSimplePage then begin GenJournalLine.SetRange("Journal Template Name", "Journal Template Name"); GenJournalLine.SetRange("Journal Batch Name", "Journal Batch Name"); GenJournalLine.SetRange("Document No.", CurrentDocNo); GenJournalLine.CalcSums("Debit Amount"); exit(GenJournalLine."Debit Amount"); end end; local procedure GetTotalCreditAmt(): Decimal var GenJournalLine: Record "Gen. Journal Line"; begin if IsSimplePage then begin GenJournalLine.SetRange("Journal Template Name", "Journal Template Name"); GenJournalLine.SetRange("Journal Batch Name", "Journal Batch Name"); GenJournalLine.SetRange("Document No.", CurrentDocNo); GenJournalLine.CalcSums("Credit Amount"); exit(GenJournalLine."Credit Amount"); end end; local procedure SetDataForSimpleMode(GenJournalLine1: Record "Gen. Journal Line") begin CurrentDocNo := GenJournalLine1."Document No."; CurrentPostingDate := GenJournalLine1."Posting Date"; CurrentCurrencyCode := GenJournalLine1."Currency Code"; SetDocumentNumberFilter(CurrentDocNo); end; local procedure SetDataForSimpleModeOnOpen() begin if IsSimplePage then begin // Filter on the first record SetCurrentKey("Document No.", "Line No."); if FindFirst() then SetDataForSimpleMode(Rec) else begin // if no rec is found reset the currentposting date to workdate and currency code to empty CurrentPostingDate := WorkDate(); Clear(CurrentCurrencyCode); end; end; end; local procedure SetDataForSimpleModeOnBatchChange() var GenJournalLine: Record "Gen. Journal Line"; begin GenJnlManagement.SetLastViewedJournalBatchName(Page::"Bank Payment Voucher", CurrentJnlBatchName); // Need to set up simple page mode properties on batch change if IsSimplePage then begin GenJournalLine.Reset(); GenJournalLine.SetRange("Journal Template Name", "Journal Template Name"); GenJournalLine.SetRange("Journal Batch Name", CurrentJnlBatchName); IsChangingDocNo := false; if GenJournalLine.FindFirst() then SetDataForSimpleMode(GenJournalLine); end; end; local procedure SetDataForSimpleModeOnNewRecord() begin // No lines shown if Count() = 0 then if ((xRec."Document No." = '') or (xRec."Journal Batch Name" <> "Journal Batch Name")) and (not IsChangingDocNo) then CurrentDocNo := "Document No." else begin "Document No." := CurrentDocNo; Validate("Credit Amount", 0); Validate("Debit Amount", 0); end else "Document No." := CurrentDocNo; "Currency Code" := CurrentCurrencyCode; if CurrentPostingDate <> 0D then Validate("Posting Date", CurrentPostingDate); end; local procedure SetDataForSimpleModeOnPropValidation(FiledNumber: Integer) var GenJournalLine: Record "Gen. Journal Line"; begin if IsSimplePage and (Count() > 0) then begin GenJournalLine.Reset(); GenJournalLine.SetRange("Journal Template Name", "Journal Template Name"); GenJournalLine.SetRange("Journal Batch Name", "Journal Batch Name"); GenJournalLine.SetRange("Document No.", CurrentDocNo); if GenJournalLine.Find('-') then repeat case FiledNumber of GenJournalLine.FieldNo("Currency Code"): GenJournalLine.Validate("Currency Code", CurrentCurrencyCode); GenJournalLine.FieldNo("Posting Date"): GenJournalLine.Validate("Posting Date", CurrentPostingDate); end; GenJournalLine.Modify(); until GenJournalLine.Next() = 0; end; CurrPage.Update(false); end; local procedure SetDataForSimpleModeOnPost() begin PostedFromSimplePage := true; SetCurrentKey("Document No.", "Line No."); if FindFirst() then SetDataForSimpleMode(Rec) end; local procedure UpdateCurrencyFactor(FieldNo: Integer) var UpdateCurrencyExchangeRates: Codeunit "Update Currency Exchange Rates"; ConfirmManagement: Codeunit "Confirm Management"; begin if CurrentCurrencyCode <> '' then if UpdateCurrencyExchangeRates.ExchangeRatesForCurrencyExist(CurrentPostingDate, CurrentCurrencyCode) then SetDataForSimpleModeOnPropValidation(FieldNo) else if ConfirmManagement.GetResponseOrDefault( StrSubstNo(MissingExchangeRatesQst, CurrentCurrencyCode, CurrentPostingDate), true) then begin UpdateCurrencyExchangeRates.OpenExchangeRatesPage(CurrentCurrencyCode); UpdateCurrencyFactor(FieldNo); end else begin CurrentCurrencyCode := "Currency Code"; CurrentPostingDate := "Posting Date"; end else SetDataForSimpleModeOnPropValidation(FieldNo); end; local procedure SetJobQueueVisibility() begin JobQueueVisible := "Job Queue Status" = "Job Queue Status"::"Scheduled for Posting"; JobQueuesUsed := GeneralLedgerSetup.JobQueueActive(); end; }
46.251376
283
0.504096
ed8492c8d7f12d32721f420c99ded43b75227743
2,678
pm
Perl
auto-lib/Paws/LookoutMetrics/RedshiftSourceConfig.pm
0leksii/aws-sdk-perl
b2132fe3c79a06fd15b6137e8a0eb628de722e0f
[ "Apache-2.0" ]
164
2015-01-08T14:58:53.000Z
2022-02-20T19:16:24.000Z
auto-lib/Paws/LookoutMetrics/RedshiftSourceConfig.pm
0leksii/aws-sdk-perl
b2132fe3c79a06fd15b6137e8a0eb628de722e0f
[ "Apache-2.0" ]
348
2015-01-07T22:08:38.000Z
2022-01-27T14:34:44.000Z
auto-lib/Paws/LookoutMetrics/RedshiftSourceConfig.pm
0leksii/aws-sdk-perl
b2132fe3c79a06fd15b6137e8a0eb628de722e0f
[ "Apache-2.0" ]
87
2015-04-22T06:29:47.000Z
2021-09-29T14:45:55.000Z
# Generated by default/object.tt package Paws::LookoutMetrics::RedshiftSourceConfig; use Moose; has ClusterIdentifier => (is => 'ro', isa => 'Str', required => 1); has DatabaseHost => (is => 'ro', isa => 'Str', required => 1); has DatabaseName => (is => 'ro', isa => 'Str', required => 1); has DatabasePort => (is => 'ro', isa => 'Int', required => 1); has RoleArn => (is => 'ro', isa => 'Str', required => 1); has SecretManagerArn => (is => 'ro', isa => 'Str', required => 1); has TableName => (is => 'ro', isa => 'Str', required => 1); has VpcConfiguration => (is => 'ro', isa => 'Paws::LookoutMetrics::VpcConfiguration', required => 1); 1; ### main pod documentation begin ### =head1 NAME Paws::LookoutMetrics::RedshiftSourceConfig =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::LookoutMetrics::RedshiftSourceConfig object: $service_obj->Method(Att1 => { ClusterIdentifier => $value, ..., VpcConfiguration => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::LookoutMetrics::RedshiftSourceConfig object: $result = $service_obj->Method(...); $result->Att1->ClusterIdentifier =head1 DESCRIPTION Provides information about the Amazon Redshift database configuration. =head1 ATTRIBUTES =head2 B<REQUIRED> ClusterIdentifier => Str A string identifying the Redshift cluster. =head2 B<REQUIRED> DatabaseHost => Str The name of the database host. =head2 B<REQUIRED> DatabaseName => Str The Redshift database name. =head2 B<REQUIRED> DatabasePort => Int The port number where the database can be accessed. =head2 B<REQUIRED> RoleArn => Str The Amazon Resource Name (ARN) of the role providing access to the database. =head2 B<REQUIRED> SecretManagerArn => Str The Amazon Resource Name (ARN) of the AWS Secrets Manager role. =head2 B<REQUIRED> TableName => Str The table name of the Redshift database. =head2 B<REQUIRED> VpcConfiguration => L<Paws::LookoutMetrics::VpcConfiguration> Contains information about the Amazon Virtual Private Cloud (VPC) configuration. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::LookoutMetrics> =head1 BUGS and CONTRIBUTIONS The source code is located here: L<https://github.com/pplu/aws-sdk-perl> Please report bugs to: L<https://github.com/pplu/aws-sdk-perl/issues> =cut
26
113
0.71882
eddc5832e6563cb1d474f84167e85386e1197406
664
pl
Perl
lib/unicore/lib/gc_sc/ODI.pl
basusingh/Nanny-Bot
4f3368c750b378f1b4d38a48dad6ac095af14056
[ "MIT" ]
1
2021-07-29T03:46:04.000Z
2021-07-29T03:46:04.000Z
lib/unicore/lib/gc_sc/ODI.pl
basusingh/Nanny-Bot
4f3368c750b378f1b4d38a48dad6ac095af14056
[ "MIT" ]
null
null
null
lib/unicore/lib/gc_sc/ODI.pl
basusingh/Nanny-Bot
4f3368c750b378f1b4d38a48dad6ac095af14056
[ "MIT" ]
null
null
null
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is built by mktables from e.g. UnicodeData.txt. # Any changes made here will be lost! # # Binary property 'Other_Default_Ignorable_Code_Point' # return <<'END'; 034F Other_Default_Ignorable_Code_Point 115F 1160 Other_Default_Ignorable_Code_Point 2065 2069 Other_Default_Ignorable_Code_Point 3164 Other_Default_Ignorable_Code_Point FFA0 Other_Default_Ignorable_Code_Point FFF0 FFF8 Other_Default_Ignorable_Code_Point E0000 Other_Default_Ignorable_Code_Point E0002 E001F Other_Default_Ignorable_Code_Point E0080 E00FF Other_Default_Ignorable_Code_Point E01F0 E0FFF Other_Default_Ignorable_Code_Point END
33.2
59
0.84488
ed66fe0c836e25e1174982db3f27aa806894461e
4,554
pl
Perl
scripting/local_date_time.pl
bheckel/code
98309e8aa145901e49460546643c911eaaff54e6
[ "Apache-2.0" ]
1
2019-08-11T00:39:34.000Z
2019-08-11T00:39:34.000Z
scripting/local_date_time.pl
bheckel/code
98309e8aa145901e49460546643c911eaaff54e6
[ "Apache-2.0" ]
null
null
null
scripting/local_date_time.pl
bheckel/code
98309e8aa145901e49460546643c911eaaff54e6
[ "Apache-2.0" ]
1
2020-07-28T05:58:47.000Z
2020-07-28T05:58:47.000Z
#!/perl/bin/perl -w ############################################################################## # Program Name: local_date_time.pl # # Summary: Convert to English dates based on localtime() # Used in nmail.pl # # Created: Thu Feb 18 1999 10:28:14 (Bob Heckel) # Modified: Mon 10 Jul 2006 13:51:32 (Bob Heckel) ############################################################################## my ($mon, $day, $year, $today); my %months = ( "0" => "JAN", "1" => "FEB", "2" => "MAR", "3" => "APR", "4" => "MAY", "5" => "JUN", "6" => "JUL", "7" => "AUG", "8" => "SEP", "9" => "OCT", "10" => "NOV", "11" => "DEC", ); ($mon, $day, $year) = (localtime())[4,3,5]; # Keep Oracle happy by using it's single quoted date format. $today = "'" . $day . '-' . $months{$mon} . '-' . eval($year+1900) . "'"; # DEPRECATED: ($sec, $min, $hour, $mday, $mon, $year, $wday, $ydat, $isdst) = localtime(time); # A BLOCK by itself (labeled or not) is semantically equivalent to a loop that # executes once. Used here as a Select Case statement. LONGWKDAY: { $longwdaystr = Sunday, last LONGWKDAY if $wday == 0; $longwdaystr = Monday, last LONGWKDAY if $wday == 1; $longwdaystr = Tuesday, last LONGWKDAY if $wday == 2; $longwdaystr = Wednesday, last LONGWKDAY if $wday == 3; $longwdaystr = Thursday, last LONGWKDAY if $wday == 4; $longwdaystr = Friday, last LONGWKDAY if $wday == 5; $longwdaystr = Saturday, last LONGWKDAY if $wday == 6; $nothing = 1; } ###print "$wday now $longwdaystr\n"; #DEBUG SHORTWKDAY: { $shortwdaystr = Sun, last SHORTWKDAY if $wday == 0; $shortwdaystr = Mon, last SHORTWKDAY if $wday == 1; $shortwdaystr = Tue, last SHORTWKDAY if $wday == 2; $shortwdaystr = Wed, last SHORTWKDAY if $wday == 3; $shortwdaystr = Thu, last SHORTWKDAY if $wday == 4; $shortwdaystr = Fri, last SHORTWKDAY if $wday == 5; $shortwdaystr = Sat, last SHORTWKDAY if $wday == 6; $nothing = 1; } ###print "$wday now $shortwdaystr\n"; #DEBUG LMONTH: { $longmonstr = January, last LMONTH if $mon == 0; $longmonstr = February, last LMONTH if $mon == 1; $longmonstr = March, last LMONTH if $mon == 2; $longmonstr = April, last LMONTH if $mon == 3; $longmonstr = May, last LMONTH if $mon == 4; $longmonstr = June, last LMONTH if $mon == 5; $longmonstr = July, last LMONTH if $mon == 6; $longmonstr = August, last LMONTH if $mon == 7; $longmonstr = September, last LMONTH if $mon == 8; $longmonstr = October, last LMONTH if $mon == 9; $longmonstr = November, last LMONTH if $mon == 10; $longmonstr = December, last LMONTH if $mon == 11; $nothing = 1; } ###print "$mon now $longmonstr\n"; #DEBUG SMONTH: { $shortmonstr = Jan, last SMONTH if $mon == 0; $shortmonstr = Feb, last SMONTH if $mon == 1; $shortmonstr = Mar, last SMONTH if $mon == 2; $shortmonstr = Apr, last SMONTH if $mon == 3; $shortmonstr = May, last SMONTH if $mon == 4; $shortmonstr = Jun, last SMONTH if $mon == 5; $shortmonstr = Jul, last SMONTH if $mon == 6; $shortmonstr = Aug, last SMONTH if $mon == 7; $shortmonstr = Sep, last SMONTH if $mon == 8; $shortmonstr = Oct, last SMONTH if $mon == 9; $shortmonstr = Nov, last SMONTH if $mon == 10; $shortmonstr = Dec, last SMONTH if $mon == 11; $nothing = 1; } ###print "$mon now $shortmonstr\n"; #DEBUG YEAR: { $yearstr = 1999, last YEAR if $year == 99; $yearstr = 2000, last YEAR if $year == 100; $yearstr = 2001, last YEAR if $year == 101; $yearstr = 2002, last YEAR if $year == 102; $yearstr = 2003, last YEAR if $year == 103; $yearstr = 2004, last YEAR if $year == 104; $yearstr = 2005, last YEAR if $year == 105; $nothing = 1; } ###print "$year now $yearstr\n"; #DEBUG # Min & sec don't have leading zeros. $min = 0 . $min if $min < 10; $sec = 0 . $sec if $sec < 10; # Daylight savings. if ($isdst == 0) { $isdst = "EST" } else { $isdst = "EDT" } # E.g. Thu Feb 18 1999 10:58:26 -0500 EST is print "$wdaystr $shortmonstr $mday $yearstr $hour:$min:$sec -0500 $isdst\n";
34.763359
81
0.517567
ed96a23aa41a2f1ecc19a8256739ceb7f283f02b
430
pl
Perl
ndk/prebuilt/linux-x86_64/lib/perl5/5.16.2/unicore/lib/Nv/42.pl
efortuna/AndroidSDKClone
240e73b763c159af6bbcd111f2705b549e85295a
[ "Apache-2.0" ]
1
2019-07-10T15:21:02.000Z
2019-07-10T15:21:02.000Z
ndk/prebuilt/linux-x86_64/lib/perl5/5.16.2/unicore/lib/Nv/42.pl
efortuna/AndroidSDKClone
240e73b763c159af6bbcd111f2705b549e85295a
[ "Apache-2.0" ]
null
null
null
ndk/prebuilt/linux-x86_64/lib/perl5/5.16.2/unicore/lib/Nv/42.pl
efortuna/AndroidSDKClone
240e73b763c159af6bbcd111f2705b549e85295a
[ "Apache-2.0" ]
1
2019-02-25T11:55:44.000Z
2019-02-25T11:55:44.000Z
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 6.1.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. return <<'END'; 32B7 END
30.714286
77
0.669767
edc6e318bc082560cd652398576f3e636025efc1
8,915
pm
Perl
RR/DNSKEY.pm
gitpan/Net-DNS-SEC
41bb441314754fac08a3b48a64a78e63fe2ca7f4
[ "Unlicense" ]
null
null
null
RR/DNSKEY.pm
gitpan/Net-DNS-SEC
41bb441314754fac08a3b48a64a78e63fe2ca7f4
[ "Unlicense" ]
null
null
null
RR/DNSKEY.pm
gitpan/Net-DNS-SEC
41bb441314754fac08a3b48a64a78e63fe2ca7f4
[ "Unlicense" ]
null
null
null
package Net::DNS::RR::DNSKEY; # # $Id: DNSKEY.pm 1271 2014-10-10 21:55:38Z willem $ # use vars qw($VERSION); $VERSION = (qw$LastChangedRevision: 1271 $)[1]; use strict; use base qw(Net::DNS::RR); =head1 NAME Net::DNS::RR::DNSKEY - DNS DNSKEY resource record =cut use integer; use warnings; use Carp; use MIME::Base64; # # source: http://www.iana.org/assignments/dns-sec-alg-numbers # { my @algbyname = ( ## Reserved => 0, # [RFC4034][RFC4398] 'RSAMD5' => 1, # [RFC3110][RFC4034] 'DH' => 2, # [RFC2539] 'DSA' => 3, # [RFC3755][RFC2536] ## Reserved => 4, # [RFC6725] 'RSASHA1' => 5, # [RFC3110][RFC4034] 'DSA-NSEC3-SHA1' => 6, # [RFC5155] 'RSASHA1-NSEC3-SHA1' => 7, # [RFC5155] 'RSASHA256' => 8, # [RFC5702] ## Reserved => 9, # [RFC6725] 'RSASHA512' => 10, # [RFC5702] ## Reserved => 11, # [RFC6725] 'ECC-GOST' => 12, # [RFC5933] 'ECDSAP256SHA256' => 13, # [RFC6605] 'ECDSAP384SHA384' => 14, # [RFC6605] 'INDIRECT' => 252, # [RFC4034] 'PRIVATEDNS' => 253, # [RFC4034] 'PRIVATEOID' => 254, # [RFC4034] ## Reserved => 255, # [RFC4034] ); my %algbyval = reverse @algbyname; my @algbynum = map { ( $_, 0 + $_ ) } keys %algbyval; # accept algorithm number my %algbyname = map { s /[^A-Za-z0-9]//g; $_ } @algbyname, @algbynum; sub algbyname { my $name = shift; my $key = uc $name; # synthetic key $key =~ s /[^A-Z0-9]//g; # strip non-alphanumerics return $algbyname{$key} || croak "unknown algorithm $name"; } sub algbyval { my $value = shift; return $algbyval{$value} || $value; } } sub decode_rdata { ## decode rdata from wire-format octet string my $self = shift; my ( $data, $offset ) = @_; my $keylength = $self->{rdlength} - 4; @{$self}{qw(flags protocol algorithm keybin)} = unpack "\@$offset n C2 a$keylength", $$data; } sub encode_rdata { ## encode rdata as wire-format octet string my $self = shift; my $keybin = $self->keybin || return ''; pack 'n C2 a*', $self->flags, $self->protocol, $self->algorithm, $keybin; } sub format_rdata { ## format rdata portion of RR string. my $self = shift; my $base64 = MIME::Base64::encode $self->keybin || return ''; my @params = map $self->$_, qw(flags protocol algorithm); chomp $base64; return join ' ', @params, "(\n$base64 ) ; Key ID =", $self->keytag; } sub parse_rdata { ## populate RR from rdata in argument list my $self = shift; $self->$_(shift) for qw(flags protocol algorithm); $self->key(@_); } sub defaults() { ## specify RR attribute default values my $self = shift; $self->algorithm(1); $self->protocol(3); } sub flags { my $self = shift; $self->{flags} = 0 + shift if scalar @_; return $self->{flags} || 0; } sub protocol { my $self = shift; $self->{protocol} = 0 + shift if scalar @_; return $self->{protocol} || 0; } sub algorithm { my ( $self, $arg ) = @_; unless ( ref($self) ) { ## class method or simple function my $argn = pop || croak 'undefined argument'; return $argn =~ /[^0-9]/ ? algbyname($argn) : algbyval($argn); } return $self->{algorithm} unless defined $arg; return algbyval( $self->{algorithm} ) if $arg =~ /MNEMONIC/i; return $self->{algorithm} = algbyname($arg); } sub key { my $self = shift; $self->keybin( MIME::Base64::decode( join "", @_ ) ) if scalar @_; return MIME::Base64::encode( $self->keybin(), "" ) if defined wantarray; } sub publickey { &key; } sub keybin { my $self = shift; return $self->{keybin} || '' unless scalar @_; delete $self->{keytag}; $self->{keybin} = shift; } sub privatekeyname { my $self = shift; my $name = lc $self->{owner}->fqdn; sprintf 'K%s+%03d+%05d.private', $name, $self->algorithm, $self->keytag; } sub keylength { my $self = shift; my $keybin = $self->keybin || return undef; local $_ = algbyval( $self->{algorithm} ); if (/^RSA/) { # Modulus length, see RFC 3110 if ( my $exp_length = unpack 'C', $keybin ) { return ( length($keybin) - $exp_length - 1 ) << 3; } else { $exp_length = unpack 'x n', $keybin; return ( length($keybin) - $exp_length - 3 ) << 3; } } elsif (/^DSA/) { # Modulus length, see RFC 2536 my $T = unpack 'C', $keybin; return ( $T << 6 ) + 512; } elsif (/^EC/) { return length($keybin) << 2; } else { return undef; } } sub keytag { my $self = shift; return 0 if ( $self->{flags} & 0xC000 ) == 0xC000; # NULL KEY # RFC4034 Appendix B.1: most significant 16 bits of least significant 24 bits return unpack 'n', substr $self->keybin(), -3 if $self->{algorithm} == 1; # RFC4034 Appendix B return $self->{keytag} = do { my @kp = @{$self}{qw(flags protocol algorithm)}; my $kb = $self->{keybin} || return 0; my $od = length($kb) & 1; my $ac = 0; $ac += $_ for unpack 'n*', pack "n C2 a* x$od", @kp, $kb; $ac += ( $ac >> 16 ); $ac & 0xFFFF; } } sub zone { my $bit = 0x0100; for ( shift->{flags} ||= 0 ) { return $_ & $bit unless scalar @_; my $set = $_ | $bit; $_ = (shift) ? $set : ( $set ^ $bit ); return $_ & $bit; } } sub revoke { my $bit = 0x0080; for ( shift->{flags} ||= 0 ) { return $_ & $bit unless scalar @_; my $set = $_ | $bit; $_ = (shift) ? $set : ( $set ^ $bit ); return $_ & $bit; } } sub sep { my $bit = 0x0001; for ( shift->{flags} ||= 0 ) { return $_ & $bit unless scalar @_; my $set = $_ | $bit; $_ = (shift) ? $set : ( $set ^ $bit ); return $_ & $bit; } } sub is_sep { ## historical my $self = shift; return $self->sep(@_) ? 1 : 0; } sub set_sep { shift->is_sep(1); } ## historical sub unset_sep { shift->is_sep(0); } ## historical sub clear_sep { shift->is_sep(0); } ## historical 1; __END__ =head1 SYNOPSIS use Net::DNS; $rr = new Net::DNS::RR('name DNSKEY flags protocol algorithm publickey'); =head1 DESCRIPTION Class for DNSSEC Key (DNSKEY) resource records. =head1 METHODS The available methods are those inherited from the base class augmented by the type-specific methods defined in this package. Use of undocumented package features or direct access to internal data structures is discouraged and could result in program termination or other unpredictable behaviour. =head2 flags $flags = $rr->flags; $rr->flags( $flags ); Unsigned 16-bit number representing Boolean flags. =head2 protocol $protocol = $rr->protocol; $rr->protocol( $protocol ); The 8-bit protocol number. This field MUST have value 3. =head2 algorithm $algorithm = $rr->algorithm; $rr->algorithm( $algorithm ); The 8-bit algorithm number describes the public key algorithm. algorithm() may also be invoked as a class method or simple function to perform mnemonic and numeric code translation. =head2 key $key = $rr->key; $rr->key( $key ); The key field holds the public key material. The format depends on the algorithm of the key being stored. =head2 privatekeyname $privatekeyname=$rr->privatekeyname Returns the name of the privatekey as it would be generated by the BIND dnssec-keygen program. The format of that name being: K<fqdn>+<algorithm>+<keyid>.private =head2 keylength Returns the length (in bits) of the modulus calculated from the key text. =head2 keytag print "keytag = ", $rr->keytag, "\n"; Returns the 16-bit numerical key tag of the key. (RFC2535 4.1.6) =head2 zone $rr->zone(0); $rr->zone(1); if ( $rr->zone ) { ... } Boolean Zone key flag. =head2 revoke $rr->revoke(0); $rr->revoke(1); if ( $rr->revoke ) { ... } Boolean Revoke flag. =head2 sep $rr->sep(0); $rr->sep(1); if ( $rr->sep ) { ... } Boolean Secure Entry Point flag. =head1 COPYRIGHT Copyright (c)2003-2005 RIPE NCC. Author Olaf M. Kolkman All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of the author not be used in advertising or publicity pertaining to distribution of the software without specific prior written permission. THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS; IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Package template (c)2009,2012 O.M.Kolkman and R.W.Franks. =head1 SEE ALSO L<perl>, L<Net::DNS>, L<Net::DNS::RR>, RFC4034, RFC3755 L<Algorithm Numbers|http://www.iana.org/assignments/dns-sec-alg-numbers> =cut
21.690998
93
0.631071
edaf86f5f0b26a5e53e211d4e86a3f6409a93138
782
t
Perl
t/without.t
wu-lee/module-release
18d25aca184362e99e61ffd6189339db5bcc60f8
[ "Artistic-2.0" ]
null
null
null
t/without.t
wu-lee/module-release
18d25aca184362e99e61ffd6189339db5bcc60f8
[ "Artistic-2.0" ]
null
null
null
t/without.t
wu-lee/module-release
18d25aca184362e99e61ffd6189339db5bcc60f8
[ "Artistic-2.0" ]
null
null
null
#!perl use strict; use warnings; use Test::More tests => 10; BEGIN { use File::Spec; my $file = File::Spec->catfile( qw(t lib setup_common.pl) ); require $file; } use Module::Release; use Test::Without::Module qw( Test::Prereq Module::CPANTS::Analyse ); my @tuples = ( [ qw( Module::Release::Prereq check_prereqs ) ], [ qw( Module::Release::Kwalitee check_kwalitee ) ], ); foreach my $tuple ( @tuples ) { my( $module, $method ) = @$tuple; my $rc = eval "{ package Module::Release; require $module; $module\->import }"; ok( defined $rc, "Loading $module succeeds" ); my $release = Module::Release->new( quiet => 1 ); can_ok( $release, $method ); eval { $release->$method }; my $at = $@; like( $at, qr/You need/i, "Gets right error message" ); }
19.55
81
0.624041
ed9cef52004e1b5c0d9f0ea3a884429b1fcaa1df
502
pl
Perl
cmd/unset/anntalk.pl
latchdevel/DXspider
e61ab5eeea22241ea8d8f1f6d072f5249901d788
[ "Artistic-1.0-Perl", "Artistic-2.0" ]
null
null
null
cmd/unset/anntalk.pl
latchdevel/DXspider
e61ab5eeea22241ea8d8f1f6d072f5249901d788
[ "Artistic-1.0-Perl", "Artistic-2.0" ]
null
null
null
cmd/unset/anntalk.pl
latchdevel/DXspider
e61ab5eeea22241ea8d8f1f6d072f5249901d788
[ "Artistic-1.0-Perl", "Artistic-2.0" ]
null
null
null
# # unset the allow talklike announce flag # # Copyright (c) 1998 - Dirk Koopman # # # my ($self, $line) = @_; my @args = split /\s+/, $line; my $call; my @out; @args = $self->call if (!@args || $self->priv < 9); foreach $call (@args) { $call = uc $call; my $chan = DXChannel::get($call); if ($chan) { $chan->ann_talk(0); $chan->user->wantann_talk(0); push @out, $self->msg('anntu', $call); } else { push @out, $self->msg('e3', "Unset Ann_Talk", $call); } } return (1, @out);
17.928571
57
0.557769
ed25c95ff4508cc041be4cab6605ad7d2622d636
1,796
t
Perl
t/basic.t
Csson/p5-Dist-Zilla-Plugin-PkgVersion-Block
ca5a1cebd28ab55daa2522638f5710392b881e77
[ "Artistic-1.0" ]
null
null
null
t/basic.t
Csson/p5-Dist-Zilla-Plugin-PkgVersion-Block
ca5a1cebd28ab55daa2522638f5710392b881e77
[ "Artistic-1.0" ]
1
2015-05-19T23:21:53.000Z
2015-05-31T13:15:24.000Z
t/basic.t
Csson/p5-Dist-Zilla-Plugin-PkgVersion-Block
ca5a1cebd28ab55daa2522638f5710392b881e77
[ "Artistic-1.0" ]
null
null
null
use strict; use Test::More; use autodie; use Test::DZil; my $classic = q{ package DZT::Classic; 1; }; my $single = q{ package DZT::Single { say 'hello'; } 1; }; my $double = q{ package DZT::First { say 'hello'; }; package DZT::Second { say 'hello'; } 1; }; my $with_ver = q{ package DZT::WithVer 1.2 { } 1; }; my $private = q{ package DZT::Private { } 1; }; my $tzil = Builder->from_config( { dist_root => 'corpus/', }, { add_files => { 'source/lib/DZT/Classic.pm' => $classic, 'source/lib/DZT/Single.pm' => $single, 'source/lib/DZT/Double.pm' => $double, 'source/lib/DZT/WithVer.pm' => $with_ver, 'source/lib/DZT/Private.pm' => $private, 'source/dist.ini' => simple_ini('GatherDir', 'PkgVersion::Block', 'ExecDir'), }, }, ); $tzil->build; my $dzt_classic = $tzil->slurp_file('build/lib/DZT/Classic.pm'); like($dzt_classic, qr{^package DZT::Classic;\n}m, "Untouched classic style."); my $dzt_single = $tzil->slurp_file('build/lib/DZT/Single.pm'); is($dzt_single, q{ package DZT::Single 0.001 { say 'hello'; } 1; }, 'Added version.'); # Semicolon necessary under PPI 1.218 (https://github.com/adamkennedy/PPI/issues/70) my $dzt_double = $tzil->slurp_file('build/lib/DZT/Double.pm'); is($dzt_double, q{ package DZT::First 0.001 { say 'hello'; }; package DZT::Second 0.001 { say 'hello'; } 1; }, 'Added version to both packages.'); my $dzt_with_ver = $tzil->slurp_file('build/lib/DZT/WithVer.pm'); is($dzt_with_ver, q{ package DZT::WithVer 1.2 { } 1; }, 'Untouched already declared version.'); my $dzt_private = $tzil->slurp_file('build/lib/DZT/Private.pm'); is($dzt_private, q{ package DZT::Private { } 1; }, 'Untouched private package.'); done_testing;
17.269231
89
0.614699
ed9dd9f570b2f75e67853d032e64f444f5455a26
11,547
pm
Perl
cloud/microsoft/office365/teams/mode/usersactivity.pm
Le-Syl21/centreon-plugins
d6faacff279fd65a65de336eb3c3d5e53dbc83be
[ "Apache-2.0" ]
316
2015-01-18T20:37:21.000Z
2022-03-27T00:20:35.000Z
cloud/microsoft/office365/teams/mode/usersactivity.pm
Le-Syl21/centreon-plugins
d6faacff279fd65a65de336eb3c3d5e53dbc83be
[ "Apache-2.0" ]
2,333
2015-04-26T19:10:19.000Z
2022-03-31T15:35:21.000Z
cloud/microsoft/office365/teams/mode/usersactivity.pm
Le-Syl21/centreon-plugins
d6faacff279fd65a65de336eb3c3d5e53dbc83be
[ "Apache-2.0" ]
371
2015-01-18T20:37:23.000Z
2022-03-22T10:10:16.000Z
# # Copyright 2021 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package cloud::microsoft::office365::teams::mode::usersactivity; use base qw(centreon::plugins::templates::counter); use strict; use warnings; use Time::Local; sub custom_active_perfdata { my ($self, %options) = @_; my %total_options = (); if ($self->{instance_mode}->{option_results}->{units} eq '%') { $total_options{total} = $self->{result_values}->{total}; $total_options{cast_int} = 1; } if ($self->{result_values}->{report_date} =~ /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/) { $self->{output}->perfdata_add(label => 'perfdate', value => timelocal(0,0,12,$3,$2-1,$1-1900)); } $self->{output}->perfdata_add( label => 'active_users', nlabel => 'teams.users.active.count', value => $self->{result_values}->{active}, warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-' . $self->{thlabel}, %total_options), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-' . $self->{thlabel}, %total_options), unit => 'users', min => 0, max => $self->{result_values}->{total} ); } sub custom_active_threshold { my ($self, %options) = @_; my $threshold_value = $self->{result_values}->{active}; if ($self->{instance_mode}->{option_results}->{units} eq '%') { $threshold_value = $self->{result_values}->{prct_active}; } my $exit = $self->{perfdata}->threshold_check( value => $threshold_value, threshold => [ { label => 'critical-' . $self->{thlabel}, exit_litteral => 'critical' }, { label => 'warning-' . $self->{thlabel}, exit_litteral => 'warning' } ] ); return $exit; } sub custom_active_output { my ($self, %options) = @_; return sprintf( "Active users on %s : %d/%d (%.2f%%)", $self->{result_values}->{report_date}, $self->{result_values}->{active}, $self->{result_values}->{total}, $self->{result_values}->{prct_active} ); } sub custom_active_calc { my ($self, %options) = @_; $self->{result_values}->{active} = $options{new_datas}->{$self->{instance} . '_active'}; $self->{result_values}->{total} = $options{new_datas}->{$self->{instance} . '_total'}; $self->{result_values}->{report_date} = $options{new_datas}->{$self->{instance} . '_report_date'}; $self->{result_values}->{prct_active} = ($self->{result_values}->{total} != 0) ? $self->{result_values}->{active} * 100 / $self->{result_values}->{total} : 0; return 0; } sub prefix_global_output { my ($self, %options) = @_; return "Total "; } sub prefix_user_output { my ($self, %options) = @_; return "User '" . $options{instance_value}->{name} . "' "; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'active', type => 0 }, { name => 'global', type => 0, cb_prefix_output => 'prefix_global_output' }, { name => 'users', type => 1, cb_prefix_output => 'prefix_user_output', message_multiple => 'All users activity are ok' } ]; $self->{maps_counters}->{active} = [ { label => 'active-users', set => { key_values => [ { name => 'active' }, { name => 'total' }, { name => 'report_date' } ], closure_custom_calc => $self->can('custom_active_calc'), closure_custom_output => $self->can('custom_active_output'), closure_custom_threshold_check => $self->can('custom_active_threshold'), closure_custom_perfdata => $self->can('custom_active_perfdata') } } ]; $self->{maps_counters}->{global} = [ { label => 'total-team-chat', nlabel => 'teams.users.messages.team.total.count', set => { key_values => [ { name => 'team_chat' } ], output_template => 'Team Chat Message Count: %d', perfdatas => [ { label => 'total_team_chat', template => '%d', min => 0 } ] } }, { label => 'total-private-chat', nlabel => 'teams.users.messages.private.total.count', set => { key_values => [ { name => 'private_chat' } ], output_template => 'Private Chat Message Count: %d', perfdatas => [ { label => 'total_private_chat', template => '%d', min => 0 } ] } }, { label => 'total-call', nlabel => 'teams.users.call.total.count', set => { key_values => [ { name => 'call' } ], output_template => 'Call Count: %d', perfdatas => [ { label => 'total_call', template => '%d', min => 0 } ] } }, { label => 'total-meeting', nlabel => 'teams.users.meeting.total.count', set => { key_values => [ { name => 'meeting' } ], output_template => 'Meeting Count: %d', perfdatas => [ { label => 'total_meeting', template => '%d', min => 0 } ] } } ]; $self->{maps_counters}->{users} = [ { label => 'team-chat', nlabel => 'teams.users.messages.team.count', set => { key_values => [ { name => 'team_chat' }, { name => 'name' } ], output_template => 'Team Chat Message Count: %d', perfdatas => [ { label => 'team_chat', template => '%d', min => 0, label_extra_instance => 1, instance_use => 'name' } ] } }, { label => 'private-chat', nlabel => 'teams.users.messages.private.count', set => { key_values => [ { name => 'private_chat' }, { name => 'name' } ], output_template => 'Private Chat Message Count: %d', perfdatas => [ { label => 'private_chat', template => '%d', min => 0, label_extra_instance => 1, instance_use => 'name' } ] } }, { label => 'call', nlabel => 'teams.users.call.count', set => { key_values => [ { name => 'call' }, { name => 'name' } ], output_template => 'Call Count: %d', perfdatas => [ { label => 'call', template => '%d', min => 0, label_extra_instance => 1, instance_use => 'name' } ] } }, { label => 'meeting', nlabel => 'teams.users.meeting.count', set => { key_values => [ { name => 'meeting' }, { name => 'name' } ], output_template => 'Meeting Count: %d', perfdatas => [ { label => 'meeting', template => '%d', min => 0, label_extra_instance => 1, instance_use => 'name' } ] } } ]; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { "filter-user:s" => { name => 'filter_user' }, "units:s" => { name => 'units', default => '%' }, "filter-counters:s" => { name => 'filter_counters', default => 'active|total' } }); return $self; } sub manage_selection { my ($self, %options) = @_; $self->{active} = { active => 0, total => 0, report_date => '' }; $self->{global} = { team_chat => 0, private_chat => 0, call => 0, meeting => 0 }; $self->{users} = {}; my $results = $options{custom}->office_get_teams_activity(param => "period='D7'"); my $results_daily = []; if (scalar(@{$results})) { $self->{active}->{report_date} = @{$results}[0]->{'Report Refresh Date'}; $results_daily = $options{custom}->office_get_teams_activity(param => "date=" . $self->{active}->{report_date}); } foreach my $user (@{$results}, @{$results_daily}) { if (defined($self->{option_results}->{filter_user}) && $self->{option_results}->{filter_user} ne '' && $user->{'User Principal Name'} !~ /$self->{option_results}->{filter_user}/) { $self->{output}->output_add(long_msg => "skipping '" . $user->{'User Principal Name'} . "': no matching filter name.", debug => 1); next; } if ($user->{'Report Period'} != 1) { if (!defined($user->{'Last Activity Date'}) || ($user->{'Last Activity Date'} ne $self->{active}->{report_date})) { $self->{output}->output_add(long_msg => "skipping '" . $user->{'User Principal Name'} . "': no activity.", debug => 1); } $self->{active}->{total}++; next; } $self->{active}->{active}++; $self->{global}->{team_chat} += $user->{'Team Chat Message Count'}; $self->{global}->{private_chat} += $user->{'Private Chat Message Count'}; $self->{global}->{call} += $user->{'Call Count'}; $self->{global}->{meeting} += $user->{'Meeting Count'}; $self->{users}->{$user->{'User Principal Name'}}->{name} = $user->{'User Principal Name'}; $self->{users}->{$user->{'User Principal Name'}}->{team_chat} = $user->{'Team Chat Message Count'}; $self->{users}->{$user->{'User Principal Name'}}->{private_chat} = $user->{'Private Chat Message Count'}; $self->{users}->{$user->{'User Principal Name'}}->{call} = $user->{'Call Count'}; $self->{users}->{$user->{'User Principal Name'}}->{meeting} = $user->{'Meeting Count'}; } } 1; __END__ =head1 MODE Check users activity (reporting period over the last refreshed day). (See link for details about metrics : https://docs.microsoft.com/en-us/office365/admin/activity-reports/microsoft-teams-user-activity?view=o365-worldwide) =over 8 =item B<--filter-user> Filter users. =item B<--warning-*> Threshold warning. Can be: 'active-users', 'total-team-chat' (count), 'total-private-chat' (count), 'total-call' (count), 'total-meeting' (count), 'team-chat' (count), 'private-chat' (count), 'call' (count), 'meeting' (count). =item B<--critical-*> Threshold critical. Can be: 'active-users', 'total-team-chat' (count), 'total-private-chat' (count), 'total-call' (count), 'total-meeting' (count), 'team-chat' (count), 'private-chat' (count), 'call' (count), 'meeting' (count). =item B<--filter-counters> Only display some counters (regexp can be used). Example to hide per user counters: --filter-counters='total' (Default: 'active|total') =item B<--units> Unit of thresholds (Default: '%') ('%', 'count'). =back =cut
37.859016
162
0.537975
73d137e0c30609e974f9b4f6837792b8148a0eb0
1,575
t
Perl
v5.22/t/mro/isa_aliases.t
perl11/p5-coretests
65f340f49aea59bd666f1bf5c077a66004b51731
[ "Artistic-2.0" ]
1
2015-12-07T12:45:44.000Z
2015-12-07T12:45:44.000Z
v5.22/t/mro/isa_aliases.t
perl11/p5-coretests
65f340f49aea59bd666f1bf5c077a66004b51731
[ "Artistic-2.0" ]
null
null
null
v5.22/t/mro/isa_aliases.t
perl11/p5-coretests
65f340f49aea59bd666f1bf5c077a66004b51731
[ "Artistic-2.0" ]
null
null
null
#!./perl BEGIN { chdir 't' if -d 't'; require './test.pl'; set_up_inc('../lib'); } plan 13; @Foogh::ISA = "Bar"; *Phoogh::ISA = *Foogh::ISA; @Foogh::ISA = "Baz"; ok 'Foogh'->isa("Baz"), 'isa after another stash has claimed the @ISA via glob assignment'; ok 'Phoogh'->isa("Baz"), 'isa on the stash that claimed the @ISA via glob assignment'; ok !Foogh->isa("Bar"), '!isa when another stash has claimed the @ISA via glob assignment'; ok !Phoogh->isa("Bar"), '!isa on the stash that claimed the @ISA via glob assignment'; @Foogh::ISA = "Bar"; *Foogh::ISA = ["Baz"]; ok 'Foogh'->isa("Baz"), 'isa after glob-to-ref assignment when *ISA is shared'; ok 'Phoogh'->isa("Baz"), 'isa after glob-to-ref assignment on another stash when *ISA is shared'; ok !Foogh->isa("Bar"), '!isa after glob-to-ref assignment when *ISA is shared'; ok !Phoogh->isa("Bar"), '!isa after glob-to-ref assignment on another stash when *ISA is shared'; @Foo::ISA = "Bar"; *Phoo::ISA = \@Foo::ISA; @Foo::ISA = "Baz"; ok 'Foo'->isa("Baz"), 'isa after another stash has claimed the @ISA via ref-to-glob assignment'; ok 'Phoo'->isa("Baz"), 'isa on the stash that claimed the @ISA via ref-to-glob assignment'; ok !Foo->isa("Bar"), '!isa when another stash has claimed the @ISA via ref-to-glob assignment'; ok !Phoo->isa("Bar"), '!isa on the stash that claimed the @ISA via ref-to-glob assignment'; *Fooo::ISA = *Baro::ISA; @Fooo::ISA = "Bazo"; sub Bazo::ook { "Baz" } sub L::ook { "See" } Baro->ook; local *Fooo::ISA = ["L"]; is 'Baro'->ook, 'See', 'localised *ISA=$ref assignment';
28.636364
75
0.645079
73e2715c7bb7d95bb26ba0ac823116586bda758d
378
pl
Perl
unidecode/Unidecode.pl
nghiepit/anyascii
7b579df65aa5e81227df0410183c5408962a9b7c
[ "0BSD" ]
null
null
null
unidecode/Unidecode.pl
nghiepit/anyascii
7b579df65aa5e81227df0410183c5408962a9b7c
[ "0BSD" ]
null
null
null
unidecode/Unidecode.pl
nghiepit/anyascii
7b579df65aa5e81227df0410183c5408962a9b7c
[ "0BSD" ]
null
null
null
use strict; use warnings; use lib 'src/lib'; use Text::Unidecode; open(my $f, '>:raw', 'table.tsv') or die; binmode($f, ":utf8"); for (my $cp = hex('0xa0'); $cp <= hex('0xffff'); $cp++) { my $input = chr($cp); my $output = unidecode($input); if ($output ne '' and index($output, "\n") == -1 and index($output, "[?]") == -1) { print $f "$input\t$output\n"; } } close $f;
22.235294
84
0.555556
ede1990565c81dc18eee98a76e978013bb43cfe3
3,769
t
Perl
t/Account/Friends.t
AlliumCepa/webgui
235e1771b16e41ef4e85ddd4e61e22a26eddbe93
[ "Apache-1.1" ]
17
2015-02-10T15:32:59.000Z
2022-03-27T20:01:14.000Z
t/Account/Friends.t
AlliumCepa/webgui
235e1771b16e41ef4e85ddd4e61e22a26eddbe93
[ "Apache-1.1" ]
34
2015-01-07T22:42:00.000Z
2020-11-15T17:45:50.000Z
t/Account/Friends.t
AlliumCepa/webgui
235e1771b16e41ef4e85ddd4e61e22a26eddbe93
[ "Apache-1.1" ]
11
2015-02-06T22:06:10.000Z
2022-03-27T20:12:30.000Z
# vim:syntax=perl #------------------------------------------------------------------- # WebGUI is Copyright 2001-2012 Plain Black Corporation. #------------------------------------------------------------------- # Please read the legal notices (docs/legal.txt) and the license # (docs/license.txt) that came with this distribution before using # this software. #------------------------------------------------------------------ # http://www.plainblack.com info@plainblack.com #------------------------------------------------------------------ # This tests the operation of WebGUI::Account modules. You can use # as a base to test your own modules. use strict; use Test::More; use WebGUI::Test; # Must use this before any other WebGUI modules use WebGUI::Session; use WebGUI::Test::Mechanize; #---------------------------------------------------------------------------- # Init my $session = WebGUI::Test->session; #---------------------------------------------------------------------------- # Tests plan tests => 11; # Increment this number for each test you create #---------------------------------------------------------------------------- # Test the creation of WebGUI::Account::Friends # Can we load it? use_ok( "WebGUI::Account::Friends" ); SKIP: { # Not everyone has Test::Exception yet eval { require Test::Exception; import Test::Exception }; # Skip 1 test if Test::Exception couldn't be loaded skip 1, 'Test::Exception not found' if $@; throws_ok( sub { WebGUI::Account::Friends->new }, 'WebGUI::Error::InvalidObject', 'new() throws exception without session object' ); }; my $friends; # ok() tests booleans. assignment evaluates to the value assigned (it's how '$a = $b = 4' works) my $account; ok( $account = WebGUI::Account->new( $session ), "WebGUI::Account object created successfully" ); # Test $account->isa isa_ok( $account, "WebGUI::Account", 'Blessed into the right class' ); #---------------------------------------------------------------------------- # Test getUrl is( $account->getUrl, $session->url->page('op=account;module=;do='.$account->method), 'getUrl adds op, module, and do since no method has been set' ); is( $account->getUrl( 'foo=bar' ), $session->url->page( 'op=account;foo=bar' ), 'getUrl adds op if passed other parameters' ); is( $account->getUrl( 'op=account' ), $session->url->page( 'op=account' ), 'getUrl doesnt add op=account if already exists' ); #---------------------------------------------------------------------------- # Test the send friend request form # Start a session my $mech = WebGUI::Test::Mechanize->new( config => WebGUI::Test->file ); $mech->get_ok( '/' ); # Get our admin my $admin = WebGUI::User->new( $mech->session, "3" ); # Add a user who can be a friend for admin my $edgar_friendly = WebGUI::Test->user( username => 'edgarfriendly', ableToBeFriend => 1, publicProfile => 'all', ); $edgar_friendly = WebGUI::User->new( $mech->session, $edgar_friendly->getId ); # fix the session # Add a user who is not very nice my $simon_phoenix = WebGUI::Test->user( username => 'simonphoenix', ableToBeFriend => 0, publicProfile => 'none' ); $simon_phoenix = WebGUI::User->new( $mech->session, $simon_phoenix->getId ); # fix the session $mech->session->user({ user => $admin }); $mech->get_ok( "/?op=account;module=friends;do=sendFriendsRequest;uid=" . $edgar_friendly->getId, "get send request form" ); $mech->submit_form_ok( { form_name => "messageForm", fields => { }, # keep the defaults }, "submit send request form", ); my $friend = WebGUI::Friends->new($mech->session); ok( $friend->isInvited($edgar_friendly->getId), "invitation was sent" ); #vim:ft=perl
35.895238
124
0.555585
edaf4670fae367560a7bd367b0099d9f8cd0bc82
1,468
pl
Perl
tools/ktrace_malloc.pl
zhihui-slash2/slash2-next
d174a735f9860d2d9e31c47548bda67257400804
[ "0BSD" ]
null
null
null
tools/ktrace_malloc.pl
zhihui-slash2/slash2-next
d174a735f9860d2d9e31c47548bda67257400804
[ "0BSD" ]
null
null
null
tools/ktrace_malloc.pl
zhihui-slash2/slash2-next
d174a735f9860d2d9e31c47548bda67257400804
[ "0BSD" ]
null
null
null
#!/usr/bin/env perl # $Id$ # %ISC_START_LICENSE% # --------------------------------------------------------------------- # Copyright 2015-2016, Google, Inc. # Copyright 2012-2015, Pittsburgh Supercomputing Center # All rights reserved. # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the # above copyright notice and this permission notice appear in all # copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL # WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE # AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL # DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR # PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER # TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR # PERFORMANCE OF THIS SOFTWARE. # -------------------------------------------------------------------- # %END_LICENSE% #use warnings; #use strict; my %h; while (<>) { if ($_ =~ /(0x[a-f0-9]+) = malloc\(([0-9]+)\)/) { $h{$1} = $1; $h{$1}{sz} = $2; $h{$1}{freed} = 0; #print "malloc $1 $2\n"; } elsif ($_ =~ /free\((0x[a-f0-9]+)\)/) { $h{$1}{freed} = 1; #print "free $1\n"; } } foreach $k (keys %h) { if ($h{$k}{freed} eq 0) { print "$h{$k} $h{$k}{sz}\n"; } else { print "FREED $h{$k} $h{$k}{sz}\n"; } }
27.698113
71
0.590599
edd8263b31d7c714e13398486659b0cea9fa9776
3,103
pm
Perl
lib/DDG/Spice/SkyscannerFlightSearch.pm
remixz/zeroclickinfo-spice
0049a9f6adcf0144ff0ae6cb10b7c8a2e2bb98c6
[ "Apache-2.0" ]
null
null
null
lib/DDG/Spice/SkyscannerFlightSearch.pm
remixz/zeroclickinfo-spice
0049a9f6adcf0144ff0ae6cb10b7c8a2e2bb98c6
[ "Apache-2.0" ]
null
null
null
lib/DDG/Spice/SkyscannerFlightSearch.pm
remixz/zeroclickinfo-spice
0049a9f6adcf0144ff0ae6cb10b7c8a2e2bb98c6
[ "Apache-2.0" ]
null
null
null
package DDG::Spice::SkyscannerFlightSearch; # ABSTRACT: This IA will call Skyscanner's API to retrieve the cheapest flight prices to # different countries from the user's country use DDG::Spice; use strict; use warnings; use JSON::MaybeXS # No caching of results spice is_cached => 0; spice wrap_jsonp_callback => 1; # only enable for non-JSONP APIs (i.e. no &callback= parameter) spice from => '([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)'; spice to => 'http://partners.api.skyscanner.net/apiservices/browseroutes/v1.0/$1/$3/$2/$4/$5/anytime/anytime?apikey={{ENV{DDG_SPICE_SKYSCANNER_APIKEY}}}'; spice alt_to => { skyscanner_images => { to => 'https://gateway.skyscanner.net/travel-api/v1/entities?external_ids=$1&enhancers=images&nocache=true&apikey={{ENV{DDG_SPICE_SKYSCANNER_IMAGES_APIKEY}}}' } }; spice headers => { Accept => 'application/json' }; triggers startend => 'skyscanner'; # Load the list of currencies for each market my $currencies_raw = share('currencyCountryMapping.json')->slurp; my $currencies = decode_json($currencies_raw); # Load the list of countries and their ISO code my $countries_raw = share('countryCodes.json')->slurp; my $countries = decode_json($countries_raw); # Load the list of cities and their Skyscanner code (using Skyscanner code as IATA code is ambiguous in certain cases such as Berlin where the city # and one of the airports have the same code) my $cities_raw = share('cityCodes.json')->slurp; my $cities = decode_json($cities_raw); # Handle statement handle remainder => sub { my $origin = ""; my $destination = ""; # get user's location for the market if available (airline and travel agent prices depend on the market), if none default to 'US' my $market = $loc->country_code // "US"; # get language locale (replace DDG's '_' with '-' for Skyscanner compatibility), if none default to 'en-US' my $locale = $lang->locale // "en-US"; $locale =~ tr/_/-/; if ($locale eq "") { $locale = "en-US"; } # get currency from the json file using the market, if none default to USD my $currency = $currencies->{$market} // "USD"; if (index($_, 'to') != -1) { my @query = split(/\s+to\s+/, $_); $origin = $query[0]; $destination = $query[1]; } else { $origin = $_; } # strip 'flight(s) from' to allow more flexible queries and remove left trailing space $origin =~ s/\b(flight(?:s)?|from)\b//g; $origin =~ s/^\s+//; #print "\n\n**** User query *****"; #print "\nOrigin: " . $origin; #print "\nDestination: " . $destination; #print "\n*********************\n\n"; # determine origin country or city (use lowercase), if no match use user's country $origin = $countries->{lc($origin)} // $cities->{lc($origin)} // $market; # determine destination country or city (use lowercase), if no match use 'anywhere' $destination = $countries->{lc($destination)} // $cities->{lc($destination)} // "anywhere"; return $market, $locale, $currency, $origin, $destination; }; 1;
36.505882
166
0.642926
edee70cf067a757fccca25568df938aae2f13bfb
212
pl
Perl
examples/ex3.pl
michal-josef-spacek/Error-Pure-Always
07240fcc1ac2ba2de645b3f4bb8a28475dff891b
[ "BSD-2-Clause" ]
null
null
null
examples/ex3.pl
michal-josef-spacek/Error-Pure-Always
07240fcc1ac2ba2de645b3f4bb8a28475dff891b
[ "BSD-2-Clause" ]
null
null
null
examples/ex3.pl
michal-josef-spacek/Error-Pure-Always
07240fcc1ac2ba2de645b3f4bb8a28475dff891b
[ "BSD-2-Clause" ]
null
null
null
#!/usr/bin/env perl use strict; use warnings; use Error::Pure::Always; # Set error type. $Error::Pure::TYPE = 'AllError'; # Error. die '1'; # Output something like: # ERROR: 1 # main err path_to_script 12
13.25
32
0.665094
ed6e9c0604f5812f33716ae7be26163c568a412f
785
pm
Perl
lib/PanLex/Server.pm
longnow/panlex-tools
1b10fa140af96078c7c909cd10f3f3c05f641671
[ "MIT" ]
8
2015-11-02T22:55:24.000Z
2018-05-27T22:11:40.000Z
lib/PanLex/Server.pm
longnow/panlex-tools
1b10fa140af96078c7c909cd10f3f3c05f641671
[ "MIT" ]
3
2021-03-31T19:12:43.000Z
2021-12-13T20:03:51.000Z
lib/PanLex/Server.pm
longnow/panlex-tools
1b10fa140af96078c7c909cd10f3f3c05f641671
[ "MIT" ]
2
2016-07-11T18:00:18.000Z
2019-04-23T14:41:52.000Z
package PanLex::Server; use strict; use warnings 'FATAL', 'all'; use utf8; use Mojo::Base 'Mojolicious'; use PanLex::Normalize; use PanLex::Util; sub startup { my $app = shift; $app->routes->post('/normalize/:method')->to('main#normalize'); $app->routes->post('/util/:method')->to('main#util'); } package PanLex::Server::Controller::Main; use Mojo::Base 'Mojolicious::Controller'; sub normalize { my $c = shift; my $method = $c->param('method'); my $args = $c->req->json; my $result = PanLex::Normalize->$method(@$args); $c->render(json => $result); } sub util { my $c = shift; my $method = $c->param('method'); my $args = $c->req->json; my $result = PanLex::Util->can($method)->(@$args); $c->render(json => $result); } 1;
19.625
67
0.598726
ed66a55790455a452f8777b92e1818d2a0286bbf
415
t
Perl
xt/release/99_pod_coverage.t
TrackingSoft/Redis-CappedCollection
3131861abb3eeba4cf2aed835e74783da24fb6a4
[ "Artistic-1.0-Perl" ]
null
null
null
xt/release/99_pod_coverage.t
TrackingSoft/Redis-CappedCollection
3131861abb3eeba4cf2aed835e74783da24fb6a4
[ "Artistic-1.0-Perl" ]
1
2020-02-15T21:45:36.000Z
2020-02-19T03:30:33.000Z
xt/release/99_pod_coverage.t
TrackingSoft/Redis-CappedCollection
3131861abb3eeba4cf2aed835e74783da24fb6a4
[ "Artistic-1.0-Perl" ]
null
null
null
#!/usr/bin/perl -w use 5.010; use strict; use warnings; use lib 'lib'; use Test::More; eval 'use Test::Pod::Coverage'; ## no critic plan skip_all => "Test::Pod::Coverage required for testing POD coverage" if $@; plan tests => 1; pod_coverage_ok( "Redis::CappedCollection", { also_private => [ qr/^BUILD$/ ], }, "Redis::CappedCollection, with 'BUILD' function as private", );
20.75
81
0.621687
edeedca9dbb79bba39ff87d7f1c01e52bd71ef3a
3,230
pm
Perl
hardware/pdu/clever/snmp/mode/psusage.pm
garnier-quentin/centreon-plugins
51c16b4419d640709d3352a260e4cd63cd96db14
[ "Apache-2.0" ]
null
null
null
hardware/pdu/clever/snmp/mode/psusage.pm
garnier-quentin/centreon-plugins
51c16b4419d640709d3352a260e4cd63cd96db14
[ "Apache-2.0" ]
null
null
null
hardware/pdu/clever/snmp/mode/psusage.pm
garnier-quentin/centreon-plugins
51c16b4419d640709d3352a260e4cd63cd96db14
[ "Apache-2.0" ]
null
null
null
# # Copyright 2018 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package hardware::pdu::clever::snmp::mode::psusage; use base qw(centreon::plugins::templates::counter); use strict; use warnings; sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'global', type => 0 }, ]; $self->{maps_counters}->{global} = [ { label => 'power', set => { key_values => [ { name => 'power' } ], output_template => 'Input power : %s W', perfdatas => [ { label => 'power', value => 'power_absolute', template => '%s', unit => 'W', min => 0 }, ], } }, { label => 'current', set => { key_values => [ { name => 'current' } ], output_template => 'Current : %s A', perfdatas => [ { label => 'current', value => 'current_absolute', template => '%s', unit => 'A', min => 0 }, ], } }, { label => 'voltage', set => { key_values => [ { name => 'voltage' } ], output_template => 'Voltage : %s V', perfdatas => [ { label => 'voltage', value => 'voltage_absolute', template => '%s', unit => 'V', min => 0 }, ], } }, ]; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '1.0'; $options{options}->add_options(arguments => { }); return $self; } my $oid_current = '.1.3.6.1.4.1.30966.1.2.1.6.0'; my $oid_voltage = '.1.3.6.1.4.1.30966.1.2.1.9.0'; sub manage_selection { my ($self, %options) = @_; my $result = $options{snmp}->get_leef(oids => [ $oid_current, $oid_voltage ], nothing_quit => 1); $self->{global} = { current => $result->{$oid_current}, voltage => $result->{$oid_voltage}, power => $result->{$oid_current} * $result->{$oid_voltage} }; } 1; __END__ =head1 MODE Check power source usage. =over 8 =item B<--warning-*> Threshold warning. Can be: 'current', 'power', 'voltage'. =item B<--critical-*> Threshold critical. Can be: 'current', 'power', 'voltage'. =back =cut
28.584071
96
0.517028
edd3c2ad771b0a1cf4b26a9b8faf705fbfc92439
2,657
al
Perl
Apps/CZ/BankingDocumentsLocalization/app/Src/Reports/IssBankStatement.Report.al
waldo1001/ALAppExtensions
935155845bf45b631d1c34b6bcd5aec54308d50f
[ "MIT" ]
337
2019-05-07T06:04:40.000Z
2022-03-31T10:07:42.000Z
Apps/CZ/BankingDocumentsLocalization/app/Src/Reports/IssBankStatement.Report.al
waldo1001/ALAppExtensions
935155845bf45b631d1c34b6bcd5aec54308d50f
[ "MIT" ]
14,850
2019-05-07T06:04:27.000Z
2022-03-31T19:53:28.000Z
Apps/CZ/BankingDocumentsLocalization/app/Src/Reports/IssBankStatement.Report.al
waldo1001/ALAppExtensions
935155845bf45b631d1c34b6bcd5aec54308d50f
[ "MIT" ]
374
2019-05-09T10:08:14.000Z
2022-03-31T17:48:32.000Z
report 31283 "Iss. Bank Statement CZB" { DefaultLayout = RDLC; RDLCLayout = './Src/Reports/IssBankStatement.rdl'; Caption = 'Issued Bank Statement'; dataset { dataitem("Iss. Bank Statement Header CZB"; "Iss. Bank Statement Header CZB") { CalcFields = Amount; RequestFilterFields = "No.", "Bank Account No."; column(COMPANYNAME; CompanyProperty.DisplayName()) { } column(ReportFilter; GetFilters()) { } column(IssBankStatementHeader_No; "No.") { IncludeCaption = true; } column(IssBankStatementHeader_BankAccountNo; "Bank Account No.") { IncludeCaption = true; } column(IssBankStatementHeader_AccountNo; "Account No.") { IncludeCaption = true; } column(IssBankStatementHeader_DocumentDate; "Document Date") { IncludeCaption = true; } column(IssBankStatementHeader_CurrencyCode; "Currency Code") { IncludeCaption = true; } column(IssBankStatementHeader_Amount; Amount) { IncludeCaption = true; } dataitem("Iss. Bank Statement Line CZB"; "Iss. Bank Statement Line CZB") { DataItemLink = "Bank Statement No." = field("No."); DataItemTableView = sorting("Bank Statement No.", "Line No."); column(IssBankStatementLine_Description; Description) { IncludeCaption = true; } column(IssBankStatementLine_AccountNo; "Account No.") { IncludeCaption = true; } column(IssBankStatementLine_VariableSymbol; "Variable Symbol") { IncludeCaption = true; } column(IssBankStatementLine_ConstantSymbol; "Constant Symbol") { IncludeCaption = true; } column(IssBankStatementLine_SpecificSymbol; "Specific Symbol") { IncludeCaption = true; } column(IssBankStatementLine_Amount; Amount) { IncludeCaption = true; } } } } labels { ReportLbl = 'Bank Statement'; PageLbl = 'Page'; TotalAmountLbl = 'Total Amount'; } }
32.402439
84
0.485886
edd3d9e94e4c65ca9805a8ad376a83ef7d761504
5,768
t
Perl
t/Object/Table-has_one.t
houseabsolute/Fey-ORM
af4bb010413ec46474da22d9e85938d46c94f462
[ "Artistic-1.0" ]
null
null
null
t/Object/Table-has_one.t
houseabsolute/Fey-ORM
af4bb010413ec46474da22d9e85938d46c94f462
[ "Artistic-1.0" ]
null
null
null
t/Object/Table-has_one.t
houseabsolute/Fey-ORM
af4bb010413ec46474da22d9e85938d46c94f462
[ "Artistic-1.0" ]
null
null
null
use strict; use warnings; use Test::More 0.88; use lib 't/lib'; use Fey::ORM::Test; use Fey::Literal::String; use Fey::Placeholder; use Fey::Test; Fey::ORM::Test::define_live_classes(); Fey::ORM::Test::insert_user_data(); ## no critic (Modules::ProhibitMultiplePackages) { package Message; use Fey::ORM::Table; has_one Schema->Schema()->table('User'); has_one 'parent_message' => ( table => Schema->Schema()->table('Message') ); } { my $parent = Message->insert( message => 'parent body', user_id => 1, ); is( $parent->user()->user_id(), 1, 'user() for parent message returns expected user object' ); is( $parent->user(), $parent->user(), 'user() attribute is cached' ); is( $parent->parent_message(), undef, 'parent message has no parent itself' ); my $child = Message->insert( message => 'child body', parent_message_id => $parent->message_id(), user_id => 1, ); my $parent_from_attr = $child->parent_message(); is( $parent_from_attr->message_id(), $parent->message_id(), 'parent_message() attribute created via has_one returns expected message' ); } { package Message; __PACKAGE__->meta()->remove_has_one('user'); has_one 'user' => ( table => Schema->Schema()->table('User'), cache => 0, ); } { my $message = Message->insert( message => 'message body', user_id => 1, ); is( $message->user()->user_id(), 1, 'user() for parent message returns expected user object' ); isnt( $message->user(), $message->user(), 'user() attribute is not cached' ); } { my $schema = Schema->Schema(); $schema->remove_foreign_key($_) for $schema->foreign_keys_between_tables( 'Message', 'User' ); $schema->remove_foreign_key($_) for $schema->foreign_keys_between_tables( 'Message', 'Message' ); # These definitions invert the source/target labeling of the # corresponding FKs in Fey::Test. The goal is to test that has_one # figures out the proper "direction" of the FK. my $fk1 = Fey::FK->new( source_columns => [ $schema->table('User')->column('user_id') ], target_columns => [ $schema->table('Message')->column('user_id') ], ); my $fk2 = Fey::FK->new( source_columns => [ $schema->table('Message')->column('message_id') ], target_columns => [ $schema->table('Message')->column('parent_message_id') ], ); $schema->add_foreign_key($_) for $fk1, $fk2; package Message; __PACKAGE__->meta()->remove_has_one('user'); has_one $schema->table('User'); __PACKAGE__->meta()->remove_has_one('parent_message'); has_one 'parent_message' => ( table => $schema->table('Message') ); } inverted_fk_tests(); { # This next set of tests is the same as the last, except this time we # explicitly provide the Fey::FK object, and test that it gets inverted. package Message; my $schema = Schema->Schema(); __PACKAGE__->meta()->remove_has_one('user'); my ($fk) = $schema->foreign_keys_between_tables( $schema->tables( 'Message', 'User' ) ); has_one user => ( table => $schema->table('User'), fk => $fk, ); __PACKAGE__->meta()->remove_has_one('parent_message'); ($fk) = $schema->foreign_keys_between_tables( $schema->tables( 'Message', 'Message' ) ); has_one 'parent_message' => ( table => $schema->table('Message'), fk => $fk, ); } inverted_fk_tests(); { package User; use Fey::ORM::Table; my $select = Schema->SQLFactoryClass()->new_select() ->select( Schema->Schema()->table('Message') ) ->from( Schema->Schema()->table('Message') )->where( Schema->Schema()->table('Message')->column('user_id'), '=', Fey::Placeholder->new() )->order_by( Schema->Schema()->table('Message')->column('message_id'), 'DESC' )->limit(1); has_one 'most_recent_message' => ( table => Schema->Schema()->table('Message'), select => $select, bind_params => sub { $_[0]->user_id() }, ); } { my $user = User->new( user_id => 1 ); my $message = $user->most_recent_message(); isa_ok( $message, 'Message', 'most_recent_message() returns Message object' ); my ($most_recent_message_id) = ( Schema->DBIManager()->default_source()->dbh() ->selectcol_arrayref('SELECT MAX(message_id) FROM Message') ) ->[0]; is( $message->message_id(), $most_recent_message_id, 'message object is the most recently inserted message' ); is( $message->user_id(), $user->user_id(), 'message belongs to the user' ); } sub inverted_fk_tests { local $Test::Builder::Level = $Test::Builder::Level + 1; my $parent = Message->insert( message => 'parent body', user_id => 1, ); is( $parent->user()->user_id(), 1, 'user() for parent message returns expected user object' ); is( $parent->parent_message(), undef, 'parent message has no parent itself' ); my $child = Message->insert( message => 'child body', parent_message_id => $parent->message_id(), user_id => 1, ); my $parent_from_attr = $child->parent_message(); is( $parent_from_attr->message_id(), $parent->message_id(), 'parent_message() attribute created via has_one returns expected message' ); } done_testing();
23.834711
81
0.570562
ede949a81a4643148c40abc43666f2f9331b0f0b
3,400
pl
Perl
examples/inference/arithm_R.pl
JanWielemaker/cplint-on-swish
151a60949d25a2c7ba4b41aa0204eea212e3fd6f
[ "BSD-2-Clause" ]
9
2015-06-16T00:19:48.000Z
2020-07-13T15:03:29.000Z
examples/inference/arithm_R.pl
logicmoo/swish
3e26a957b5c7c899a7e535b12c1fc32ee2b48b99
[ "BSD-2-Clause" ]
2
2016-11-15T17:47:13.000Z
2017-03-03T10:38:13.000Z
examples/inference/arithm_R.pl
logicmoo/swish
3e26a957b5c7c899a7e535b12c1fc32ee2b48b99
[ "BSD-2-Clause" ]
6
2016-06-07T11:56:29.000Z
2020-07-13T12:57:19.000Z
/* Random arithmetic function from http://forestdb.org/models/arithmetic.html The model generatively defines a random arithmetic function. The problem is to predict the value returned by the function given one or two couples of input-output, i.e., to compute a conditional probability. Translated from the Church functional probabilistic programming language. Sampling is necessary as queries have an infinite number of explanations. Both rejection sampling and Metropolis/Hastings can be applied. */ :- use_module(library(mcintyre)). :- use_module(library(cplint_r)). :- mc. :- begin_lpad. eval(X,Y):- random_fn(X,0,F), Y is F. op(L,+):0.5;op(L,-):0.5. random_fn(X,L,F):- comb(L), random_fn(X,l(L),F1), random_fn(X,r(L),F2), op(L,Op), F=..[Op,F1,F2]. random_fn(X,L,F):- \+ comb(L), base_random_fn(X,L,F). comb(_):0.3. base_random_fn(X,L,X):- identity(L). base_random_fn(_X,L,C):- \+ identity(L), random_const(L,C). identity(_):0.5. random_const(_,C):discrete(C,[0:0.1,1:0.1,2:0.1,3:0.1,4:0.1, 5:0.1,6:0.1,7:0.1,8:0.1,9:0.1]). :- end_lpad. /** <examples> ?- mc_mh_sample(eval(2,4),eval(1,3),100,P, [mix(100),lag(3),successes(T),failures(F)]). % perform Metropolis Hastings sampling of eval(2,Y) given that % eval(1,3) is true (100 samples, 100 mixing samples, lag 3) % expected result % T = 17, % F = 83, % P = 0.17. ?- mc_mh_sample(eval(2,4),eval(1,3),100,P, [lag(3),successes(T),failures(F)]). % perform Metropolis Hastings sampling of eval(2,Y) given that % eval(1,3) is true % expected result % T = 17, % F = 83, % P = 0.17. ?- mc_mh_sample(eval(2,4),(eval(0,2),eval(1,3)),100,P, [lag(3),successes(T),failures(F)]). % perform Metropolis Hastings sampling of eval(2,Y) given that % eval(0,2) and eval(1,3) are true % expected result % T = 100, % F = 0, % P = 1. ?- mc_rejection_sample(eval(2,4),eval(1,3),100,P, [successes(T),failures(F)]). % perform rejection sampling of eval(2,4) given that eval(1,3) is true % expected result % T = 10, % F = 90, % P = 0.1. ?- mc_mh_sample_arg(eval(2,Y),(eval(0,2),eval(1,3)),100,Y,V, [mix(100),lag(3)]). % sample arg Y of eval(2,Y) given that % eval(0,2) and eval(1,3) are true % Sample using Metropolis Hastings % expected result % V = [[4]-100]. ?- mc_mh_sample_arg(eval(2,Y),(eval(0,2),eval(1,3)),100,Y,V, [mix(100),lag(3)]),argbar_r(V). ?- mc_mh_sample_arg(eval(2,Y),eval(1,3),100,Y,V, [mix(100),lag(3)]). % sample arg Y of eval(2,Y) given that % eval(1,3) is true % Sample using Metropolis Hastings % expected result % V = [[3]-52, [6]-20, [5]-16, [4]-12] ?- mc_mh_sample_arg(eval(2,Y),eval(1,3),100,Y,V, [mix(100),lag(3)]),argbar_r(V). ?- mc_rejection_sample_arg(eval(2,Y),eval(1,3),100,Y,V). % sample argument Y of eval(2,Y) given that % eval(1,3) is true % Sample using rejection sampling % expected result % V = [[3]-79, [4]-8, [6]-8, [2]-5]. ?- mc_rejection_sample_arg(eval(2,Y),eval(1,3),100,Y,V),argbar_r(V). ?- mc_expectation(eval(2,Y),100,Y,E). % what is the expected value of Y in eval(2,Y)? % expected result % E = 3.48 ?- mc_mh_expectation(eval(2,Y),eval(1,3),100,Y,E, [mix(100),lag(3)]). % what is the expected value of Y in eval(2,Y) given that eval(1,3) is true? % expected result % E = 3.52 ?- mc_rejection_expectation(eval(2,Y),eval(1,3),100,Y,E). % what is the expected value of Y in eval(2,Y) given that eval(1,3) is true? % expected result % E = 3.06 */
24.460432
76
0.655
ed19776563fefbf50cc248e7fd1699c1e58f1b30
4,060
pm
Perl
source/lib/StreamGraph/View/BorderFactory.pm
grandchild/streamgraph
57893740a7bf460e3d66cd1e8fd2777d5b726cc4
[ "MIT" ]
null
null
null
source/lib/StreamGraph/View/BorderFactory.pm
grandchild/streamgraph
57893740a7bf460e3d66cd1e8fd2777d5b726cc4
[ "MIT" ]
null
null
null
source/lib/StreamGraph/View/BorderFactory.pm
grandchild/streamgraph
57893740a7bf460e3d66cd1e8fd2777d5b726cc4
[ "MIT" ]
null
null
null
package StreamGraph::View::BorderFactory; our $VERSION = '0.000001'; use warnings; use strict; use Carp; use StreamGraph::View::Border::Ellipse; use StreamGraph::View::Border::Rectangle; use StreamGraph::View::Border::RoundedRect; use StreamGraph::View::ArgUtils; use List::Util; use Glib ':constants'; sub new { my $class = shift(@_); my @attributes = @_; my $self = {}; bless $self, $class; my %attributes = @attributes; args_valid(\%attributes, qw(view fill_color_gdk outline_color_gdk)); args_required(\%attributes, qw(view)); args_store($self, \%attributes); if (!($self->{view}->isa('StreamGraph::View'))) { carp "Invalid StreamGraph::View argument.\n"; } arg_default($self, "fill_color_gdk", Gtk2::Gdk::Color->parse('white')); arg_default($self, "outline_color_gdk", Gtk2::Gdk::Color->parse('gray')); return $self; } sub create_border { my ($self, @attributes) = @_; my %attributes = @attributes; args_valid(\%attributes, qw(type content fill_color_gdk outline_color_gdk)); args_required(\%attributes, qw(type content)); my $content = $attributes{content}; if (!$content->isa('StreamGraph::View::Content')) { croak "Invalid content. 'content' parameter must be a 'StreamGraph::View::Content'.\n"; } my $type = $attributes{type}; my $fill_color_gdk = (defined $attributes{fill_color_gdk}) ? $attributes{fill_color_gdk} : $self->{fill_color_gdk}; my $outline_color_gdk = (defined $attributes{outline_color_gdk}) ? $attributes{outline_color_gdk} : $self->{outline_color_gdk}; if ($type eq 'StreamGraph::View::Border::Ellipse') { return StreamGraph::View::Border::Ellipse->new( group=>$self->{view}->root, content=>$content, fill_color_gdk=>$fill_color_gdk, outline_color_gdk=>$outline_color_gdk); } if ($type eq 'StreamGraph::View::Border::RoundedRect') { return StreamGraph::View::Border::RoundedRect->new( group=>$self->{view}->root, content=>$content, fill_color_gdk=>$fill_color_gdk, outline_color_gdk=>$outline_color_gdk); } if ($type eq 'StreamGraph::View::Border::Rectangle') { return StreamGraph::View::Border::Rectangle->new( group=>$self->{view}->root, content=>$content, fill_color_gdk=>$fill_color_gdk, outline_color_gdk=>$outline_color_gdk); } croak "Unexpected border type: $type\n"; } 1; # Magic true value required at end of module __END__ =head1 StreamGraph::View::BorderFactory This factory makes borders for mind map view items. The following types of borders are currently supported: StreamGraph::View::Border::RoundedRect - A rounded rectangle border. StreamGraph::View::Border::Rectangle - A rectangular border. StreamGraph::View::Border::Ellipse - An ellipse shaped border. =head2 Properties =over =item 'view' (StreamGraph::View) The canvas on which the border will be drawn. =item 'type' (string) The type of border to draw (see above). =item 'content' (StreamGraph::View::Content) The content to be placed in the border. =item 'fill_color_gdk' (Gtk2::Gdk::Color) The color of the interior of the border. =item 'outline_color_gdk' (Gtk2::Gdk::Color) The color of the border outline. =back =head2 Methods =over =item C<new (view=>$view, ...)> Constructor for this factory. Pass in a StreamGraph::View argument. =item C<create_border (type=>$border_type, content=>$content, ...)> Creates a new StreamGraph::View::Border border with the specified content. =back =head1 DIAGNOSTICS =over =item C<Invalid StreamGraph::View argument.> The 'view' parameter must be a StreamGraph::View. =item C<Invalid content. 'content' parameter must be 'StreamGraph::View::Content')> The only content types that subclass 'StreamGraph::View::Content' are permitted. =item C<Unexpected border type: $type> Only the border types listed above are currently supported. =back
22.430939
88
0.677833
edcc1eae6386ba3b5246c7f65532ae2e73919b68
3,675
pm
Perl
misc-scripts/xref_mapping/XrefParser/MGIParser.pm
sgiorgetti/ensembl
ff90d0812cc0e64cc55c74a759575db351c5217b
[ "Apache-2.0" ]
1
2021-09-27T11:01:06.000Z
2021-09-27T11:01:06.000Z
misc-scripts/xref_mapping/XrefParser/MGIParser.pm
sgiorgetti/ensembl
ff90d0812cc0e64cc55c74a759575db351c5217b
[ "Apache-2.0" ]
1
2021-09-23T13:46:54.000Z
2021-09-23T13:46:54.000Z
misc-scripts/xref_mapping/XrefParser/MGIParser.pm
sgiorgetti/ensembl
ff90d0812cc0e64cc55c74a759575db351c5217b
[ "Apache-2.0" ]
null
null
null
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2022] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut =head1 NAME XrefParser::MGIParser =head1 DESCRIPTION A parser class to parse the MGI (official) source, creating a DIRECT xref between MGI accession and ensembl mouse gene stable id ENSMUSG* -species = mus_musculus -species_id = 10090 -data_uri = http://www.informatics.jax.org/downloads/reports/MRK_ENSEMBL.rpt -file_format = TSV -columns = [accession symbol name position chrom ens_gene_stableid] ##ignore other columns =head1 SYNOPSIS my $parser = XrefParser::MGIParser->new($db->dbh); $parser->run({ source_id => 55, species_id => 10090, files => ["MRK_ENSEMBL.rpt"], }); =cut package XrefParser::MGIParser; use strict; use warnings; use Carp; use Text::CSV; use parent qw( XrefParser::BaseParser ); =head2 run Arg [1] : HashRef standard list of arguments from ParseSource Example : $mgi_parser->run({ ... }); Description: Runs the MGIParser Return type: 0 on success Exceptions : throws on all processing errors Caller : ParseSource in the xref pipeline =cut sub run { my ( $self, $ref_arg ) = @_; my $source_id = $ref_arg->{source_id}; my $species_id = $ref_arg->{species_id}; my $files = $ref_arg->{files}; my $verbose = $ref_arg->{verbose} // 0; my $dbi = $ref_arg->{dbi} // $self->dbi; if ( ( !defined $source_id ) or ( !defined $species_id ) or ( !defined $files ) ) { confess 'Need to pass source_id, species_id and files as pairs'; } my $file = @{$files}[0]; my $file_io = $self->get_filehandle($file); if ( !defined $file_io ) { confess "Could not open $file\n"; } #synonyms; move this to SynonymAdaptor?! my $syn_hash = $self->get_ext_synonyms( 'MGI', $dbi ); #Init input file my $input_file = Text::CSV->new( { sep_char => "\t", empty_is_undef => 1, strict => 1, allow_loose_quotes => 1, } ) or confess "Cannot use file $file: " . Text::CSV->error_diag(); my $count = 0; my $syn_count = 0; while ( my $data = $input_file->getline($file_io) ) { my $acc = $data->[0]; my $ensid = $data->[5]; my $xref_id = $self->add_xref( { acc => $acc, version => 0, label => $data->[1], desc => $data->[2], source_id => $source_id, species_id => $species_id, info_type => 'DIRECT', dbi => $dbi, } ); $self->add_direct_xref( $xref_id, $ensid, 'Gene', undef, $dbi ); if ( exists $syn_hash->{$acc} ) { foreach my $syn ( @{ $syn_hash->{$acc} } ) { $self->add_to_syn( $acc, $source_id, $syn, $species_id, $dbi ); $syn_count += 1; } } $count += 1; } $input_file->eof || confess "Error parsing file $file: " . $input_file->error_diag(); $file_io->close(); if ($verbose) { print "$count direct MGI xrefs added\n"; print $syn_count. " synonyms added\n"; } return 0; } 1;
25.880282
100
0.627755
edc0dd2f44b9e9c166a3b2096b0c6977c1091657
2,878
al
Perl
Modules/System/Email/src/Test Email/EmailTestMail.Codeunit.al
MiguelMercadoActual/ALAppExtensions
97ee3823053eb32fa7e38dc3d1e7a89bdcca8d7b
[ "MIT" ]
337
2019-05-07T06:04:40.000Z
2022-03-31T10:07:42.000Z
Modules/System/Email/src/Test Email/EmailTestMail.Codeunit.al
MiguelMercadoActual/ALAppExtensions
97ee3823053eb32fa7e38dc3d1e7a89bdcca8d7b
[ "MIT" ]
14,850
2019-05-07T06:04:27.000Z
2022-03-31T19:53:28.000Z
Modules/System/Email/src/Test Email/EmailTestMail.Codeunit.al
MiguelMercadoActual/ALAppExtensions
97ee3823053eb32fa7e38dc3d1e7a89bdcca8d7b
[ "MIT" ]
374
2019-05-09T10:08:14.000Z
2022-03-31T17:48:32.000Z
// ------------------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // ------------------------------------------------------------------------------------------------ /// <summary> /// Sends a test email to a specified account. /// </summary> codeunit 8887 "Email Test Mail" { TableNo = "Email Account"; var TestEmailChoiceTxt: Label 'Choose the email address that should receive a test email message:'; TestEmailSubjectTxt: Label 'Test Email Message'; TestEmailBodyTxt: Label '<body><p style="font-family:Verdana,Arial;font-size:10pt"><b>The user %1 sent this message to test their email settings. You do not need to reply to this message.</b></p><p style="font-family:Verdana,Arial;font-size:9pt"><b>Sent through connector:</b> %2<BR></p></body>', Comment = '%1 is an email address, such as user@domain.com; %2 is the name of a connector, such as SMTP;'; TestEmailSuccessMsg: Label 'Test email has been sent to %1.\Check your email for messages to make sure that the email was delivered successfully.', Comment = '%1 is an email address.'; TestEmailFailedMsg: Label 'An error has occured while sending the email, please look at the Outbox to find the error.'; TestEmailOtherTxt: Label 'Other...'; trigger OnRun() var Email: Codeunit Email; Message: Codeunit "Email Message"; EmailUserSpecifiedAddress: Page "Email User-Specified Address"; EmailRecipient: Text; EmailChoices: Text; SelectedEmailChoice: Integer; EmailBody: Text; EmailChoicesSubLbl: Label '%1,%2', Locked = true; begin EmailChoices := StrSubstNo(EmailChoicesSubLbl, Rec."Email Address", TestEmailOtherTxt); SelectedEmailChoice := StrMenu(EmailChoices, 2, TestEmailChoiceTxt); if SelectedEmailChoice = 0 then exit; if SelectedEmailChoice = 1 then EmailRecipient := Rec."Email Address" else if EmailUserSpecifiedAddress.RunModal() = Action::OK then EmailRecipient := EmailUserSpecifiedAddress.GetEmailAddress() else exit; #if not CLEAN17 Email.OnGetTestEmailBody(Rec.Connector, EmailBody); #endif Email.OnGetBodyForTestEmail(Rec.Connector, Rec."Account Id", EmailBody); if EmailBody = '' then EmailBody := StrSubstNo(TestEmailBodyTxt, UserId(), Rec.Connector); Message.Create(EmailRecipient, TestEmailSubjectTxt, EmailBody, true); if Email.Send(Message, Rec) then Message(StrSubstNo(TestEmailSuccessMsg, EmailRecipient)) else Error(TestEmailFailedMsg); end; }
47.966667
411
0.624392
eda5cf82be6051d81930641e357cb425d6e62f7c
5,868
al
Perl
Apps/W1/MSWalletPayments/app/src/pages/MerchSetupInv.Page.al
manjulchauhan/ALAppExtensions
3f2f1d6e5337188b1af9c0275420f1c1de036a7f
[ "MIT" ]
127
2018-04-17T18:03:03.000Z
2019-05-06T18:54:17.000Z
Apps/W1/MSWalletPayments/app/src/pages/MerchSetupInv.Page.al
snu-development/ALAppExtensions
371a27fe48483be776642dde19483a87ae27289c
[ "MIT" ]
2,279
2018-09-12T12:01:49.000Z
2019-05-06T13:59:35.000Z
Apps/W1/MSWalletPayments/app/src/pages/MerchSetupInv.Page.al
snu-development/ALAppExtensions
371a27fe48483be776642dde19483a87ae27289c
[ "MIT" ]
41
2018-05-17T11:19:52.000Z
2019-04-30T17:30:38.000Z
#if not CLEAN20 page 1087 "MS - Wallet Merch. Setup Inv" { ObsoleteState = Pending; ObsoleteReason = 'MS Wallet have been deprecated'; ObsoleteTag = '20.0'; Caption = 'Set up Microsoft Pay Payments'; DataCaptionExpression = ''; DeleteAllowed = false; InsertAllowed = false; PageType = Card; SourceTable = "MS - Wallet Merchant Account"; layout { area(content) { group(General) { InstructionalText = 'With Microsoft Pay Payments, your customers can pay you using credit cards and PayPal.'; field(LogoControlDetails; MSWalletMerchantTemplate.Logo) { ApplicationArea = Basic, Suite; Caption = 'Logo'; ShowCaption = false; Editable = false; ToolTip = 'Specifies the logo that will be included on all invoices.'; } field(TermsOfServiceControlSetup; TermsOfServiceLbl) { ApplicationArea = Basic, Suite; Editable = false; ShowCaption = false; ToolTip = 'Specifies the Microsoft Pay Payments terms of service.'; trigger OnDrillDown(); begin if "Terms of Service" <> '' then Hyperlink("Terms of Service") else Hyperlink(MSWalletMerchantTemplate."Terms of Service"); end; } group(MsPayMerchantDetails) { ShowCaption = false; Visible = "Merchant ID" <> ''; group(Details) { group(AccountEnabledGroup) { ShowCaption = false; InstructionalText = 'Your Microsoft Pay Payments merchant profile is configured and active. All the invoices you send will contain a link for your customers to pay you using Microsoft Pay Payments.'; } field(MerchantIDControl; "Merchant ID") { ApplicationArea = Basic, Suite; Editable = false; ToolTip = 'Specifies the Merchant ID of the Microsoft Pay Payments merchant account.'; } group(TestModeGroup) { ShowCaption = false; Visible = "Test Mode"; field(TestModeControl; "Test Mode") { ApplicationArea = Invoicing; ToolTip = 'Specifies if test mode is enabled. If you send invoices and get payments while your are in test mode, no actual money transfer will be made.'; Editable = "Test Mode"; } } field(ConfigureMsPayControl; ConfigureMsPayLbl) { ApplicationArea = Basic, Suite; Editable = false; ShowCaption = false; ToolTip = 'Specifies a link to Microsoft Pay Payments so you can configure your Microsoft Pay Payments merchant profile.'; trigger OnDrillDown(); var MSWalletMerchantMgt: Codeunit "MS - Wallet Merchant Mgt"; begin Hyperlink(MSWalletMerchantMgt.GetMerchantSignupUrl()); ConfigureEmailLinkCount += 1; if ConfigureEmailLinkCount >= 4 then Message(EnablePopUpMsg); end; } field(RemoveAccountControl; RemoveAccountLbl) { ApplicationArea = Basic, Suite; Editable = false; ShowCaption = false; ToolTip = 'Specifies that you want to disconnect your Microsoft Pay Payments account from Invoicing.'; trigger OnDrillDown(); begin if Confirm(ConfirmDeleteQst, false) then Delete(true); end; } } } } } } trigger OnAfterGetCurrRecord(); begin MSWalletMerchantTemplate.RefreshLogoIfNeeded(); end; trigger OnOpenPage(); var MSWalletMgt: Codeunit "MS - Wallet Mgt."; begin MSWalletMgt.GetTemplate(MSWalletMerchantTemplate); MSWalletMerchantTemplate.RefreshLogoIfNeeded(); end; var MSWalletMerchantTemplate: Record "MS - Wallet Merchant Template"; ConfigureEmailLinkCount: Integer; ConfirmDeleteQst: Label 'If you disconnect Invoicing from Microsoft Pay Payments, your customers will not be able to pay existing invoices using online payments.\Are you sure you want to remove the connection?'; TermsOfServiceLbl: Label 'Terms of Service'; RemoveAccountLbl: Label 'Disconnect from Microsoft Pay Payments'; ConfigureMsPayLbl: Label 'Configure Microsoft Pay Payments (opens in a new window)'; EnablePopUpMsg: Label 'If you cannot see the Microsoft Pay Payments setup window, make sure your browser allows pop-ups.'; } #endif
43.466667
227
0.485515
edd010da1361310e1db38fa41043ada7ae8438ac
1,528
pl
Perl
nfsroot/usr/share/doc/libparse-recdescent-perl/examples/demo_lisplike.pl
simontakite/FAI
077f94c83700cdd29433d09372f916f9e277497b
[ "Apache-2.0" ]
1
2019-02-26T16:02:06.000Z
2019-02-26T16:02:06.000Z
nfsroot/usr/share/doc/libparse-recdescent-perl/examples/demo_lisplike.pl
simontakite/FAI
077f94c83700cdd29433d09372f916f9e277497b
[ "Apache-2.0" ]
null
null
null
nfsroot/usr/share/doc/libparse-recdescent-perl/examples/demo_lisplike.pl
simontakite/FAI
077f94c83700cdd29433d09372f916f9e277497b
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/perl -w use Parse::RecDescent; use Data::Dumper; my $grammar = q{ s_expr: '(' s_expr(s) ')' # NESTED S-EXPRS { $return = $item[2] } | /" [^\\"]* (\\. [^\\"]*)* "/x # STRINGS | /[^()\s]+/ # ANYTHING ELSE }; my $parser = Parse::RecDescent->new($grammar) or die; undef $/; my $data = <DATA>; my $nested_array = $parser->s_expr($data); print Data::Dumper->Dump($nested_array); __DATA__ (net (rename VDDTX "vddtx") (joined (portRef VDDTX) (portRef &2 (instanceRef I_45_1102680350))) (figure WIRE (path (pointList (pt 6700 -2100) (pt 6900 -2100))) (path (pointList (pt 6900 -2100) (pt 6900 -2500))))) (net (rename N00023 "N00023") (joined (portRef &2 (instanceRef I_45_1215476478)) (portRef &1 (instanceRef I_45_1102680350)) (portRef &2 (instanceRef I_45_1215470655))) (figure WIRE (path (pointList (pt 5800 -3400) (pt 6900 -3400))) (path (pointList (pt 5800 -3400) (pt 5800 -3700))) (path (pointList (pt 6900 -3100) (pt 6900 -3400))) (path (pointList (pt 8000 -3400) (pt 8000 -3700))) (path (pointList (pt 6900 -3400) (pt 8000 -3400)))) (instance (rename TIE1 "TIE1") (viewRef XTIE0A2Y2 (cellRef XTIE0A2Y2 (libraryRef RIPPER_LIBRARY))) (transform (origin (pt 6900 -3400)))))
18.634146
64
0.513743
edbcabbd88d1a6b527f9b6a553508c3863c7ba39
1,089
pm
Perl
ext/Parrot-Embed/lib/Parrot/Embed.pm
allisonrandal/pcc_testing
b906b48d01125d1818f8ea31ff87b9fa85d21994
[ "Artistic-2.0" ]
1
2016-04-05T22:45:45.000Z
2016-04-05T22:45:45.000Z
ext/Parrot-Embed/lib/Parrot/Embed.pm
allisonrandal/pcc_testing
b906b48d01125d1818f8ea31ff87b9fa85d21994
[ "Artistic-2.0" ]
null
null
null
ext/Parrot-Embed/lib/Parrot/Embed.pm
allisonrandal/pcc_testing
b906b48d01125d1818f8ea31ff87b9fa85d21994
[ "Artistic-2.0" ]
null
null
null
package Parrot::Embed; # Copyright (C) 2006-2009, Parrot Foundation. # $Id$ use strict; use warnings; our $VERSION = '20081006'; use base 'DynaLoader'; Parrot::Embed->bootstrap($VERSION); 1; __END__ =head1 NAME Parrot::Embed - use Parrot from Perl 5 =head1 VERSION Version 20081006 =head1 SYNOPSIS use Parrot::Embed qw(Parrot_revision); =head1 DESCRIPTION This module embeds libparrot in Perl 5 programs. You can load Parrot bytecode, compile your own code, and call Parrot subroutines and send and receive values to them. It provides the core implementation used by the L<Parrot::Interpreter> module. Do consider using L<Parrot::Interpreter> first however. See also L<Parrot::PMC>. This module provides no user-inspectable code. =head1 AUTHOR chromatic, C<< <chromatic at wgz.org> >> =head1 BUGS Please report any bugs or feature requests to the Parrot Porters mailing list. Someday there may be a CPAN version of this code. Who knows? =cut # Local Variables: # mode: cperl # cperl-indent-level: 4 # fill-column: 100 # End: # vim: expandtab shiftwidth=4:
18.457627
79
0.743802
edede426126bc4af4db65ececdedc246310b9339
8,147
pl
Perl
lib/mk-ca-bundle.pl
patrick0057/ermine-curl
60c20d72f5ffd66e975aa37487324f9a7dddccb7
[ "curl" ]
133
2015-01-05T10:45:10.000Z
2022-01-07T09:41:57.000Z
lib/mk-ca-bundle.pl
patrick0057/ermine-curl
60c20d72f5ffd66e975aa37487324f9a7dddccb7
[ "curl" ]
114
2015-02-24T18:55:51.000Z
2021-12-11T13:37:32.000Z
lib/mk-ca-bundle.pl
patrick0057/ermine-curl
60c20d72f5ffd66e975aa37487324f9a7dddccb7
[ "curl" ]
45
2015-02-24T03:50:42.000Z
2022-01-31T00:35:44.000Z
#!/usr/bin/perl -w # *************************************************************************** # * _ _ ____ _ # * Project ___| | | | _ \| | # * / __| | | | |_) | | # * | (__| |_| | _ <| |___ # * \___|\___/|_| \_\_____| # * # * Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel@haxx.se>, et al. # * # * This software is licensed as described in the file COPYING, which # * you should have received as part of this distribution. The terms # * are also available at http://curl.haxx.se/docs/copyright.html. # * # * You may opt to use, copy, modify, merge, publish, distribute and/or sell # * copies of the Software, and permit persons to whom the Software is # * furnished to do so, under the terms of the COPYING file. # * # * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # * KIND, either express or implied. # * # *************************************************************************** # This Perl script creates a fresh ca-bundle.crt file for use with libcurl. # It downloads certdata.txt from Mozilla's source tree (see URL below), # then parses certdata.txt and extracts CA Root Certificates into PEM format. # These are then processed with the OpenSSL commandline tool to produce the # final ca-bundle.crt file. # The script is based on the parse-certs script written by Roland Krikava. # This Perl script works on almost any platform since its only external # dependency is the OpenSSL commandline tool for optional text listing. # Hacked by Guenter Knauf. # use Getopt::Std; use MIME::Base64; use LWP::UserAgent; use strict; use vars qw($opt_b $opt_f $opt_h $opt_i $opt_l $opt_n $opt_q $opt_t $opt_u $opt_v $opt_w); my $url = 'http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1'; # If the OpenSSL commandline is not in search path you can configure it here! my $openssl = 'openssl'; my $version = '1.18'; $opt_w = 76; # default base64 encoded lines length $0 =~ s@.*(/|\\)@@; $Getopt::Std::STANDARD_HELP_VERSION = 1; getopts('bfhilnqtuvw:'); if ($opt_i) { print ("=" x 78 . "\n"); print "Script Version : $version\n"; print "Perl Version : $]\n"; print "Operating System Name : $^O\n"; print "Getopt::Std.pm Version : ${Getopt::Std::VERSION}\n"; print "MIME::Base64.pm Version : ${MIME::Base64::VERSION}\n"; print "LWP::UserAgent.pm Version : ${LWP::UserAgent::VERSION}\n"; print "LWP.pm Version : ${LWP::VERSION}\n"; print ("=" x 78 . "\n"); } sub HELP_MESSAGE() { print "Usage:\t${0} [-b] [-f] [-i] [-l] [-n] [-q] [-t] [-u] [-v] [-w<l>] [<outputfile>]\n"; print "\t-b\tbackup an existing version of ca-bundle.crt\n"; print "\t-f\tforce rebuild even if certdata.txt is current\n"; print "\t-i\tprint version info about used modules\n"; print "\t-l\tprint license info about certdata.txt\n"; print "\t-n\tno download of certdata.txt (to use existing)\n"; print "\t-q\tbe really quiet (no progress output at all)\n"; print "\t-t\tinclude plain text listing of certificates\n"; print "\t-u\tunlink (remove) certdata.txt after processing\n"; print "\t-v\tbe verbose and print out processed CAs\n"; print "\t-w <l>\twrap base64 output lines after <l> chars (default: ${opt_w})\n"; exit; } sub VERSION_MESSAGE() { print "${0} version ${version} running Perl ${]} on ${^O}\n"; } HELP_MESSAGE() if ($opt_h); my $crt = $ARGV[0] || 'ca-bundle.crt'; (my $txt = $url) =~ s@(.*/|\?.*)@@g; my $stdout = $crt eq '-'; my $resp; my $fetched; unless ($opt_n and -e $txt) { print STDERR "Downloading '$txt' ...\n" if (!$opt_q); my $ua = new LWP::UserAgent(agent => "$0/$version"); $ua->env_proxy(); $resp = $ua->mirror($url, $txt); if ($resp && $resp->code eq '304') { print STDERR "Not modified\n" unless $opt_q; exit 0 if -e $crt && !$opt_f; } else { $fetched = 1; } if( !$resp || $resp->code !~ /^(?:200|304)$/ ) { print STDERR "Unable to download latest data: " . ($resp? $resp->code . ' - ' . $resp->message : "LWP failed") . "\n" unless $opt_q; exit 1 if -e $crt || ! -r $txt; } } my $currentdate = scalar gmtime($fetched ? $resp->last_modified : (stat($txt))[9]); my $format = $opt_t ? "plain text and " : ""; if( $stdout ) { open(CRT, '> -') or die "Couldn't open STDOUT: $!\n"; } else { open(CRT,">$crt.~") or die "Couldn't open $crt.~: $!\n"; } print CRT <<EOT; ## ## $crt -- Bundle of CA Root Certificates ## ## Certificate data from Mozilla as of: ${currentdate} ## ## This is a bundle of X.509 certificates of public Certificate Authorities ## (CA). These were automatically extracted from Mozilla's root certificates ## file (certdata.txt). This file can be found in the mozilla source tree: ## ${url} ## ## It contains the certificates in ${format}PEM format and therefore ## can be directly used with curl / libcurl / php_curl, or with ## an Apache+mod_ssl webserver for SSL client authentication. ## Just configure this file as the SSLCACertificateFile. ## EOT print STDERR "Processing '$txt' ...\n" if (!$opt_q); my $caname; my $certnum = 0; my $skipnum = 0; my $start_of_cert = 0; open(TXT,"$txt") or die "Couldn't open $txt: $!\n"; while (<TXT>) { if (/\*\*\*\*\* BEGIN LICENSE BLOCK \*\*\*\*\*/) { print CRT; print if ($opt_l); while (<TXT>) { print CRT; print if ($opt_l); last if (/\*\*\*\*\* END LICENSE BLOCK \*\*\*\*\*/); } } next if /^#|^\s*$/; chomp; if (/^CVS_ID\s+\"(.*)\"/) { print CRT "# $1\n"; } # this is a match for the start of a certificate if (/^CKA_CLASS CK_OBJECT_CLASS CKO_CERTIFICATE/) { $start_of_cert = 1 } if ($start_of_cert && /^CKA_LABEL UTF8 \"(.*)\"/) { $caname = $1; } my $untrusted = 0; if ($start_of_cert && /^CKA_VALUE MULTILINE_OCTAL/) { my $data; while (<TXT>) { last if (/^END/); chomp; my @octets = split(/\\/); shift @octets; for (@octets) { $data .= chr(oct); } } # scan forwards until the trust part while (<TXT>) { last if (/^CKA_CLASS CK_OBJECT_CLASS CKO_NSS_TRUST/); chomp; } # now scan the trust part for untrusted certs while (<TXT>) { last if (/^#/); if (/^CKA_TRUST_SERVER_AUTH\s+CK_TRUST\s+CKT_NSS_NOT_TRUSTED$/ or /^CKA_TRUST_SERVER_AUTH\s+CK_TRUST\s+CKT_NSS_TRUST_UNKNOWN$/) { $untrusted = 1; } } if ($untrusted) { $skipnum ++; } else { my $encoded = MIME::Base64::encode_base64($data, ''); $encoded =~ s/(.{1,${opt_w}})/$1\n/g; my $pem = "-----BEGIN CERTIFICATE-----\n" . $encoded . "-----END CERTIFICATE-----\n"; print CRT "\n$caname\n"; print CRT ("=" x length($caname) . "\n"); if (!$opt_t) { print CRT $pem; } else { my $pipe = "|$openssl x509 -md5 -fingerprint -text -inform PEM"; if (!$stdout) { $pipe .= " >> $crt.~"; close(CRT) or die "Couldn't close $crt.~: $!"; } open(TMP, $pipe) or die "Couldn't open openssl pipe: $!"; print TMP $pem; close(TMP) or die "Couldn't close openssl pipe: $!"; if (!$stdout) { open(CRT, ">>$crt.~") or die "Couldn't open $crt.~: $!"; } } print STDERR "Parsing: $caname\n" if ($opt_v); $certnum ++; $start_of_cert = 0; } } } close(TXT) or die "Couldn't close $txt: $!\n"; close(CRT) or die "Couldn't close $crt.~: $!\n"; unless( $stdout ) { if ($opt_b && -e $crt) { my $bk = 1; while (-e "$crt.~${bk}~") { $bk++; } rename $crt, "$crt.~${bk}~" or die "Failed to create backup $crt.~$bk}~: $!\n"; } elsif( -e $crt ) { unlink( $crt ) or die "Failed to remove $crt: $!\n"; } rename "$crt.~", $crt or die "Failed to rename $crt.~ to $crt: $!\n"; } unlink $txt if ($opt_u); print STDERR "Done ($certnum CA certs processed, $skipnum untrusted skipped).\n" if (!$opt_q); exit;
33.526749
100
0.565852
eda58e8f145656fe431e45e9a1079cb49eea6283
8,070
pm
Perl
lib/Bio/PopGen/IO/prettybase.pm
Helmholtz-HIPS/prosnap
5286cda39276d5eda85d2ddb23b8ab83c5d4960c
[ "MIT" ]
5
2017-10-27T15:03:19.000Z
2020-04-25T17:44:49.000Z
lib/Bio/PopGen/IO/prettybase.pm
Helmholtz-HIPS/prosnap
5286cda39276d5eda85d2ddb23b8ab83c5d4960c
[ "MIT" ]
4
2021-01-28T20:49:55.000Z
2022-03-25T19:02:54.000Z
lib/Bio/PopGen/IO/prettybase.pm
Helmholtz-HIPS/prosnap
5286cda39276d5eda85d2ddb23b8ab83c5d4960c
[ "MIT" ]
2
2019-02-22T10:51:15.000Z
2019-02-22T12:35:35.000Z
# # BioPerl module for Bio::PopGen::IO::prettybase # # Please direct questions and support issues to <bioperl-l@bioperl.org> # # Cared for by Jason Stajich <jason-at-bioperl.org> # # Copyright Jason Stajich # # You may distribute this module under the same terms as perl itself # POD documentation - main docs before the code =head1 NAME Bio::PopGen::IO::prettybase - Extract individual allele data from PrettyBase format =head1 SYNOPSIS Do not use directly, use through the Bio::PopGen::IO driver =head1 DESCRIPTION This object will parse comma delimited PrettyBase output. PrettyBase is defined by the SeattleSNPs http://pga.gs.washington.edu/ This is expected to be tab delimited (you can vary with the field_delimiter flag SITE SAMPLE ALLELE1 ALLELE2 There are 2 initialization parameters, the delimiter (-field_delimiter) [default 'tab'] and a boolean -no_header which specifies if there is no header line to read in. All lines starting with '#' will be skipped =head1 FEEDBACK =head2 Mailing Lists User feedback is an integral part of the evolution of this and other Bioperl modules. Send your comments and suggestions preferably to the Bioperl mailing list. Your participation is much appreciated. bioperl-l@bioperl.org - General discussion http://bioperl.org/wiki/Mailing_lists - About the mailing lists =head2 Support Please direct usage questions or support issues to the mailing list: I<bioperl-l@bioperl.org> rather than to the module maintainer directly. Many experienced and reponsive experts will be able look at the problem and quickly address it. Please include a thorough description of the problem with code and data examples if at all possible. =head2 Reporting Bugs Report bugs to the Bioperl bug tracking system to help us keep track of the bugs and their resolution. Bug reports can be submitted via the web: https://github.com/bioperl/bioperl-live/issues =head1 AUTHOR - Jason Stajich Email jason-at-bioperl.org =head1 CONTRIBUTORS Matthew Hahn, matthew.hahn-at-duke.edu =head1 APPENDIX The rest of the documentation details each of the object methods. Internal methods are usually preceded with a _ =cut # Let the code begin... package Bio::PopGen::IO::prettybase; use vars qw($FieldDelim $Header); use strict; ($FieldDelim,$Header) =( '\t',0); use Bio::PopGen::Individual; use Bio::PopGen::Population; use Bio::PopGen::Genotype; use base qw(Bio::PopGen::IO); =head2 new Title : new Usage : my $obj = Bio::PopGen::IO::prettybase->new(); Function: Builds a new Bio::PopGen::IO::prettybase object Returns : an instance of Bio::PopGen::IO::prettybase Args : -field_delimiter => a field delimiter character or regexp (default is /\t/ ) -header => boolean if the file will have a header and parser should skip first line in the file (default is false) -convert_indel_states => convert alleles which are longer than one character to an 'I' meaning insert state, and alleles which are '-' to a delete state. (default is false) =cut sub _initialize { my($self, @args) = @_; my ($fieldsep, $conv_indels, $header) = $self->_rearrange([qw(FIELD_DELIMITER CONVERT_INDEL_STATES HEADER)],@args); $self->flag('header', defined $header ? $header : $Header); $self->flag('field_delimiter',defined $fieldsep ? $fieldsep : $FieldDelim); $self->{'_header'} = undef; $self->{'_parsed_individiuals'} = []; $self->{'_parsed'} = 0; $self->flag('convert_indel',$conv_indels || 0); return 1; } =head2 flag Title : flag Usage : $obj->flag($flagname,$newval) Function: Get/Set the flag value Returns : value of a flag (a boolean) Args : A flag name, currently we expect 'header', 'field_delimiter', or 'allele_delimiter' on set, new value (a boolean or undef, optional) =cut sub flag{ my $self = shift; my $fieldname = shift; return unless defined $fieldname; return $self->{'_flag'}->{$fieldname} = shift if @_; return $self->{'_flag'}->{$fieldname}; } =head2 next_individual Title : next_individual Usage : my $ind = $popgenio->next_individual; Function: Retrieve the next individual from a dataset Returns : Bio::PopGen::IndividualI object Args : none =cut sub next_individual { my ($self) = @_; unless( $self->{'_parsed'} ) { $self->_parse_prettybase; } return $self->{'_parsed_individiuals'}->[$self->{'_iterator'}++]; } =head2 next_population Title : next_population Usage : my $ind = $popgenio->next_population; Function: Retrieve the next population from a dataset Returns : Bio::PopGen::PopulationI object Args : none Note : Many implementation will not implement this =cut # Plan is to just return the whole dataset as a single population by # default I think - people would then have each population in a separate # file. sub next_population{ my ($self) = @_; my @inds; while( my $ind = $self->next_individual ) { push @inds, $ind; } return unless @inds; Bio::PopGen::Population->new(-individuals => \@inds); } sub _parse_prettybase { my $self = shift; my %inds; my $convert_indels = $self->flag('convert_indel'); while( defined( $_ = $self->_readline) ) { next if( /^\s*\#/ || /^\s+$/ || ! length($_) ); my ($site,$sample,@alleles) = split($self->flag('field_delimiter'),$_); if( ! defined $sample ) { warn("sample id is undefined for $_"); next; } for my $allele ( @alleles ) { $allele =~ s/^\s+//; $allele =~ s/\s+$//; if( $convert_indels ) { if( length($allele) > 1 ) { # we have an insert state $allele = 'I'; } elsif( $allele eq '-' ) { # have a delete state $allele = 'D'; } } } my $g = Bio::PopGen::Genotype->new(-alleles => \@alleles, -marker_name => $site, -individual_id=> $sample); if( ! defined $inds{$sample} ) { $inds{$sample} = Bio::PopGen::Individual->new(-unique_id => $sample); } $inds{$sample}->add_Genotype($g); } $self->{'_parsed_individiuals'} = [ values %inds ]; $self->{'_parsed'} = 1; return; } =head2 write_individual Title : write_individual Usage : $popgenio->write_individual($ind); Function: Write an individual out in the file format Returns : none Args : L<Bio::PopGen::PopulationI> object(s) =cut sub write_individual{ my ($self,@inds) = @_; foreach my $ind ( @inds ) { if (! ref($ind) || ! $ind->isa('Bio::PopGen::IndividualI') ) { $self->warn("Cannot write an object that is not a Bio::PopGen::IndividualI object"); next; } foreach my $marker ( $ind->get_marker_names ) { my $g = $ind->get_Genotypes(-marker=> $marker); next unless defined $g; $self->_print( join("\t", $marker, $ind->unique_id, $g->get_Alleles), "\n"); } } } =head2 write_population Title : write_population Usage : $popgenio->write_population($pop); Function: Write a population out in the file format Returns : none Args : L<Bio::PopGen::PopulationI> object(s) Note : Many implementation will not implement this =cut sub write_population{ my ($self,@pops) = @_; foreach my $pop ( @pops ) { if (! ref($pop) || ! $pop->isa('Bio::PopGen::PopulationI') ) { $self->warn("Cannot write an object that is not a Bio::PopGen::PopulationI object"); next; } my @mnames = $pop->get_marker_names; foreach my $ind ( $pop->get_Individuals ) { if (! ref($ind) || ! $ind->isa('Bio::PopGen::IndividualI') ) { $self->warn("Cannot write an object that is not a Bio::PopGen::IndividualI object"); next; } foreach my $marker ( @mnames ) { my $g = $ind->get_Genotypes(-marker=> $marker); next unless defined $g; $self->_print( join("\t", $marker, $ind->unique_id, $g->get_Alleles), "\n"); } } } } 1;
26.286645
93
0.650805
edd26b45394cb541087fe5405aac3417ab27d545
4,257
pm
Perl
lib/Dancer/Session.pm
atoomic/Dancer
1ab1aab873c9f95b75b2d7d6b4ceba6cad283b07
[ "Artistic-1.0" ]
1
2017-09-09T12:44:54.000Z
2017-09-09T12:44:54.000Z
lib/Dancer/Session.pm
abh/Dancer
0466b406a80deedcb06bb6623124a7bdef6754a2
[ "Artistic-1.0" ]
null
null
null
lib/Dancer/Session.pm
abh/Dancer
0466b406a80deedcb06bb6623124a7bdef6754a2
[ "Artistic-1.0" ]
null
null
null
package Dancer::Session; use strict; use warnings; use Dancer::Cookies; use Dancer::Engine; # Singleton representing the session engine class to use my $ENGINE = undef; sub engine {$ENGINE} # This wrapper look for the session engine and try to load it. sub init { my ($class, $name, $config) = @_; $ENGINE = Dancer::Engine->build(session => $name, $config); #$ENGINE->init(); already done } # retrieve or create a session for the client sub get_current_session { my $sid = engine->read_session_id; my $session = undef; my $class = ref(engine); $session = $class->retrieve($sid) if $sid; if (not defined $session) { $session = $class->create(); engine->write_session_id($session->id); } return $session; } sub get { get_current_session() } sub read { my ($class, $key) = @_; my $session = get_current_session(); return $session->{$key}; } sub write { my ($class, $key, $value) = @_; my $session = get_current_session(); $session->{$key} = $value; # TODO : should be moved as an "after" filter $session->flush; return $value; } 1; __END__ =pod =head1 NAME Dancer::Session - session engine for the Dancer framework =head1 DESCRIPTION This module provides support for server-side sessions for the L<Dancer> web framework. The session is accessible to the user via an abstraction layer implemented by the L<Dancer::Session> class. =head1 USAGE =head2 Configuration The session engine must be first enabled in the environment settings, this can be done like the following: In the application code: # enabling the YAML-file-based session engine set session => 'YAML'; Or in config.yml or environments/$env.yml session: "YAML" By default session are disabled, you must enable them before using it. If the session engine is disabled, any Dancer::Session call will throw an exception. =head2 Route Handlers When enabled, the session engine can be used in a route handler with the keyword B<session>. This keyword represents a key-value pairs ensemble that is actually stored to the session. You can either look for an existing item in the session storage or modify one. Here is a simple example of two route handlers that implement a basic C</login> and C</home> actions using the session engine. post '/login' => sub { # look for params and authenticate the user # ... if ($user) { session user_id => $user->id; } }; get '/home' => sub { # if a user is present in the session, let him go, otherwise redirect to # /login if (not session('user_id')) { redirect '/login'; } }; Of course, you probably don't want to have to duplicate the code to check whether the user is logged in for each route handler; there's an example in the L<Dancer::Cookbook> showing how to use a before filter to check whether the user is logged in before all requests, and redirect to a login page if not. =head1 SUPPORTED ENGINES Dancer has a modular session engine that makes implementing new session backends pretty easy. If you'd like to write your own, feel free to take a look at L<Dancer::Session::Abstract>. The following engines are supported: =over 4 =item L<Dancer::Session::YAML> A YAML file-based session backend, pretty convininent for development purposes, but maybe not the best for production needs. =item L<Dancer::Session::Memcached> Session are stored in Memcached servers. This is good for production matters and is a good way to use a distributed session storage. =item L<Dancer::Session::Cookie> This module implements a session engine for sessions stored entirely inside encrypted cookies (this engine doesn't use a server-side storage). =back =head1 DEPENDENCY Dancer::Session may depend on third-party modules, depending on the session engine used. See the session engine module for details. =head1 AUTHORS This module has been written by Alexis Sukrieh. See the AUTHORS file that comes with this distribution for details. =head1 LICENSE This module is free software and is released under the same terms as Perl itself. =head1 SEE ALSO See L<Dancer> for details about the complete framework. =cut
25.339286
83
0.711064
edae5b942ce8b368eff164f43afd91f0785c488f
1,771
pm
Perl
auto-lib/Paws/KinesisAnalytics/KinesisStreamsInputUpdate.pm
galenhuntington/aws-sdk-perl
13b775dcb5f0b3764f0a82f3679ed5c7721e67d3
[ "Apache-2.0" ]
null
null
null
auto-lib/Paws/KinesisAnalytics/KinesisStreamsInputUpdate.pm
galenhuntington/aws-sdk-perl
13b775dcb5f0b3764f0a82f3679ed5c7721e67d3
[ "Apache-2.0" ]
1
2021-05-26T19:13:58.000Z
2021-05-26T19:13:58.000Z
auto-lib/Paws/KinesisAnalytics/KinesisStreamsInputUpdate.pm
galenhuntington/aws-sdk-perl
13b775dcb5f0b3764f0a82f3679ed5c7721e67d3
[ "Apache-2.0" ]
null
null
null
package Paws::KinesisAnalytics::KinesisStreamsInputUpdate; use Moose; has ResourceARNUpdate => (is => 'ro', isa => 'Str'); has RoleARNUpdate => (is => 'ro', isa => 'Str'); 1; ### main pod documentation begin ### =head1 NAME Paws::KinesisAnalytics::KinesisStreamsInputUpdate =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::KinesisAnalytics::KinesisStreamsInputUpdate object: $service_obj->Method(Att1 => { ResourceARNUpdate => $value, ..., RoleARNUpdate => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::KinesisAnalytics::KinesisStreamsInputUpdate object: $result = $service_obj->Method(...); $result->Att1->ResourceARNUpdate =head1 DESCRIPTION When updating application input configuration, provides information about an Amazon Kinesis stream as the streaming source. =head1 ATTRIBUTES =head2 ResourceARNUpdate => Str Amazon Resource Name (ARN) of the input Amazon Kinesis stream to read. =head2 RoleARNUpdate => Str ARN of the IAM role that Amazon Kinesis Analytics can assume to access the stream on your behalf. You need to grant the necessary permissions to this role. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::KinesisAnalytics> =head1 BUGS and CONTRIBUTIONS The source code is located here: L<https://github.com/pplu/aws-sdk-perl> Please report bugs to: L<https://github.com/pplu/aws-sdk-perl/issues> =cut
26.833333
120
0.756635
ed8fc75d6a3ab7ece8b4c3240a26dc5dbd5d344e
16,498
pm
Perl
src/fhem/trunk/fhem/contrib/deprecated/98_JsonList.pm
nastymorbol/fhem-docker
c88d13e6fb098a487486b448806048eab1222b81
[ "MIT" ]
null
null
null
src/fhem/trunk/fhem/contrib/deprecated/98_JsonList.pm
nastymorbol/fhem-docker
c88d13e6fb098a487486b448806048eab1222b81
[ "MIT" ]
null
null
null
src/fhem/trunk/fhem/contrib/deprecated/98_JsonList.pm
nastymorbol/fhem-docker
c88d13e6fb098a487486b448806048eab1222b81
[ "MIT" ]
null
null
null
################################################################ # $Id: 98_JsonList.pm 16370 2018-03-10 09:00:04Z rudolfkoenig $ # # Copyright notice # # (c) 2008 Copyright: Martin Fischer (m_fischer at gmx dot de) # All rights reserved # # This script is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # The GNU General Public License can be found at # http://www.gnu.org/copyleft/gpl.html. # A copy is found in the textfile GPL.txt and important notices to the license # from the author is found in LICENSE.txt distributed with these scripts. # # This script is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # ################################################################ # examples: # jsonslist - returns all definitions and status infos # jsonlist lamp1 - returns definitions and status infos for 'lamp1' # jsonlist FS20 - returns status infos for FS20 devices # jsonlist ROOMS - returns a list of rooms ################################################################ package main; use strict; use warnings; use POSIX; sub CommandJsonList($$); sub JsonEscape($); sub PrintHashJson($$); ##################################### sub JsonList_Initialize($$) { my %lhash = ( Fn=>"CommandJsonList", Hlp=>"[<devspec>|<devtype>|rooms],list definitions and status info or rooms as JSON" ); $cmds{jsonlist} = \%lhash; } ##################################### sub JsonEscape($) { my $a = shift; return "null" if(!$a); $a=~ s/([\x00-\x19\x22\x5c])/sprintf '\u%04x', ord($1)/ge; # Forum 57377 return $a; } ##################################### sub PrintHashJson($$) { my ($h, $lev) = @_; return if($h->{PrintHashJson}); my $hc = keys %{$h}; my @str; foreach my $c (sort keys %{$h}) { my $str = ""; if(ref($h->{$c})) { if(ref($h->{$c}) eq "HASH" && $c ne "PortObj") { if($c eq "IODev" || $c eq "HASH") { $str .= sprintf("%*s\"%s\": \"%s\"", $lev," ",$c, JsonEscape($h->{$c}{NAME})); } else { $str .= sprintf("%*s\"%s\": {\n", $lev, " ", $c); if(keys(%{$h->{$c}}) != 0) { $h->{PrintHashJson} = 1; $str .= PrintHashJson($h->{$c}, $lev+2); delete($h->{PrintHashJson}); } else { $str .= sprintf("%*s\"null\": \"null\"\n", $lev+4, " "); } $str .= sprintf("%*s}", $lev, " "); } } elsif(ref($h->{$c}) eq "ARRAY") { $str .= sprintf("%*s\"%s\": \"%s\"", $lev," ",$c, "ARRAY"); } elsif($c eq "PortObj") { $str .= sprintf("%*s\"%s\": \"%s\"", $lev," ",$c, "PortObj"); } } else { $str .= sprintf("%*s\"%s\": \"%s\"", $lev," ",$c, JsonEscape($h->{$c})); } push @str, $str if($str); } return join(",\n", @str) . "\n"; } ##################################### sub CommandJsonList($$) { my ($cl, $param) = @_; my $lt = ""; my $str = ""; # Text indentation my $lev = 2; if(!$param) { # Array counter my @ac; my $ac = 0; my $cc = 0; my @dc; my $dc = 0; my $tc = 0; # total available my $tr = 0; # results returned my $q = ""; # open JSON object $str = "{\n"; $str .= sprintf("%*s\"ResultSet\": \"%s\",\n", $lev, " ","full"); # open JSON array $str .= sprintf("%*s\"Results\": [\n", $lev, " "); delete($modules{""}) if(defined($modules{""})); @dc = keys(%defs); $dc = @dc; #$tc = 0; for my $d (sort { my $x = $modules{$defs{$a}{TYPE}}{ORDER} cmp $modules{$defs{$b}{TYPE}}{ORDER}; $x = ($a cmp $b) if($x == 0); $x; } keys %defs) { my $p = $defs{$d}; my $t = $p->{TYPE}; if(!$t) { Log3 undef, 3, "JsonList: device ($d) without TYPE"; next; } $t = $q if($q ne ""); #$str .= sprintf("} ") if($t eq $lt); #$str .= sprintf("},\n") if($t eq $lt); #$str .= sprintf("%*s},\n", $lev+6, " ") if($t eq $lt); my $a1 = JsonEscape($p->{STATE}); # close device object $str .= sprintf("%*s},\n", $lev+6, " ") if($t eq $lt); if($t ne $lt) { # close device opject $str .= sprintf("%*s}\n", $lev+6, " ") if($lt && $t ne $lt); #$str .= sprintf("}\n") if($lt); # close devices array $str .= sprintf("%*s]\n", $lev+4, " ") if($lt); # close list object $str .= sprintf("%*s},\n", $lev+2, " ") if($lt); #$str .= sprintf("%*s{\n", $lev+4, " "); # open list object $str .= sprintf("%*s\{\n", $lev+2, " "); $str .= sprintf("%*s\"%s\": \"%s\",\n", $lev+4, " ", "list", $t); # open devices array $str .= sprintf("%*s\"%s\": [\n", $lev+4, " ", "devices"); } $lt = $t; #$str .= sprintf("%*s{\n", $lev+8, " "); # open device object $str .= sprintf("%*s{\n", $lev+6, " "); #$str .= sprintf("%*s\"name\": \"%s\",\n", $lev+8, " ", $d); #$str .= sprintf("%*s\"state\": \"%s\",\n", $lev+8, " ", $a1); #$str .= sprintf("\"INT\": { "); @ac = keys(%{$p}); $ac = 0; foreach my $k (sort @ac) { next if(ref($p->{$k})); $ac++; } $cc = 0; foreach my $c (sort keys %{$p}) { next if(ref($p->{$c})); $str .= sprintf("%*s\"%s\": \"%s\",\n", $lev+8, " ", JsonEscape($c), JsonEscape($p->{$c})); $cc++; #$str .= ",\n" if($cc != $ac || ($cc == $ac && $p->{IODev})); #$str .= ",\n" if($cc != $ac || ($cc == $ac && $p->{IODev})); #$str .= "\n" if($cc == $ac && !$p->{IODev}); } $str .= sprintf("%*s\"IODev\": \"%s\",\n", $lev+8, " ", $p->{IODev}{NAME}) if($p->{IODev}); #$str .= sprintf(" }, "); @ac = keys(%{$attr{$d}}); $ac = @ac; $cc = 0; if($ac != 0) { $str .= sprintf("%*s\"ATTR\": {\n", $lev+8, " "); foreach my $c (sort keys %{$attr{$d}}) { $str .= sprintf("%*s\"%s\": \"%s\"", $lev+10, " ", JsonEscape($c), JsonEscape($attr{$d}{$c})); $cc++; #$str .= ",\n" if($cc != $ac); $str .= ",\n" if($cc != $ac); #$str .= "\n" if($cc == $ac); } $str .= "\n"; #$str .= sprintf("%*s]\n", $lev+8, " ") if(!$p->{READINGS}); #$str .= sprintf("%*s],\n", $lev+8, " ") if($p->{READINGS}); $str .= sprintf("%*s},\n", $lev+8, " "); } else { $str .= sprintf("%*s\"ATTR\": {},\n", $lev+8, " "); } #$str .= sprintf("%*s],\n", $lev+8, " ") if($p->{READINGS}); #$str .= sprintf("%*s]\n", $lev+8, " ") if(!$p->{READINGS}); my $r = $p->{READINGS}; if($r) { $str .= sprintf("%*s\"READINGS\": [\n", $lev+8, " "); @ac = keys(%{$r}); $ac = @ac; $cc = 0; foreach my $c (sort keys %{$r}) { $str .= sprintf("%*s{\n", $lev+10, " "); $str .= sprintf("%*s\"%s\": \"%s\",\n", $lev+12, " ", JsonEscape($c), JsonEscape($r->{$c}{VAL})); $str .= sprintf("%*s\"measured\": \"%s\"\n", $lev+12, " ", $r->{$c}{TIME}); $cc++; #$str .= ",\n" if($cc != $ac); $str .= sprintf("%*s},\n", $lev+10, " ") if($cc != $ac); $str .= sprintf("%*s}\n", $lev+10, " ") if($cc == $ac); } $str .= sprintf("%*s],\n", $lev+8, " "); } else { $str .= sprintf("%*s\"READINGS\": [],\n", $lev+8, " "); } # corresponding set parameters $str .= sprintf("%*s\"sets\": [\n", $lev+6, " "); my $sets = getAllSets($d); if($sets) { my @pSets; foreach my $set (split(" ", JsonEscape($sets))) { push @pSets, sprintf("%*s\"%s\"", $lev+8, " ", $set); } $str .= join(",\n", @pSets); } $str .= sprintf("\n%*s],\n", $lev+6, " "); # corresponding attributes $str .= sprintf("%*s\"attrs\": [\n", $lev+6, " "); my $attrs = getAllAttr($d); if($attrs) { my @aSets; foreach my $attr (split(" ", JsonEscape($attrs))) { push @aSets, sprintf("%*s\"%s\"", $lev+8, " ", $attr); } $str .= join(",\n", @aSets); } $str .= sprintf("\n%*s]\n", $lev+6, " "); $tc++; $tr = $tc if($q eq ""); $tr++ if($q ne "" && $p->{TYPE} eq $t); $str .= sprintf("%*s}\n", $lev+6, " ") if(($tc == $dc) || (!$lt)); } $str .= sprintf("%*s]\n", $lev+4, " ") if($lt); $str .= sprintf("%*s}\n", $lev+2, " ") if($lt); # close JSON array $str .= sprintf("%*s],\n", $lev, " "); # return number of results $str .= sprintf("%*s\"totalResultsReturned\": %s\n", $lev, " ",$tr); # close JSON object $str .= "}\n"; } else { if($param eq "ROOMS") { my %rooms; foreach my $d (keys %attr) { my $r = $attr{$d}{room}; map { $rooms{$_} = 1 } split(",", $r) if($r && $r ne "hidden"); } my @rooms = sort keys %rooms; # Result counter my $c = 0; # Open JSON object $str .= "{\n"; $str .= sprintf("%*s\"%s\": \"%s\",\n", $lev, " ", "ResultSet", "rooms"); # Open JSON array $str .= sprintf("%*s\"%s\": [", $lev, " ", "Results"); for (my $i=0; $i<@rooms; $i++) { $str .= "," if($i <= $#rooms && $i > 0); $str .= sprintf("\n%*s\"%s\"", $lev+2, " ", $rooms[$i]); $c++; } $str .= "\n"; # Close JSON array $str .= sprintf("%*s],\n", $lev, " "); # Result summary #$str .= sprintf("%*s\"%s\": %s,\n", $lev, " ", "totalResultsAvailable", $c); $str .= sprintf("%*s\"%s\": %s\n", $lev, " ", "totalResultsReturned", $c); # Close JSON object $str .= "}"; } else { # Search for given device-type my @devs = grep { $param eq $defs{$_}{TYPE} } keys %defs; if(@devs) { my $lt = ""; my $ld = ""; # Result counter my $c = 0; # Open JSON object $str .= "{\n"; $str .= sprintf("%*s\"%s\": \"%s\",\n", $lev, " ", "ResultSet", "devices#$param"); # Open JSON array $str .= sprintf("%*s\"%s\": [", $lev, " ", "Results"); # Sort first by type then by name for my $d (sort { my $x = $modules{$defs{$a}{TYPE}}{ORDER} cmp $modules{$defs{$b}{TYPE}}{ORDER}; $x = ($a cmp $b) if($x == 0); $x; } keys %defs) { if($defs{$d}{TYPE} eq $param) { my $t = $defs{$d}{TYPE}; $str .= sprintf("\n%*s},",$lev+2, " ") if($d ne $ld && $lt ne ""); $str .= sprintf("\n%*s{",$lev+2, " "); $str .= sprintf("\n%*s\"name\": \"%s\",",$lev+4, " ", $d); $str .= sprintf("\n%*s\"state\": \"%s\"",$lev+4, " ", $defs{$d}{STATE}); $lt = $t; $ld = $d; $c++; } } $str .= sprintf("\n%*s}\n",$lev+2, " "); # Close JSON array $str .= sprintf("%*s],\n", $lev, " "); # Result summary $str .= sprintf("%*s\"%s\": %s\n", $lev, " ", "totalResultsReturned", $c); # Close JSON object $str .= "}"; } else { # List device foreach my $sdev (devspec2array($param)) { if(!defined($defs{$sdev})) { $str .= "No device named or type $param found, try <list> for all devices"; next; } $defs{$sdev}{"ATTRIBUTES"} = $attr{$sdev}; # Open JSON object $str = "{\n"; $str .= sprintf("%*s\"%s\": {\n", $lev, " ", "ResultSet"); # Open JSON array $str .= sprintf("%*s\"%s\": {\n", $lev+2, " ", "Results"); $str .= PrintHashJson($defs{$sdev}, $lev+4); # Close JSON array $str .= sprintf("%*s}\n", $lev+2, " "); # Close JSON object $str .= sprintf("%*s}\n", $lev, " "); $str .= "}"; } } } } return $str; } 1; =pod =item command =item summary show device data in JSON format (deprecated, use JsonList2) =item summary_DE zeigt Ger&auml;tedaten in JSON Format (&uuml;berholt, bitte JSonList2 verwenden) =begin html <a name="JsonList"></a> <h3>JsonList</h3> <ul> <b>Note</b>: this command is deprecated, use <a href="#JsonList2">jsonlist2</a> instead.<br><br> <code>jsonlist [&lt;devspec&gt;|&lt;typespec&gt;|ROOMS]</code> <br><br> Returns an JSON tree of all definitions, all notify settings and all at entries if no parameter is given. Can also be called via HTTP by http://fhemhost:8083/fhem?cmd=jsonlist&XHR=1 <br><br> Example: <pre><code> fhem> jsonlist { "ResultSet": "full", "Results": [ { "list": "Global", "devices": [ { "DEF": "&lt;no definition&gt;", "NAME": "global", "NR": "1", "STATE": "&lt;no definition&gt;", "TYPE": "Global", "currentlogfile": "/var/log/fhem/fhem-2011-12.log", "logfile": "/var/log/fhem/fhem-%Y-%m.log", "ATTR": { "configfile": "/etc/fhem/fhem.conf", "logfile": "/var/log/fhem/fhem-%Y-%m.log", "modpath": "/usr/share/fhem", "pidfilename": "/var/run/fhem.pid", "port": "7072 global", "room": "Server", "statefile": "/var/cache/fhem/fhem.save", "verbose": "4", "version": "=VERS= from =DATE= ($Id: 98_JsonList.pm 16370 2018-03-10 09:00:04Z rudolfkoenig $)" }, "READINGS": [] } ] }, { "list": "CM11", "devices": [ { "DEF": "/dev/cm11", "DeviceName": "/dev/cm11", "FD": "14", "NAME": "CM11", "NR": "19", "PARTIAL": "null", "STATE": "Initialized", "TYPE": "CM11", "ATTR": { "model": "CM11" }, "READINGS": [] } ] }, { [...placeholder for more entrys...] }, ], "totalResultsReturned": 235 } </code></pre> If specifying <code>&lt;devspec&gt;</code>, then a detailed status for <code>&lt;devspec&gt;</code> will be displayed, e.g.: <pre><code> fhem> jsonlist lamp1 { "ResultSet": { "Results": { "ATTRIBUTES": { "alias": "Lamp on Sideboard", "model": "fs20st", "room": "Livingroom" }, "BTN": "01", "CHANGED": "ARRAY", "CHANGETIME": "ARRAY", "CODE": { "1": "0b0b 01", "2": "0b0b 0f", "3": "0b0b f0", "4": "0b0b ff" }, "DEF": "12341234 1112 lm 1144 fg 4411 gm 4444", "IODev": "CUN868", "NAME": "lamp1", "NR": "155", "READINGS": { "state": { "TIME": "2011-12-01 16:23:01", "VAL": "on" } }, "STATE": "on", "TYPE": "FS20", "XMIT": "0b0b" } } } </code></pre> If specifying <code>&lt;typespec&gt;</code>, then a list with the status for the defined <code>&lt;typespec&gt;</code> devices will be displayed, e.g.: <pre><code> fhem> jsonlist HMS { "ResultSet": "devices#HMS", "Results": [ { "name": "KG.ga.WD.01", "state": "Water Detect: off" }, { "name": "KG.hz.GD.01", "state": "Gas Detect: off" }, { "name": "KG.k1.TF.01", "state": "T: 16.6 H: 51.2 Bat: ok" }, { "name": "NN.xx.RM.xx", "state": "smoke_detect: off" } ], "totalResultsReturned": 4 } </code></pre> If specifying <code>ROOMS</code>, then a list with the defined rooms will be displayed, e.g.: <pre><code> fhem> jsonlist ROOMS { "ResultSet": "rooms", "Results": [ "Bathroom", "Bedroom", "Children", "Diningroom", "Garden", "House", "Livingroom", "Office", "hidden" ], "totalResultsReturned": 15 } </code></pre> </ul> =end html =cut
29.779783
109
0.424051
ede7d743605270aefb00d1957c471c00cb91f8ab
462
t
Perl
t/build-hook.t
pnu/panda
671bd4f46b775342452489d709c0e9a9844dd5ed
[ "MIT" ]
89
2015-01-03T02:44:44.000Z
2021-11-22T08:31:29.000Z
t/build-hook.t
trenchmortar/panda
46b7940708c5916da407760d5c0c591fd40633e8
[ "MIT" ]
178
2015-01-01T18:23:41.000Z
2017-06-30T10:49:54.000Z
t/build-hook.t
trenchmortar/panda
46b7940708c5916da407760d5c0c591fd40633e8
[ "MIT" ]
50
2015-01-02T04:49:08.000Z
2021-11-07T04:51:37.000Z
#!perl6 use v6.c; use Test; use Panda::Tester; use Panda::Builder; my $wd = $*CWD.child('testmodules').child('with-build').Str; $PANDATEST::RAN = False; lives-ok { ok Panda::Tester.test($wd), "run test"; ok Panda::Builder.build($wd), "run build"; ok Panda::Builder.build($wd), "run build"; ok $PANDATEST::RAN, "and it ran the builder"; }, "run test and build with a Build.pm present"; done-testing; # vim: expandtab shiftwidth=4 ft=perl6
19.25
60
0.65368
edaf0d8ca0cec11b0e8bad90b46100b40fb5d311
2,785
al
Perl
benchmark/benchmarks/FASP-benchmarks/data/random-oriented/randomoriented-1135-330-429.al
krzysg/FaspHeuristic
1929c40e3fbc49e68b04acfc5522539a18758031
[ "MIT" ]
null
null
null
benchmark/benchmarks/FASP-benchmarks/data/random-oriented/randomoriented-1135-330-429.al
krzysg/FaspHeuristic
1929c40e3fbc49e68b04acfc5522539a18758031
[ "MIT" ]
null
null
null
benchmark/benchmarks/FASP-benchmarks/data/random-oriented/randomoriented-1135-330-429.al
krzysg/FaspHeuristic
1929c40e3fbc49e68b04acfc5522539a18758031
[ "MIT" ]
null
null
null
1 169 284 2 23 286 3 154 4 39 5 168 6 112 7 203 8 38 243 265 278 9 257 10 33 143 179 292 11 12 13 14 300 15 16 17 225 18 19 215 20 21 170 208 22 23 24 25 142 26 134 27 310 28 29 80 103 30 230 317 31 170 32 215 328 33 85 34 16 58 35 36 37 186 38 39 35 40 16 168 41 267 42 75 235 247 43 150 261 278 44 145 45 103 46 182 47 50 48 324 49 50 157 175 273 281 51 1 172 180 281 52 9 53 54 109 55 251 268 56 97 57 58 59 303 60 234 309 61 62 129 63 70 64 44 84 286 65 26 96 115 66 7 67 169 200 293 68 69 115 70 71 92 177 72 73 46 74 75 300 76 44 132 77 252 264 272 304 78 80 79 301 312 80 51 208 81 82 69 83 84 131 255 313 85 86 15 87 158 255 88 233 322 89 12 86 99 90 91 92 93 6 47 48 182 94 95 102 96 97 208 306 98 260 99 156 100 101 100 173 102 87 128 159 244 103 27 211 104 61 105 57 296 106 57 107 10 148 304 108 56 304 109 110 111 194 112 9 113 51 213 114 292 115 24 116 23 95 251 117 118 40 192 196 119 120 121 122 123 14 124 101 198 125 17 330 126 127 248 284 311 128 63 173 232 129 228 130 39 131 94 132 133 94 265 134 75 251 295 135 188 211 136 74 245 327 137 138 41 139 140 159 196 220 284 141 142 143 144 84 97 145 146 144 147 3 217 307 148 4 45 149 74 150 151 43 152 153 116 156 213 154 11 168 155 265 156 157 158 42 78 285 159 106 270 160 2 32 121 161 81 162 157 163 310 312 164 80 313 165 7 112 219 166 86 167 319 328 168 169 170 107 228 171 172 288 173 141 174 85 175 122 176 11 212 263 177 213 178 191 179 244 256 180 297 181 125 272 182 166 304 183 100 292 184 140 237 185 186 2 187 237 289 188 189 106 206 190 251 191 166 264 317 329 192 193 184 194 320 195 26 196 197 37 48 157 198 199 24 200 194 297 201 202 40 203 44 204 192 316 205 164 285 206 71 91 150 197 207 182 208 91 328 209 283 292 210 86 91 211 225 212 213 214 162 215 221 216 235 217 158 192 234 218 219 220 15 189 246 264 221 251 280 294 222 136 153 321 223 224 225 200 226 227 228 27 79 120 226 299 229 230 8 231 13 201 228 232 136 233 19 79 204 234 315 323 235 131 236 1 54 104 237 238 223 239 15 95 96 120 326 240 203 241 93 181 242 243 244 66 245 246 246 261 247 103 306 248 300 249 72 196 206 250 203 212 235 251 117 149 252 127 231 253 133 254 141 180 246 255 7 14 78 206 216 256 230 257 262 271 325 258 20 106 259 134 201 260 144 227 268 261 87 170 262 85 119 263 155 264 265 201 266 231 267 182 249 264 268 127 194 269 270 271 64 327 272 71 273 154 214 277 274 275 276 22 277 278 92 285 279 280 201 281 219 236 282 80 81 283 284 123 230 285 81 96 286 276 287 64 218 263 288 233 306 289 293 290 291 292 165 270 293 76 193 211 294 295 48 88 296 185 297 31 298 102 154 299 300 301 56 171 327 302 15 51 291 303 304 168 305 53 243 306 193 307 308 58 131 309 22 310 311 120 312 17 205 313 112 314 188 315 115 207 316 317 318 144 319 237 320 321 322 129 323 324 325 93 319 326 327 328 52 190 329 175 330 131 159
8.439394
21
0.727828
eda37a27ea4b77dd156cf609d46a2274d07eaf8b
384
pm
Perl
auto-lib/Paws/GameLift/ResolveAliasOutput.pm
galenhuntington/aws-sdk-perl
13b775dcb5f0b3764f0a82f3679ed5c7721e67d3
[ "Apache-2.0" ]
null
null
null
auto-lib/Paws/GameLift/ResolveAliasOutput.pm
galenhuntington/aws-sdk-perl
13b775dcb5f0b3764f0a82f3679ed5c7721e67d3
[ "Apache-2.0" ]
1
2021-05-26T19:13:58.000Z
2021-05-26T19:13:58.000Z
auto-lib/Paws/GameLift/ResolveAliasOutput.pm
galenhuntington/aws-sdk-perl
13b775dcb5f0b3764f0a82f3679ed5c7721e67d3
[ "Apache-2.0" ]
null
null
null
package Paws::GameLift::ResolveAliasOutput; use Moose; has FleetId => (is => 'ro', isa => 'Str'); has _request_id => (is => 'ro', isa => 'Str'); ### main pod documentation begin ### =head1 NAME Paws::GameLift::ResolveAliasOutput =head1 ATTRIBUTES =head2 FleetId => Str Fleet identifier that is associated with the requested alias. =head2 _request_id => Str =cut 1;
14.222222
61
0.671875
ed0846049bbd4bba191434ddba1042ccd54b3032
2,292
pm
Perl
tools/winapi/setup.pm
imaami/wine
9711a73b2ee23ca2ab025a2d377147daec6f7507
[ "MIT" ]
null
null
null
tools/winapi/setup.pm
imaami/wine
9711a73b2ee23ca2ab025a2d377147daec6f7507
[ "MIT" ]
null
null
null
tools/winapi/setup.pm
imaami/wine
9711a73b2ee23ca2ab025a2d377147daec6f7507
[ "MIT" ]
null
null
null
# # Copyright 1999, 2000, 2001 Patrik Stridvall # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA # package setup; use strict; use warnings 'all'; BEGIN { use vars qw($VERSION @ISA @EXPORT @EXPORT_OK); require Exporter; @ISA = qw(Exporter); @EXPORT = qw(); @EXPORT_OK = qw($current_dir $wine_dir $winapi_dir); use vars qw($current_dir $wine_dir $winapi_dir); my $tool = $0; $tool =~ s%^(?:.*?/)?([^/]+)$%$1%; if(defined($current_dir) && defined($wine_dir) && defined($winapi_dir)) { # Nothing } elsif($0 =~ m%^(.*?)/?tools/([^/]+)/[^/]+$%) { my $dir = $2; if(defined($1) && $1 ne "") { $wine_dir = $1; } else { $wine_dir = "."; } require Cwd; my $cwd = Cwd::cwd(); if($wine_dir =~ /^\./) { $current_dir = "."; my $pwd; chomp($pwd = `pwd`); foreach my $n (1..((length($wine_dir) + 1) / 3)) { $pwd =~ s/\/([^\/]*)$//; $current_dir = "$1/$current_dir"; } $current_dir =~ s%/\.$%%; } elsif($wine_dir eq $cwd) { $wine_dir = "."; $current_dir = "."; } elsif($cwd =~ m%^$wine_dir/(.*?)?$%) { $current_dir = $1; $wine_dir = "."; foreach my $dir (split(m%/%, $current_dir)) { $wine_dir = "../$wine_dir"; } $wine_dir =~ s%/\.$%%; } else { print STDERR "$tool: You must run this tool in the main Wine directory or a sub directory\n"; exit 1; } $winapi_dir = "$wine_dir/tools/winapi"; $winapi_dir =~ s%^\./%%; push @INC, $winapi_dir; } else { print STDERR "$tool: You must run this tool in the main Wine directory or a sub directory\n"; exit 1; } } 1;
25.752809
98
0.600349
ed9c33978ef67489d93fb29077bd3f4390e9e63a
3,419
pm
Perl
network/hirschmann/standard/snmp/mode/processcount.pm
xdrive05/centreon-plugins
8227ba680fdfd2bb0d8a806ea61ec1611c2779dc
[ "Apache-2.0" ]
1
2021-03-16T22:20:32.000Z
2021-03-16T22:20:32.000Z
network/hirschmann/standard/snmp/mode/processcount.pm
xdrive05/centreon-plugins
8227ba680fdfd2bb0d8a806ea61ec1611c2779dc
[ "Apache-2.0" ]
null
null
null
network/hirschmann/standard/snmp/mode/processcount.pm
xdrive05/centreon-plugins
8227ba680fdfd2bb0d8a806ea61ec1611c2779dc
[ "Apache-2.0" ]
null
null
null
# # Copyright 2020 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package network::hirschmann::standard::snmp::mode::processcount; use base qw(centreon::plugins::mode); use strict; use warnings; sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { "warning:s" => { name => 'warning' }, "critical:s" => { name => 'critical' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); $self->{output}->option_exit(); } } sub run { my ($self, %options) = @_; $self->{snmp} = $options{snmp}; my $oid_hmCpuRunningProcesses = '.1.3.6.1.4.1.248.14.2.15.2.3.0'; my $result = $self->{snmp}->get_leef(oids => [$oid_hmCpuRunningProcesses], nothing_quit => 1); my $processcount = $result->{$oid_hmCpuRunningProcesses}; my $exit = $self->{perfdata}->threshold_check(value => $processcount, threshold => [ { label => 'critical', exit_litteral => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); $self->{output}->output_add(severity => $exit, short_msg => sprintf("Number of current processes running: %d", $processcount)); $self->{output}->perfdata_add(label => "nbproc", value => $processcount, warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), min => 0); $self->{output}->display(); $self->{output}->exit(); } 1; __END__ =head1 MODE Check number of processes. hmEnableMeasurement must be activated (value = 1). =over 8 =item B<--warning> Threshold warning (process count). =item B<--critical> Threshold critical (process count). =back =cut
33.519608
197
0.592863
ed8ab726b050dfa368bb646548b6f0633f8c69d7
703
pm
Perl
lib/perfSONAR_PS/NPToolkit/WebService/Auth.pm
candlerb/perl-shared
027b63874da5c5a4431afd0c4bbd78cef047b14d
[ "Apache-2.0" ]
7
2015-08-21T21:37:03.000Z
2022-03-21T08:25:35.000Z
lib/perfSONAR_PS/NPToolkit/WebService/Auth.pm
candlerb/perl-shared
027b63874da5c5a4431afd0c4bbd78cef047b14d
[ "Apache-2.0" ]
48
2015-09-01T14:21:25.000Z
2021-05-19T19:20:12.000Z
lib/perfSONAR_PS/NPToolkit/WebService/Auth.pm
candlerb/perl-shared
027b63874da5c5a4431afd0c4bbd78cef047b14d
[ "Apache-2.0" ]
3
2016-07-07T00:06:31.000Z
2020-11-26T10:32:52.000Z
package perfSONAR_PS::NPToolkit::WebService::Auth; use base 'Exporter'; use strict; our @EXPORT_OK = ( 'is_authenticated', 'unauthorized_output' ); sub is_authenticated { my $cgi = shift; my $authenticated = 0; return if (! defined $cgi); if( defined $cgi->auth_type() && $cgi->auth_type ne '' && defined $cgi->remote_user() ){ $authenticated = 1; } return $authenticated; } sub unauthorized_output { my $cgi = shift; my $header = ""; if ( !is_authenticated($cgi) ) { $header = $cgi->header( -type => "text/plain", -status => "401 Unauthorized", ); $header .= "Unauthorized"; } return $header; } 1;
22.677419
92
0.577525
ed8fce8aa80b6d03b97f1aada988d899aa78608a
65,154
pl
Perl
vendor/C/netpbm/buildtools/configure.pl
ownclo/jpeg-on-steroids
deef3d015f07c46fedeaf0cceaadd4b702e89838
[ "BSD-3-Clause" ]
2
2016-11-23T18:45:39.000Z
2017-08-28T14:45:50.000Z
vendor/C/netpbm/buildtools/configure.pl
ownclo/jpeg-on-steroids
deef3d015f07c46fedeaf0cceaadd4b702e89838
[ "BSD-3-Clause" ]
null
null
null
vendor/C/netpbm/buildtools/configure.pl
ownclo/jpeg-on-steroids
deef3d015f07c46fedeaf0cceaadd4b702e89838
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/perl -w require 5.000; use strict; use English; use File::Basename; use Cwd 'abs_path'; use Fcntl; use Config; #use File::Temp "tempfile"; Not available before Perl 5.6.1 my ($TRUE, $FALSE) = (1,0); # This program generates Makefile.config, which is included by all of the # Netpbm makefiles. You run this program as the first step in building # Netpbm. (The second step is 'make'). # This program is only a convenience. It is supported to create # Makefile.config any way you want. In fact, an easy way is to copy # Makefile.config.in and follow the instructions in the comments therein # to uncomment certain lines and make other changes. # Note that if you invoke 'make' without having first run 'configure', # the make will call 'configure' itself when it finds # 'Makefile.config' missing. That might look a little messy to the # user, but it isn't the normal build process. # The argument to this program is the filepath of the Makefile.config.in # file. If unspecified, the default is 'Makefile.config.in' in the # Netpbm source directory. # For explanations of the stuff we put in the make files, see the comments # in Makefile.config.in. # $testCc is the command we use to do test compiles. Note that test # compiles are never more than heuristics, because we may be configuring # a build that will happen on a whole different system, which will build # programs to run on a third system. my $testCc; #****************************************************************************** # # SUBROUTINES # #***************************************************************************** sub autoFlushStdout() { my $oldFh = select(STDOUT); $OUTPUT_AUTOFLUSH = $TRUE; select($oldFh); } sub prompt($$) { my ($prompt, $default) = @_; my $defaultPrompt = defined($default) ? $default : "?"; print("$prompt [$defaultPrompt] ==> "); my $response = <STDIN>; if (defined($response)) { chomp($response); if ($response eq "" && defined($default)) { $response = $default; } } else { print("\n"); die("End of file on Standard Input when expecting response to prompt"); } return $response; } sub tmpdir() { # This is our approximation of File::Spec->tmpdir(), which became part of # basic Perl some time after Perl 5.005_03. my $retval; if ($ENV{"TMPDIR"}) { $retval = $ENV{"TMPDIR"}; } else { if ($Config{'osvers'} eq "djgpp") { $retval = "/dev/env/DJDIR/tmp"; } else { $retval = "/tmp"; } } return $retval; } sub tempFile($) { # Here's what we'd do if we could expect Perl 5.6.1 or later, instead # of calling this subroutine: # my ($cFile, $cFileName) = tempfile("netpbmXXXX", # SUFFIX=>".c", # DIR=>File::Spec->tmpdir(), # UNLINK=>0); my ($suffix) = @_; my $fileName; local *file; # For some inexplicable reason, must be local, not my my $i; $i = 0; do { $fileName = tmpdir() . "/netpbm" . $i++ . $suffix; } until sysopen(*file, $fileName, O_RDWR|O_CREAT|O_EXCL); return(*file, $fileName); } sub commandExists($) { my ($command) = @_; #----------------------------------------------------------------------------- # Return TRUE iff a shell command $command exists. #----------------------------------------------------------------------------- # Note that it's significant that the redirection on the following # causes it to be executed in a shell. That makes the return code # from system() a lot different than if system() were to try to # execute the program directly. return(system("$command 1</dev/null 1>/dev/null 2>/dev/null")/256 != 127); } sub chooseTestCompiler($$) { my ($compiler, $testCcR) = @_; my $cc; if ($ENV{'CC'}) { $cc = $ENV{'CC'}; } else { if (commandExists('cc')) { $cc = 'cc'; } elsif (commandExists("gcc")) { $cc = 'gcc'; } } $$testCcR = $cc; } sub testCflags($) { my ($needLocal) = @_; my $cflags; $cflags = ""; # initial value if ($ENV{"CPPFLAGS"}) { $cflags = $ENV{"CPPFLAGS"}; } else { $cflags = ""; } if ($ENV{"CFLAGS"}) { $cflags .= " " . $ENV{"CFLAGS"}; } if ($needLocal) { $cflags .= " -I/usr/local/include"; } return $cflags; } sub testCompile($$$) { my ($cflags, $cSourceCodeR, $successR) = @_; #----------------------------------------------------------------------------- # Do a test compile of the program in @{$cSourceCodeR}. # # Return $$successR == $TRUE iff the compile succeeds (exit code 0). #----------------------------------------------------------------------------- my ($cFile, $cFileName) = tempFile(".c"); print $cFile @{$cSourceCodeR}; my ($oFile, $oFileName) = tempFile(".o"); # Note: we tried using /dev/null for the output file and got complaints # from the Sun compiler that it has the wrong suffix. 2002.08.09. my $compileCommand = "$testCc -c -o $oFileName $cflags $cFileName"; print ("Doing test compile: $compileCommand\n"); my $rc = system($compileCommand); unlink($oFileName); close($oFile); unlink($cFileName); close($cFile); $$successR = ($rc == 0); } sub displayIntroduction() { print("This is the Netpbm configurator. It is an interactive dialog " . "that\n"); print("helps you build the file 'Makefile.config' and prepare to build "); print("Netpbm.\n"); print("\n"); print("Do not be put off by all the questions. Configure gives you " . "the \n"); print("opportunity to make a lot of choices, but you don't have to. " . "If \n"); print("you don't have reason to believe you're smarter than Configure,\n"); print("just take the defaults (hit ENTER) and don't sweat it.\n"); print("\n"); print("If you are considering having a program feed answers to the " . "questions\n"); print("below, please read doc/INSTALL, because that's probably the " . "wrong thing to do.\n"); print("\n"); print("Hit ENTER to begin.\n"); my $response = <STDIN>; } sub askAboutCygwin() { print("Are you building in/for the Cygwin environment?\n"); print("\n"); my $default; if ($OSNAME eq "cygwin") { $default = "y"; } else { $default = "n"; } my $retval; while (!defined($retval)) { my $response = prompt("(y)es or (n)o", $default); if (uc($response) =~ /^(Y|YES)$/) { $retval = $TRUE; } elsif (uc($response) =~ /^(N|NO)$/) { $retval = $FALSE; } else { print("'$response' isn't one of the choices. \n" . "You must choose 'yes' or 'no' (or 'y' or 'n').\n"); } } return $retval; } sub askAboutDjgpp() { print("Are you building in/for the DJGPP environment?\n"); print("\n"); my $default; if ($OSNAME eq "dos") { $default = "y"; } else { $default = "n"; } my $retval; while (!defined($retval)) { my $response = prompt("(y)es or (n)o", $default); if (uc($response) =~ /^(Y|YES)$/) { $retval = $TRUE; } elsif (uc($response) =~ /^(N|NO)$/) { $retval = $FALSE; } else { print("'$response' isn't one of the choices. \n" . "You must choose 'yes' or 'no' (or 'y' or 'n').\n"); } } } sub computePlatformDefault($) { my ($defaultP) = @_; if ($OSNAME eq "linux") { $$defaultP = "gnu"; } elsif ($OSNAME eq "cygwin") { $$defaultP = "win"; } elsif ($OSNAME eq "dos") { # DJGPP says "dos" $$defaultP = "win"; } elsif ($OSNAME eq "aix" || $OSNAME eq "freebsd" || $OSNAME eq "darwin" || $OSNAME eq "amigaos") { $$defaultP = $OSNAME; } elsif ($OSNAME eq "solaris") { $$defaultP = "sun"; } elsif ($OSNAME eq "dec_osf") { $$defaultP = "tru64"; } else { print("Unrecognized OSNAME='$OSNAME'. No default possible\n"); } # OK - if you know what $OSNAME is on any other platform, send me a patch! } sub getPlatform() { my $platform; my $default; computePlatformDefault(\$default); print("Which of the following best describes your platform?\n"); print("gnu GNU/Linux\n"); print("sun Solaris or SunOS\n"); print("hp HP-UX\n"); print("aix AIX\n"); print("win Windows/DOS (Cygwin, DJGPP, Mingw32)\n"); print("tru64 Tru64\n"); print("irix Irix\n"); print("bsd NetBSD, BSD/OS\n"); print("openbsd OpenBSD\n"); print("freebsd FreeBSD\n"); print("darwin Darwin or Mac OS X\n"); print("amigaos Amiga\n"); print("unixware Unixware\n"); print("sco SCO OpenServer\n"); print("beos BeOS\n"); print("none none of these are even close\n"); print("\n"); my $response = prompt("Platform", $default); my %platform = ("gnu" => "GNU", "sun" => "SOLARIS", "hp" => "HP-UX", "aix" => "AIX", "tru64" => "TRU64", "irix" => "IRIX", "win" => "WINDOWS", "beos" => "BEOS", "bsd" => "NETBSD", "openbsd" => "OPENBSD", "freebsd" => "FREEBSD", "unixware" => "UNIXWARE", "sco" => "SCO", "darwin" => "DARWIN", "amigaos" => "AMIGA", "none" => "NONE" ); $platform = $platform{$response}; if (!defined($platform)) { print("'$response' isn't one of the choices.\n"); exit 8; } my $subplatform; if ($platform eq "WINDOWS") { my ($djgpp, $cygwin); if ($OSNAME eq "dos") { $djgpp = askAboutDjgpp(); if ($djgpp) { $cygwin = $FALSE; } else { $cygwin = askAboutCygwin(); } } else { $cygwin = askAboutCygwin(); if ($cygwin) { $djgpp = $FALSE; } else { $djgpp = askAboutDjgpp(); } } if ($cygwin) { $subplatform = "cygwin"; } elsif ($djgpp) { $subplatform = "djgpp"; } else { $subplatform = "other"; } } return($platform, $subplatform); } sub getCompiler($$) { my ($platform, $compilerR) = @_; #----------------------------------------------------------------------------- # Here are some of the issues surrounding choosing a compiler: # # - It's not just the name of the program we need -- different compilers # need different options. # # - There are basically two choices on any system: native compiler or # GNU compiler. That's all this program recognizes, anyway. On some, # native _is_ GNU, and we return 'gcc'. # # - A user may well have various compilers. Different releases, using # different standard libraries, for different target machines, etc. # # - The CC environment variable tells the default compiler. # # - In the absence of a CC environment variable, 'cc' is the default # compiler. # # - The user must be able to specify the compiler by overriding the CC # make variable (e.g. make CC=gcc2). # # - Configure needs to do test compiles. The test is best if it uses # the same compiler that the build eventually will use, but it's # useful even if not. # # The value this subroutine returns is NOT the command name to invoke the # compiler. It is simply "cc" to mean native compiler or "gcc" to mean # GNU compiler. #----------------------------------------------------------------------------- my %gccOptionalPlatform = ("SOLARIS" => 1, "TRU64" => 1, "SCO" => 1, "AIX" => 1, "HP-UX" => 1); my %gccUsualPlatform = ("GNU" => 1, "NETBSD" => 1, "OPENBSD" => 1, "FREEBSD" => 1, "DARWIN" => 1, ); if ($gccUsualPlatform{$platform}) { $$compilerR = "gcc"; } elsif ($gccOptionalPlatform{$platform}) { print("GNU compiler or native operating system compiler (cc)?\n"); print("\n"); my $default; if ($platform eq "SOLARIS" || $platform eq "SCO" ) { $default = "gcc"; } else { $default = "cc"; } my $response = prompt("gcc or cc", $default); if ($response eq "gcc") { $$compilerR = "gcc"; } elsif ($response eq "cc") { $$compilerR = "cc"; } else { print("'$response' isn't one of the choices. \n" . "You must choose 'gcc' or 'cc'.\n"); exit 12; } if ($$compilerR eq 'gcc' && !commandExists('gcc')) { print("WARNING: You selected the GNU compiler, " . "but do not appear to have a program " . "named 'gcc' in your PATH. This may " . "cause trouble later. You may need to " . "set the CC environment variable or CC " . "makefile variable or install 'gcc'\n"); } print("\n"); } else { $$compilerR = 'cc'; } } sub gccLinker() { #----------------------------------------------------------------------------- # Determine what linker Gcc on this system appears to use. # # Return either "gnu" or "sun" # # For now, we assume it must be either a GNU linker or Sun linker and # that all Sun linkers are fungible. # # If we can't tell, we assume it is the GNU linker. #----------------------------------------------------------------------------- # First, we assume that the compiler calls 'collect2' as the linker # front end. The specs file might specify some other program, but # it usually says 'collect2'. my $retval; my $collect2 = qx{gcc --print-prog-name=collect2}; if (defined($collect2)) { chomp($collect2); my $linker = qx{$collect2 -v 2>&1}; if (defined($linker) && $linker =~ m{GNU ld}) { $retval = "gnu"; } else { $retval = "sun"; } } else { $retval = "gnu"; } return $retval; } sub getLinker($$$$) { my ($platform, $compiler, $baseLinkerR, $viaCompilerR) = @_; my $baseLinker; if ($platform eq "SOLARIS") { $$viaCompilerR = $TRUE; while (!defined($$baseLinkerR)) { print("GNU linker or SUN linker?\n"); print("\n"); my $default; if ($compiler eq "gcc") { $default = gccLinker(); } else { $default = "sun"; } my $response = prompt("sun or gnu", $default); if ($response eq "gnu") { $$baseLinkerR = "GNU"; } elsif ($response eq "sun") { $$baseLinkerR = "SUN"; } else { print("'$response' isn't one of the choices. \n" . "You must choose 'sun' or 'gnu'.\n"); } print("\n"); } } else { $$viaCompilerR = $TRUE; $$baseLinkerR = "?"; } } sub libSuffix($) { my ($platform) = @_; #----------------------------------------------------------------------------- # Return the traditional suffix for the link-time library on platform # type $platform. # # Note that this information is used mainly for cosmetic purposes in this # this program and the Netpbm build, because the build typically removes # any suffix and uses link options such as "-ltiff" to link the library. # This leaves it up to the linker to supply the actual suffix. #----------------------------------------------------------------------------- my $suffix; if ($platform eq 'WINDOWS') { $suffix = '.dll'; } elsif ($platform eq 'AIX') { $suffix = '.a'; } elsif ($platform eq 'DARWIN') { $suffix = '.dylib'; } else { $suffix = '.so'; } } sub getLibTypes($$$$$$$$) { my ($platform, $subplatform, $default_target, $netpbmlibtypeR, $netpbmlibsuffixR, $shlibprefixlistR, $willBuildSharedR, $staticlib_tooR) = @_; print("Do you want libnetpbm to be statically linked or shared?\n"); print("\n"); my $default = ($default_target eq "merge") ? "static" : "shared"; my ($netpbmlibtype, $netpbmlibsuffix, $shlibprefixlist, $willBuildShared, $staticlib_too); my $response = prompt("static or shared", $default); if ($response eq "shared") { $willBuildShared = $TRUE; if ($platform eq "WINDOWS") { $netpbmlibtype = "dll"; $netpbmlibsuffix = "dll"; if ($subplatform eq "cygwin") { $shlibprefixlist = "cyg lib"; } } elsif ($platform eq "DARWIN") { $netpbmlibtype = "dylib"; $netpbmlibsuffix = "dylib"; } else { if ($platform eq "IRIX") { $netpbmlibtype = "irixshared"; } else { $netpbmlibtype = "unixshared"; } if ($platform eq "AIX") { $netpbmlibsuffix = "a"; } elsif ($platform eq "HP-UX") { $netpbmlibsuffix = "sl"; } else { $netpbmlibsuffix = "so"; } } } elsif ($response eq "static") { $willBuildShared = $FALSE; $netpbmlibtype = "unixstatic"; $netpbmlibsuffix = "a"; # targets, but needed for building # libopt } else { print("'$response' isn't one of the choices. \n" . "You must choose 'static' or 'shared'.\n"); exit 12; } print("\n"); # Note that we can't do both a static and shared library for AIX, because # they both have the same name: libnetpbm.a. if (($netpbmlibtype eq "unixshared" or $netpbmlibtype eq "irixshared" or $netpbmlibtype eq "dll") and $netpbmlibsuffix ne "a") { print("Do you want to build static libraries too (for linking to \n"); print("programs not in the Netpbm package?\n"); print("\n"); my $default = "y"; my $response = prompt("(y)es or (n)o", $default); if (uc($response) =~ /^(Y|YES)$/) { $staticlib_too = "y"; } elsif (uc($response) =~ /^(N|NO)$/) { $staticlib_too = "n"; } else { print("'$response' isn't one of the choices. \n" . "You must choose 'yes' or 'no' (or 'y' or 'n').\n"); exit 12; } } else { $staticlib_too = "n"; } print("\n"); $$netpbmlibtypeR = $netpbmlibtype; $$netpbmlibsuffixR = $netpbmlibsuffix; $$shlibprefixlistR = $shlibprefixlist; $$willBuildSharedR = $willBuildShared; $$staticlib_tooR = $staticlib_too; } sub inttypesDefault() { my $retval; if (defined($testCc)) { print("(Doing test compiles to choose a default for you -- " . "ignore errors)\n"); my $cflags = testCflags($FALSE); my $works; # We saw a system (Irix 5.3 with native IDO, December 2005) on # which sys/types.h defines uint32_t, but not int32_t and other # similar types. We saw a Mac OS X system (January 2006) on which # sys/types sometimes defines uint32_t, but sometimes doesn't. # So we make those last resorts. # int_fastXXX_t are the least likely of all the types to be # defined, so we look for that. # Solaris 8, for example, has a <sys/inttypes.h> that defines # int32_t and uint32_t, but nothing the defines int_fast32_t. my @candidateList = ("<inttypes.h>", "<sys/inttypes.h>", "<types.h>", "<sys/types.h>"); for (my $i = 0; $i < @candidateList && !$works; ++$i) { my $candidate = $candidateList[$i]; my @cSourceCode = ( "#include $candidate\n", "int_fast32_t testvar;\n" ); testCompile($cflags, \@cSourceCode, \my $success); if ($success) { $works = $candidate; } } if ($works) { $retval = $works; } else { testCompile($cflags, ["int_fast32_t testvar;"], \my $success); if ($success) { $retval = "NONE"; } else { $retval = '"inttypes_netpbm.h"'; } } print("\n"); } else { $retval = '<inttypes.h>'; } return $retval; } sub getInttypes($) { my ($inttypesHeaderFileR) = @_; my $gotit; print("What header file defines uint32_t, etc.?\n"); print("\n"); my $default = inttypesDefault(); while (!$gotit) { my $response = prompt("'#include' argument or NONE", $default); if ($response eq "NONE") { $$inttypesHeaderFileR = ''; $gotit = $TRUE; } else { if ($response !~ m{<.+>} && $response !~ m{".+"}) { print("'$response' is not a legal argument of a C #include " . "statement. It must be something in <> or \"\".\n"); } else { $gotit = $TRUE; $$inttypesHeaderFileR = $response; } } } } sub getInt64($$) { my ($inttypes_h, $haveInt64R) = @_; if (defined($testCc)) { print("(Doing test compiles to determine if you have int64 type -- " . "ignore errors)\n"); my $cflags = testCflags($FALSE); my $works; my @cSourceCode = ( "#include $inttypes_h\n", "int64_t testvar;\n" ); testCompile($cflags, \@cSourceCode, \my $success); if ($success) { print("You do.\n"); $$haveInt64R = 'Y'; } else { print("You do not. 64-bit code won't be built.\n"); $$haveInt64R = 'N'; } print("\n"); } else { $$haveInt64R = "N"; } } # TODO: These should do test compiles to see if the headers are in the # default search path, both to create a default to offer and to issue a # warning after user has chosen. Also test links to test the link library. # It looks like these should all be in the default search paths and were there # just to override defaults in Makefile.config.in. Since Configure now # creates a default of "standard search path," I'm guessing we don't need # to set these anymore. sub getTiffLibrary($@) { my ($platform, @suggestedHdrDir) = @_; my $tifflib; { my $default = "libtiff" . libSuffix($platform); print("What is your TIFF (graphics format) library?\n"); my $response = prompt("library filename or 'none'", $default); if ($response ne "none") { $tifflib = $response; } if (defined($tifflib) and $tifflib =~ m{/} and !-f($tifflib)) { printf("WARNING: No regular file named '$tifflib' exists.\n"); } } my $tiffhdr_dir; if (defined($tifflib)) { my $default; if (-d("/usr/include/tiff")) { $default = "/usr/include/tiff"; } elsif (-d("/usr/include/libtiff")) { $default = "/usr/include/libtiff"; } else { $default = "default"; } print("Where are the interface headers for it?\n"); my $response = prompt("TIFF header directory", $default); if ($response ne "default") { $tiffhdr_dir = $response; } if (defined($tiffhdr_dir) and !-d($tiffhdr_dir)) { printf("WARNING: No directory named '$tiffhdr_dir' exists.\n"); } } return($tifflib, $tiffhdr_dir); } sub getJpegLibrary($@) { my ($platform, @suggestedHdrDir) = @_; my $jpeglib; { my $default = "libjpeg" . libSuffix($platform); print("What is your JPEG (graphics format) library?\n"); my $response = prompt("library filename or 'none'", $default); if ($response ne "none") { $jpeglib = $response; } } my $jpeghdr_dir; if (defined($jpeglib)) { my $default; if (-d("/usr/include/jpeg")) { $default = "/usr/include/jpeg"; } else { $default = "default"; } print("Where are the interface headers for it?\n"); my $response = prompt("JPEG header directory", $default); if ($response ne "default") { $jpeghdr_dir = $response; } if (defined($jpeghdr_dir) and !-d($jpeghdr_dir)) { printf("WARNING: No directory named '$jpeghdr_dir' exists.\n"); } } return($jpeglib, $jpeghdr_dir); } sub getPngLibrary($@) { my ($platform, @suggestedHdrDir) = @_; my ($pnglib, $pnghdr_dir); if (commandExists('libpng-config')) { # We don't need to ask where Libpng is; there's a 'libpng-config' # That tells exactly how to access it, and the make files will use # that. } else { { my $default = "libpng" . libSuffix($platform); print("What is your PNG (graphics format) library?\n"); my $response = prompt("library filename or 'none'", $default); if ($response ne "none") { $pnglib = $response; } } if (defined($pnglib)) { my $default; if (-d("/usr/include/png")) { $default = "/usr/include/libpng"; } else { $default = "default"; } print("Where are the interface headers for it?\n"); my $response = prompt("PNG header directory", $default); if ($response ne "default") { $pnghdr_dir = $response; } } } return($pnglib, $pnghdr_dir); } sub getZLibrary($@) { my ($platform, @suggestedHdrDir) = @_; my ($zlib, $zhdr_dir); { my $default = "libz" . libSuffix($platform); print("What is your Z (compression) library?\n"); my $response = prompt("library filename or 'none'", $default); if ($response ne "none") { $zlib = $response; } } if (defined($zlib)) { my $default; if (-d("/usr/include/zlib")) { $default = "/usr/include/zlib"; } else { $default = "default"; } print("Where are the interface headers for it?\n"); my $response = prompt("Z header directory", $default); if ($response ne "default") { $zhdr_dir = $response; } } return($zlib, $zhdr_dir); } sub getX11Library($@) { my ($platform, @suggestedHdrDir) = @_; my $x11lib; { my $default; if (-d('/usr/link/X11')) { $default = '/usr/link/X11/libX11' . libSuffix($platform); } elsif (-d('/usr/X11R6/lib')) { $default = '/usr/X11R6/lib/libX11' . libSuffix($platform); } else { $default = "libX11" . libSuffix($platform); } print("What is your X11 (X client) library?\n"); my $response = prompt("library filename or 'none'", $default); if ($response ne "none") { $x11lib = $response; } } my $x11hdr_dir; if (defined($x11lib)) { my $default; $default = "default"; print("Where are the interface headers for it?\n"); my $response = prompt("X11 header directory", $default); if ($response ne "default") { $x11hdr_dir = $response; } if (defined($x11hdr_dir)) { if (!-d($x11hdr_dir)) { printf("WARNING: No directory named '$x11hdr_dir' exists.\n"); } elsif (!-d("$x11hdr_dir/X11")) { printf("WARNING: Directory '$x11hdr_dir' does not contain " . "the requisite 'X11' subdirectory\n"); } } } return($x11lib, $x11hdr_dir); } sub getLinuxsvgaLibrary($@) { my ($platform, @suggestedHdrDir) = @_; my ($svgalib, $svgalibhdr_dir); if ($platform eq "GNU") { my $default; if (-d('/usr/link/svgalib')) { $default = '/usr/link/svgalib/libvga.so'; } elsif (-d('/usr/lib/svgalib')) { $default = '/usr/lib/svgalib/libvga.so'; } elsif (system('ldconfig -p | grep libvga >/dev/null 2>&1') == 0) { # &>/dev/null should work above, but on 12.03.26, it caused the # return value of system() always to be zero! $default = 'libvga.so'; } else { $default = 'none'; } print("What is your Svgalib library?\n"); my $response = prompt("library filename or 'none'", $default); if ($response ne 'none') { $svgalib = $response; } } if (defined($svgalib) && $svgalib ne 'none') { my $default; if (-d('/usr/include/svgalib')) { $default = '/usr/include/svgalib'; } else { $default = "default"; } print("Where are the interface headers for it?\n"); my $response = prompt("Svgalib header directory", $default); if ($response ne "default") { $svgalibhdr_dir = $response; } if (defined($svgalibhdr_dir)) { if (!-d($svgalibhdr_dir)) { printf("WARNING: No directory named " . "'$svgalibhdr_dir' exists.\n"); } } } return($svgalib, $svgalibhdr_dir); } sub symlink_command() { my $retval; # Some Windows environments don't have symbolic links (or even a # simulation via a "ln" command, but have a "cp" command which works # in a pinch. Some Windows environments have "ln", but it won't do # symbolic links. if (commandExists("ln")) { # We assume if Perl can do symbolic links, so can Ln, and vice # versa. my $symlink_exists = eval { symlink("",""); 1 }; if ($symlink_exists) { $retval = "ln -s"; } else { $retval = "ln"; } } elsif (commandExists("cp")) { $retval = "cp"; } else { # Well, maybe we just made a mistake. $retval = "ln -s"; } return $retval; } sub help() { print("This is the Netpbm custom configuration program. \n"); print("It is not GNU Configure.\n"); print("\n"); print("There is one optional argument to this program: The " . "name of the file to use as the basis for the Makefile.config " . "file. Default is 'Makefile.config.in'\n"); print("\n"); print("Otherwise, the program is interactive.\n"); } sub gnuOptimizeOpt($) { my ($gccCommandName) = @_; #----------------------------------------------------------------------------- # Compute the -O compiler flag appropriate for a GNU system. Ordinarily, # this is just -O3. But many popular GNU systems have a broken compiler # that causes -O3 to generate incorrect code (symptom: pnmtojpeg --quality=95 # generates a syntax error message from shhopt). #----------------------------------------------------------------------------- # I don't know what are exactly the cases that Gcc is broken. I know # Red Hat 7.1 and 7.2 and Mandrake 8.2, running gcc 2.96.1, commonly have # the problem. But it may be limited to a certain subrelease level or # CPU type or other environment. People who have reported the problem have # reported that Gcc 3.0 doesn't have it. Gcc 2.95.3 doesn't have it. # Note that automatic inlining happens at -O3 level, but there are some # subroutines in Netpbm marked for explicit inlining, and we need to disable # that inlining too, so we must go all the way down to -O0. my @gccVerboseResp = `$gccCommandName --verbose 2>&1`; my $brokenCompiler; if (@gccVerboseResp ==2) { if ($gccVerboseResp[1] =~ m{gcc version 2.96}) { $brokenCompiler = $TRUE; } else { $brokenCompiler = $FALSE; } } else { $brokenCompiler = $FALSE; } my $oOpt; if ($brokenCompiler) { print("You appear to have a broken compiler which would produce \n"); print("incorrect code if requested to do inline optimization.\n"); print("Therefore, I am configuring the build to not do inline \n"); print("optimization. This will make some Netpbm programs \n"); print("noticeably slower. If I am wrong about your compiler, just\n"); print("edit Makefile.config and change -O0 to -O3 near the bottom.\n"); print("\n"); print("The problem is known to exist in the GNU Compiler \n"); print("release 2.96. If you upgrade, you will not have this \n"); print("problem.\n"); print("---------------------------------------------\n"); print("\n"); $oOpt = "-O0"; } else { $oOpt = "-O3"; } return $oOpt; } sub needLocal($) { #----------------------------------------------------------------------------- # Return wether or not /usr/local paths must be added to compiles and # links. In a properly configured system, those paths should be in # the compiler and linker default search paths, e.g. the compiler # should search /usr/local/include and then /usr/include without any # -I options needed. But we've seen some systems where it isn't. # # Actually, I have doubts now as to whether these misconfigured systems # really exist. This subroutine was apparently always broken, because # before 04.03.15, it had "netbsd", etc. in lower case. So it always # returned false. I never had a complaint. Plus, we had a bug in # Makefile.config.in wherein it wiped out the user's setting of the LDFLAGS # environment variable. This could explain /usr/local/lib not being in # the path when it should have been. # # So I've disabled this function; we'll see if we encounter any truly # misconfigured systems. 04.03.15. #----------------------------------------------------------------------------- my ($platform) = @_; return $FALSE; # See comments above. my $needLocal; if ($platform eq "NETBSD" || $platform eq "OPENBSD" || $platform eq "FREEBSD") { $needLocal = $TRUE; } else { $needLocal = $FALSE; } return $needLocal; } sub findProcessManagement($) { my ($dontHaveProcessMgmtR) = @_; #----------------------------------------------------------------------------- # Return $TRUE iff the system does not have <sys/wait.h> in its default # search path. #----------------------------------------------------------------------------- my $cflags = testCflags($FALSE); my @cSourceCode = ( "#include <sys/wait.h>\n", ); testCompile($cflags, \@cSourceCode, \my $success); if (!$success) { print("Your system does not appear to have <sys/wait.h> in its " . "standard compiler include path. Therefore, we will build " . "Netpbm with some function missing (e.g. the pm_system() " . "function in libnetpbm and most of 'pamlookup'\n"); $$dontHaveProcessMgmtR = $TRUE; } else { $$dontHaveProcessMgmtR = $FALSE; } } sub validateLibraries(@) { my @libList = @_; #----------------------------------------------------------------------------- # Check each library name in the list @libList for viability. #----------------------------------------------------------------------------- foreach my $libname (@libList) { if (defined($libname)) { if ($libname =~ m{/} and !-f($libname)) { print("WARNING: No regular file named '$libname' exists.\n"); } elsif (!($libname =~ m{ .* \. (so|a|sa|sl|dll|dylib) $ }x)) { print("WARNING: The library name '$libname' does not have " . "a conventional suffix (.so, .a, .dll, etc.)\n"); } } } } sub warnJpegTiffDependency($$) { my ($jpeglib, $tifflib) = @_; if (defined($tifflib) && !defined($jpeglib)) { print("WARNING: You say you have a Tiff library, " . "but no Jpeg library.\n"); print("Sometimes the Tiff library prerequires the " . "Jpeg library. If \n"); print("that is the case on your system, you will " . "have some links fail with\n"); print("missing 'jpeg...' symbols. If so, rerun " . "Configure and say you\n"); print("have no Tiff library either.\n"); print("\n"); } } sub testCompileJpeglibH($$) { my ($cflags, $successR) = @_; #----------------------------------------------------------------------------- # Do a test compile to see if we can see jpeglib.h. #----------------------------------------------------------------------------- my @cSourceCode = ( "#include <ctype.h>\n", "#include <stdio.h>\n", "#include <jpeglib.h>\n", ); testCompile($cflags, \@cSourceCode, $successR); } sub testCompileJpegMarkerStruct($$) { my ($cflags, $successR) = @_; #----------------------------------------------------------------------------- # Do a test compile to see if struct jpeg_marker_struct is defined in # jpeglib.h. Assume it is already established that the compiler works # and can find jpeglib.h. #----------------------------------------------------------------------------- my @cSourceCode = ( "#include <ctype.h>\n", "#include <stdio.h>\n", "#include <jpeglib.h>\n", "struct jpeg_marker_struct test;\n", ); testCompile($cflags, \@cSourceCode, $successR); } sub printMissingHdrWarning($$) { my ($name, $hdr_dir) = @_; print("WARNING: You said the compile-time part of the $name library " . "(the header\n"); print("files) is in "); if (defined($hdr_dir)) { print("directory '$hdr_dir', "); } else { print("the compiler's default search path, "); } print("but a test compile failed\n"); print("to confirm that. If your configuration is exotic, the test " . "compile might\n"); print("just be wrong, but otherwise the Netpbm build will fail.\n"); print("\n"); print("To fix this, either install the $name library there \n"); print("or re-run Configure and answer the question about the $name " . "library\n"); print("differently.\n"); print("\n"); } sub printOldJpegWarning() { print("WARNING: Your JPEG library appears to be too old for Netpbm.\n"); print("We base this conclusion on the fact that jpeglib.h apparently\n"); print("does not define struct jpeg_marker_struct.\n"); print("If the JPEG library is not Independent Jpeg Group's Version 6b\n"); print("or better, the Netpbm build will fail when it attempts to build\n"); print("the parts that use the JPEG library.\n"); print("\n"); print("If your configuration is exotic, this test may just be wrong.\n"); print("Otherwise, either upgrade your JPEG library or re-run Configure\n"); print("and say you don't have a JPEG library.\n"); print("\n"); } sub testJpegHdr($$) { my ($needLocal, $jpeghdr_dir) = @_; if (defined($testCc)) { my $generalCflags = testCflags($needLocal); my $jpegIOpt = $jpeghdr_dir ? "-I$jpeghdr_dir" : ""; testCompileJpeglibH("$generalCflags $jpegIOpt", \my $success); if (!$success) { print("\n"); printMissingHdrWarning("JPEG", $jpeghdr_dir); } else { # We can get to something named jpeglib.h, but maybe it's an old # version we can't use. Check it out. testCompileJpegMarkerStruct("$generalCflags $jpegIOpt", \my $success); if (!$success) { print("\n"); printOldJpegWarning(); } } } } sub testCompileZlibH($$) { my ($cflags, $successR) = @_; #----------------------------------------------------------------------------- # Do a test compile to see if we can see zlib.h. #----------------------------------------------------------------------------- my @cSourceCode = ( "#include <zlib.h>\n", ); testCompile($cflags, \@cSourceCode, $successR); } sub testCompilePngH($$) { my ($cflags, $successR) = @_; #----------------------------------------------------------------------------- # Do a test compile to see if we can see png.h, assuming we can see # zlib.h, which png.h #includes. #----------------------------------------------------------------------------- my @cSourceCode = ( "#include <png.h>\n", ); testCompile($cflags, \@cSourceCode, $successR); } sub testPngHdr($$$) { #----------------------------------------------------------------------------- # Issue a warning if the compiler can't find png.h. #----------------------------------------------------------------------------- my ($needLocal, $pnghdr_dir, $zhdr_dir) = @_; if (defined($testCc)) { my $generalCflags = testCflags($needLocal); my $zlibIOpt = $zhdr_dir ? "-I$zhdr_dir" : ""; testCompileZlibH("$generalCflags $zlibIOpt", \my $success); if (!$success) { print("\n"); printMissingHdrWarning("Zlib", $zhdr_dir); } else { my $pngIOpt = $pnghdr_dir ? "-I$pnghdr_dir" : ""; testCompilePngH("$generalCflags $zlibIOpt $pngIOpt", \my $success); if (!$success) { print("\n"); printMissingHdrWarning("PNG", $pnghdr_dir); } } } } sub testLibpngConfig($) { my ($needLocal) = @_; #----------------------------------------------------------------------------- # Issue a warning if the instructions 'libpng-config' give for compiling # with Libpng don't work. #----------------------------------------------------------------------------- my $generalCflags = testCflags($needLocal); my $pngCflags = qx{libpng-config --cflags}; chomp($pngCflags); testCompilePngH("$generalCflags $pngCflags", \my $success); if (!$success) { print("\n"); print("Unable to compile a test PNG program using the compiler " . "flags that libpng-config says to use: '$pngCflags'.\n"); print("This indicates that you have Libpng installed incorrectly.\n"); print("libpng-config gets installed as part of the Libpng package.\n"); } else { } } sub testConfiguration($$$$$$$) { my ($needLocal, $jpeglib, $jpeghdr_dir, $pnglib, $pnghdr_dir, $zlib, $zhdr_dir) = @_; if (defined($jpeglib)) { testJpegHdr($needLocal, $jpeghdr_dir); } if (defined($pnglib) && defined($zlib)) { testPngHdr($needLocal, $pnghdr_dir, $zhdr_dir); } elsif (commandExists('libpng-config')) { testLibpngConfig($needLocal); } # TODO: We ought to validate other libraries too. But it's not # that important, because in the vast majority of cases where the # user incorrectly identifies any library, it affects all the # libraries and if the user can get a handle on the JPEG library # problem, he will also solve problems with any other library. } #****************************************************************************** # # MAINLINE # #***************************************************************************** autoFlushStdout(); my $configInPathArg; if (@ARGV > 0) { if ($ARGV[0] =~ "^-") { if ($ARGV[0] eq "--help") { help(); exit(0); } else { die("Unrecognized option: $ARGV[0]"); } } $configInPathArg = $ARGV[0]; } if (stat("Makefile.config")) { print("Discard existing Makefile.config?\n"); print("Y or N (N) ==> "); my $answer = <STDIN>; if (!defined($answer)) { die("\nEnd of file on Standard Input"); } chomp($answer); if (uc($answer) ne "Y") { print("Aborting at user request.\n"); exit(1); } } print("\n"); displayIntroduction(); my ($platform, $subplatform) = getPlatform(); print("\n"); if ($platform eq "NONE") { print("You will have to construct Makefile.config manually. To do \n"); print("this, copy Makefile.config.in as Makefile.config, and then \n"); print("edit it. Follow the instructions and examples in the file. \n"); print("Please report your results to the Netpbm maintainer so he \n"); print("can improve the configure program. \n"); exit; } getCompiler($platform, \my $compiler); getLinker($platform, $compiler, \my $baseLinker, \my $linkViaCompiler); chooseTestCompiler($compiler, \$testCc); my $netpbmlib_runtime_path; # Undefined if the default from Makefile.config.in is acceptable. if ($platform eq "SOLARIS" or $platform eq "IRIX" or $platform eq "DARWIN" or $platform eq "NETBSD" or $platform eq "AMIGA") { print("Where will the Netpbm shared library reside once installed?\n"); print("Enter 'default' if it will reside somewhere that the shared\n"); print("library loader will find it automatically. Otherwise, \n"); print("this directory will get built into the Netpbm programs.\n"); print("\n"); my $default = "default"; my $response = prompt("Netpbm shared library directory", $default); if ($response eq "default") { $netpbmlib_runtime_path = ""; } else { $netpbmlib_runtime_path = $response; } } my $default_target; print("Do you want a regular build or a merge build?\n"); print("If you don't know what this means, " . "take the default or see doc/INSTALL\n"); print("\n"); { my $default = "regular"; my $response = prompt("regular or merge", $default); if ($response eq "regular") { $default_target = "nonmerge"; } elsif ($response eq "merge") { $default_target = "merge"; } else { print("'$response' isn't one of the choices. \n" . "You must choose 'regular' or 'merge'.\n"); exit 12; } } print("\n"); getLibTypes($platform, $subplatform, $default_target, \my $netpbmlibtype, \my $netpbmlibsuffix, \my $shlibprefixlist, \my $willBuildShared, \my $staticlib_too); getInttypes(\my $inttypesHeaderFile); getInt64($inttypesHeaderFile, \my $haveInt64); findProcessManagement(\my $dontHaveProcessMgmt); #****************************************************************************** # # FIND THE PREREQUISITE LIBRARIES # #***************************************************************************** print("\n\n"); print("The following questions concern the subroutine libraries that are " . "Netpbm\n"); print("prerequisites. Every library has a compile-time part (header " . "files)\n"); print("and a link-time part. In the case of a shared library, these are " . "both\n"); print("part of the \"development\" component of the library, which may be " . "separately\n"); print("installable from the runtime shared library. For each library, you " . "must\n"); print("give the filename of the link library. If it is not in your " . "linker's\n"); print("default search path, give the absolute pathname of the file. In " . "addition,\n"); print("you will be asked for the directory in which the library's interface " . "headers\n"); print("reside, and you can respond 'default' if they are in your compiler's " . "default\n"); print("search path.\n"); print("\n"); print("If you don't have the library on your system, you can enter 'none' " . "as the\n"); print("library filename and the builder will skip any part that requires " . "that "); print("library.\n"); print("\n"); my ($jpeglib, $jpeghdr_dir) = getJpegLibrary($platform); print("\n"); my ($tifflib, $tiffhdr_dir) = getTiffLibrary($platform, $jpeghdr_dir); print("\n"); my ($pnglib, $pnghdr_dir) = getPngLibrary($platform, $tiffhdr_dir, $jpeghdr_dir); print("\n"); my ($zlib, $zhdr_dir) = getZLibrary($platform, $pnghdr_dir, $tiffhdr_dir, $jpeghdr_dir); print("\n"); my ($x11lib, $x11hdr_dir) = getX11Library($platform); print("\n"); my ($linuxsvgalib, $linuxsvgahdr_dir) = getLinuxsvgaLibrary($platform); print("\n"); # We should add the JBIG and URT libraries here too. They're a little # more complicated because there are versions shipped with Netpbm. #****************************************************************************** # # CONFIGURE DOCUMENTATION # #***************************************************************************** print("What URL will you use for the main Netpbm documentation page?\n"); print("This information does not get built into any programs or libraries.\n"); print("It does not make anything actually install that web page.\n"); print("It is just for including in legacy man pages.\n"); print("\n"); my $default = "http://netpbm.sourceforge.net/doc/"; my $netpbm_docurl = prompt("Documentation URL", $default); print("\n"); #****************************************************************************** # # VALIDATE THE CONFIGURATION USER HAS SELECTED # #***************************************************************************** validateLibraries($jpeglib, $tifflib, $pnglib, $zlib); warnJpegTiffDependency($jpeglib, $tifflib); testConfiguration(needLocal($platform), $jpeglib, $jpeghdr_dir, $pnglib, $pnghdr_dir, $zlib, $zhdr_dir, ); #****************************************************************************** # # FIND THE NETPBM SOURCE TREE AND INITIALIZE BUILD TREE # #***************************************************************************** my $defaultConfigInPath; if (-f("GNUmakefile")) { # He's apparently running us in the source tree or an already set up # build directory. $defaultConfigInPath = "Makefile.config.in"; } else { my $srcdir; my $done; $done = $FALSE; while (!$done) { print("Where is the Netpbm source code?\n"); $srcdir = prompt("Netpbm source directory", abs_path(dirname($0) . "/..")); if (-f("$srcdir/GNUmakefile")) { $done = $TRUE; } else { print("That doesn't appear to contain Netpbm source code.\n"); print("There is no file named 'GNUmakefile' in it.\n"); print("\n"); } } unlink("GNUmakefile"); symlink("$srcdir/GNUmakefile", "GNUmakefile"); unlink("Makefile"); symlink("$srcdir/Makefile", "Makefile"); open(SRCDIR, ">Makefile.srcdir"); print(SRCDIR "SRCDIR = $srcdir\n"); close(SRCDIR); $defaultConfigInPath = "$srcdir/Makefile.config.in"; } sub makeCompilerGcc($) { my ($Makefile_configR) = @_; my $compileCommand = 'gcc'; push(@{$Makefile_configR}, "CC = $compileCommand\n"); push(@{$Makefile_configR}, gnuCflags($compileCommand)); } #****************************************************************************** # # BUILD Makefile.config # #***************************************************************************** sub gnuCflags($) { my ($gccCommandName) = @_; return("CFLAGS = " . gnuOptimizeOpt($gccCommandName) . " -ffast-math " . " -pedantic -fno-common " . "-Wall -Wno-uninitialized -Wmissing-declarations -Wimplicit " . "-Wwrite-strings -Wmissing-prototypes -Wundef\n"); } my @Makefile_config; # This is the complete Makefile.config contents. We construct it here # and ultimately write the whole thing out as Makefile.config. # First, we just read the 'Makefile.config.in' in my $configInPath; if (defined($configInPathArg)) { $configInPath = $configInPathArg; } else { $configInPath = $defaultConfigInPath; } open (CONFIG_IN,"<$configInPath") or die("Unable to open file '$configInPath' for input."); @Makefile_config = <CONFIG_IN>; unshift(@Makefile_config, "####This file was automatically created by 'configure.'\n", "####Many variables are set twice -- a generic setting, then \n", "####a system-specific override at the bottom of the file.\n", "####\n"); close(CONFIG_IN); # Now, add the variable settings that override the default settings that are # done by the Makefile.config.in contents. push(@Makefile_config, "\n\n\n\n"); push(@Makefile_config, "####Lines above were copied from Makefile.config.in " . "by 'configure'.\n"); push(@Makefile_config, "####Lines below were added by 'configure' based on " . "the $platform platform.\n"); if (defined($subplatform)) { push(@Makefile_config, "####subplatform '$subplatform'\n"); } push(@Makefile_config, "DEFAULT_TARGET = $default_target\n"); push(@Makefile_config, "NETPBMLIBTYPE=$netpbmlibtype\n"); push(@Makefile_config, "NETPBMLIBSUFFIX=$netpbmlibsuffix\n"); if (defined($shlibprefixlist)) { push(@Makefile_config, "SHLIBPREFIXLIST=$shlibprefixlist\n"); } push(@Makefile_config, "STATICLIB_TOO=$staticlib_too\n"); if (defined($netpbmlib_runtime_path)) { push(@Makefile_config, "NETPBMLIB_RUNTIME_PATH=$netpbmlib_runtime_path\n"); } if ($platform eq "GNU") { my $compileCommand; if (!commandExists("cc") && commandExists("gcc")) { $compileCommand = "gcc"; push(@Makefile_config, "CC = $compileCommand\n"); } else { $compileCommand = "cc"; } push(@Makefile_config, gnuCflags($compileCommand)); # The merged programs have a main_XXX subroutine instead of main(), # which would cause a warning with -Wmissing-declarations or # -Wmissing-prototypes. push(@Makefile_config, "CFLAGS_MERGE = " . "-Wno-missing-declarations -Wno-missing-prototypes\n"); push(@Makefile_config, "LDRELOC = ld --reloc\n"); push(@Makefile_config, "LINKER_CAN_DO_EXPLICIT_LIBRARY=Y\n"); } elsif ($platform eq "SOLARIS") { push(@Makefile_config, 'LDSHLIB = -Wl,-Bdynamic,-G,-h,$(SONAME)', "\n"); push(@Makefile_config, 'NEED_RUNTIME_PATH = Y', "\n"); if ($compiler eq "cc") { push(@Makefile_config, "CFLAGS = -O\n"); push(@Makefile_config, "CFLAGS_SHLIB = -Kpic\n"); } else { makeCompilerGcc(\@Makefile_config); } # Before Netpbm 10.20 (January 2004), we set this to -R for # $compiler == cc and -rpath otherwise. But now we know that the GNU # compiler can also invoke a linker that needs -R, so we're more flexible. if ($baseLinker eq "GNU") { push(@Makefile_config, "RPATHOPTNAME = -rpath\n"); } else { push(@Makefile_config, "RPATHOPTNAME = -R\n"); } push(@Makefile_config, "NETWORKLD = -lsocket -lnsl\n"); } elsif ($platform eq "HP-UX") { if ($compiler eq "gcc") { makeCompilerGcc(\@Makefile_config); push(@Makefile_config, "CFLAGS += -fPIC\n"); push(@Makefile_config, "LDSHLIB = -shared -fPIC\n"); push(@Makefile_config, 'LDFLAGS += -Wl,+b,/usr/pubsw/lib', "\n"); } else { # We don't know what to do here. We used to (before 10.20) just # just assume the compiler was gcc. We know that the gcc stuff # above does NOT work for HP native compiler. push(@Makefile_config, "LDSHLIB =\n"); } } elsif ($platform eq "AIX") { push(@Makefile_config, 'LDFLAGS = -L /usr/pubsw/lib', "\n"); if ($compiler eq "cc") { # Yes, the -L option implies the runtime as well as linktime library # search path. There's no way to specify runtime path independently. push(@Makefile_config, "RPATHOPTNAME = -L\n"); push(@Makefile_config, "LDSHLIB = -qmkshrobj\n"); } else { makeCompilerGcc(\@Makefile_config); push(@Makefile_config, "LDSHLIB = -shared\n"); } } elsif ($platform eq "TRU64") { # push(@Makefile_config, "INSTALL = installbsd\n"); if ($compiler eq "cc") { push(@Makefile_config, 'CFLAGS = -O2 -std1', "\n"); push(@Makefile_config, "LDFLAGS = -call_shared -oldstyle_liblookup " . "-L/usr/local/lib\n"); push(@Makefile_config, "LDSHLIB = -shared -expect_unresolved \"*\"\n"); } else { # We've never tested this. This is just here to give a user a # headstart on submitting to us the necessary information. 2002.07.04. push(@Makefile_config, "CC = gcc\n"); push(@Makefile_config, 'CFLAGS = -O3', "\n"); push(@Makefile_config, "LDSHLIB = -shared\n"); } # Between May 2000 and July 2003, we had -DLONG_32 in these options. # We took it out because it generated bad code for a TRU64 user in # July 2003 whose system has 64 bit long and 32 bit int. It affects # only Ppmtompeg and it isn't clear that using long instead of int is # ever right anyway. push(@Makefile_config, "OMIT_NETWORK = y\n"); push(@Makefile_config, "LINKER_CAN_DO_EXPLICIT_LIBRARY=Y\n"); } elsif ($platform eq "IRIX") { # push(@Makefile_config, "INSTALL = install\n"); push(@Makefile_config, "MANPAGE_FORMAT = cat\n"); push(@Makefile_config, "RANLIB = true\n"); push(@Makefile_config, "CFLAGS = -n32 -O3 -fullwarn\n"); push(@Makefile_config, "LDFLAGS = -n32\n"); push(@Makefile_config, "LDSHLIB = -shared -n32\n"); } elsif ($platform eq "WINDOWS") { if ($subplatform eq "cygwin") { makeCompilerGcc(\@Makefile_config); } push(@Makefile_config, "EXE = .exe\n"); push(@Makefile_config, "OMIT_NETWORK = y\n"); # # Though it may not have the link as "ginstall", "install" in a Windows # # Unix environment is usually GNU install. # my $ginstall_result = `ginstall --version 2>/dev/null`; # if (!$ginstall_result) { # # System doesn't have 'ginstall', so use 'install' instead. # push(@Makefile_config, "INSTALL = install\n"); # } push(@Makefile_config, 'SYMLINK = ', symlink_command(), "\n"); push(@Makefile_config, 'DLLVER=$(NETPBM_MAJOR_RELEASE)', "\n"); push(@Makefile_config, "LDSHLIB = " . '-shared -Wl,--image-base=0x10000000 -Wl,--enable-auto-import', "\n"); } elsif ($platform eq "BEOS") { push(@Makefile_config, "LDSHLIB = -nostart\n"); } elsif ($platform eq "OPENBSD") { # vedge@vedge.com.ar says on 2001.04.29 that there are a ton of # undefined symbols in the Fiasco stuff on OpenBSD. So we'll just # cut it out of the build until someone feels like fixing it. push(@Makefile_config, "BUILD_FIASCO = N\n"); } elsif ($platform eq "FREEBSD") { } elsif ($platform eq "AMIGA") { push(@Makefile_config, "CFLAGS = -m68020-60 -ffast-math -mstackextend\n"); } elsif ($platform eq "UNIXWARE") { # Nothing to do. } elsif ($platform eq "SCO") { # Got this from "John H. DuBois III" <spcecdt@armory.com> 2002.09.27: push(@Makefile_config, "RANLIB = true\n"); if ($compiler eq "cc") { push(@Makefile_config, "CFLAGS = -O\n"); push(@Makefile_config, "CFLAGS_SHLIB = -O -K pic\n"); push(@Makefile_config, "LDSHLIB = -G\n"); push(@Makefile_config, "SHLIB_CLIB =\n"); } else { makeCompilerGcc(\@Makefile_config); push(@Makefile_config, "LDSHLIB = -shared\n"); } push(@Makefile_config, "NETWORKLD = -lsocket -lresolve\n"); } elsif ($platform eq "DARWIN") { push(@Makefile_config, "CC = cc -no-cpp-precomp\n"); push(@Makefile_config, 'CFLAGS_SHLIB = -fno-common', "\n"); push(@Makefile_config, "LDSHLIB = ", "-dynamiclib ", '-install_name $(NETPBMLIB_RUNTIME_PATH)/libnetpbm.$(MAJ).dylib', "\n"); # push(@Makefile_config, "INSTALL = install\n"); } else { die ("Internal error: invalid value for \$platform: '$platform'\n"); } if (needLocal($platform)) { push(@Makefile_config, "CFLAGS += -I/usr/local/include\n"); push(@Makefile_config, "LDFLAGS += -L/usr/local/lib\n"); } if ($linkViaCompiler) { push(@Makefile_config, "LINKERISCOMPILER = Y\n"); } my $flex_result = `flex --version`; if (!$flex_result) { # System doesn't have 'flex'. Maybe 'lex' will work. See the # make rules for Thinkjettopbm for information on our experiences # with Lexes besides Flex. my $systemRc = system('lex </dev/null >/dev/null 2>&1'); if ($systemRc >> 8 == 127) { print("\n"); print("You do not appear to have the 'flex' or 'lex' pattern \n"); print("matcher generator on your system, so we will not build \n"); print("programs that need it (Thinkjettopbm)\n"); print("\n"); print("Press ENTER to continue.\n"); my $key = <STDIN>; print("\n"); push(@Makefile_config, "LEX=\n"); } else { print("\n"); print("Using 'lex' as the pattern matcher generator, " . "since we cannot\n"); print("find 'flex' on your system.\n"); print("\n"); push(@Makefile_config, "LEX = lex\n"); } } if ($compiler eq 'gcc') { push(@Makefile_config, "CFLAGS_SHLIB += -fPIC\n"); } if (defined($tiffhdr_dir)) { push(@Makefile_config, "TIFFHDR_DIR = $tiffhdr_dir\n"); } if (defined($tifflib)) { push(@Makefile_config, "TIFFLIB = $tifflib\n"); } if (defined($jpeghdr_dir)) { push(@Makefile_config, "JPEGHDR_DIR = $jpeghdr_dir\n"); } if (defined($jpeglib)) { push(@Makefile_config, "JPEGLIB = $jpeglib\n"); } if (defined($pnghdr_dir)) { push(@Makefile_config, "PNGHDR_DIR = $pnghdr_dir\n"); } if (defined($pnglib)) { push(@Makefile_config, "PNGLIB = $pnglib\n"); } if (defined($zhdr_dir)) { push(@Makefile_config, "ZHDR_DIR = $zhdr_dir\n"); } if (defined($zlib)) { push(@Makefile_config, "ZLIB = $zlib\n"); } if (defined($x11hdr_dir)) { push(@Makefile_config, "X11HDR_DIR = $x11hdr_dir\n"); } if (defined($x11lib)) { push(@Makefile_config, "X11LIB = $x11lib\n"); } if (defined($linuxsvgahdr_dir)) { push(@Makefile_config, "LINUXSVGAHDR_DIR = $linuxsvgahdr_dir\n"); } if (defined($linuxsvgalib)) { push(@Makefile_config, "LINUXSVGALIB = $linuxsvgalib\n"); } if (defined($netpbm_docurl)) { push(@Makefile_config, "NETPBM_DOCURL = $netpbm_docurl\n"); } if ($inttypesHeaderFile ne '<inttypes.h>') { push(@Makefile_config, "INTTYPES_H = $inttypesHeaderFile\n"); } if ($haveInt64 ne 'Y') { push(@Makefile_config, "HAVE_INT64 = $haveInt64\n"); } if ($dontHaveProcessMgmt) { push(@Makefile_config, "DONT_HAVE_PROCESS_MGMT = Y\n"); } #****************************************************************************** # # WRITE OUT THE FILE # #***************************************************************************** open(MAKEFILE_CONFIG, ">Makefile.config") or die("Unable to open Makefile.config for writing in the current " . "directory."); print MAKEFILE_CONFIG @Makefile_config; close(MAKEFILE_CONFIG) or die("Error: Close of Makefile.config failed.\n"); print("\n"); print("We have created the file 'Makefile.config'. Note, however, that \n"); print("we guessed a lot at your configuration and you may want to look \n"); print("at Makefile.config and edit it to your requirements and taste \n"); print("before doing the make.\n"); print("\n"); print("Now you may proceed with 'make'\n"); print("\n"); exit 0;
30.675141
79
0.529284
eda9368c71de037cece47ee1aeea6ac9f817e2b4
3,920
pm
Perl
lib/Acme/SGABRIEL/Utils.pm
gitpan/Acme-SGABRIEL-Utils
22706ba254baaf6501265c343b597537a850232d
[ "Artistic-2.0", "Unlicense" ]
null
null
null
lib/Acme/SGABRIEL/Utils.pm
gitpan/Acme-SGABRIEL-Utils
22706ba254baaf6501265c343b597537a850232d
[ "Artistic-2.0", "Unlicense" ]
null
null
null
lib/Acme/SGABRIEL/Utils.pm
gitpan/Acme-SGABRIEL-Utils
22706ba254baaf6501265c343b597537a850232d
[ "Artistic-2.0", "Unlicense" ]
null
null
null
package Acme::SGABRIEL::Utils; use 5.006; use strict; use warnings FATAL => 'all'; use Exporter qw( import ); our @EXPORT = qw( sum ); =head1 NAME Acme::SGABRIEL::Utils - Provides a simple experimentation module per Intermediate Perl, Chapter 20, Exercises 1-4 =head1 VERSION Version 0.01 See the Acme::SGABRIEL::Utils::Test module's VERSION block for details =cut our $VERSION = '0.01'; =head1 SYNOPSIS Just provides the 'sum' subroutine =head1 EXPORT sum (default) =head1 SUBROUTINES/METHODS =head2 sub sum( number, number, ...) =cut sub sum { my @list_of_numbers = (@_); my $result = 0; $result *= $_ for @list_of_numbers; return $result; } =head1 AUTHOR Gabriel Sharp, C<< <osirisgothra at hotmail.com> >> =head1 BUGS Please report any bugs or feature requests to C<bug-acme::sgabriel::utils at rt.cpan.org>, or through the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Acme::SGABRIEL::Utils>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 SUPPORT You can find documentation for this module with the perldoc command. perldoc Acme::SGABRIEL::Utils You can also look for information at: =over 4 =item * RT: CPAN's request tracker (report bugs here) L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Acme::SGABRIEL::Utils> =item * AnnoCPAN: Annotated CPAN documentation L<http://annocpan.org/dist/Acme::SGABRIEL::Utils> =item * CPAN Ratings L<http://cpanratings.perl.org/d/Acme::SGABRIEL::Utils> =item * Search CPAN L<http://search.cpan.org/dist/Acme::SGABRIEL::Utils/> =back =head1 ACKNOWLEDGEMENTS Me, Myself, and I Brian d Foy - Apparently people are mad because you told people to upload to CPAN in your book 'Intermediate Perl' so if someone is mad this experimental module is here, go yell at him for it :) =head1 LICENSE AND COPYRIGHT Copyright 2014 Gabriel Sharp ...as if (ahem) ..as is This program is free software; you can redistribute it and/or modify it under the terms of the the Artistic License (2.0). You may obtain a copy of the full license at: L<http://www.perlfoundation.org/artistic_license_2_0> Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =cut 1; # End of Acme::SGABRIEL::Utils
28
130
0.765306
eda2b70d4fadad0be13d2763eb9dddeb348717d3
12,120
pm
Perl
lib/Cfn/Resource/AWS/EMR/InstanceFleetConfig.pm
lominorama/cfn-perl
d4aafdd58cc06fe749cd65f51ce5e08e67c30e3a
[ "Apache-2.0" ]
null
null
null
lib/Cfn/Resource/AWS/EMR/InstanceFleetConfig.pm
lominorama/cfn-perl
d4aafdd58cc06fe749cd65f51ce5e08e67c30e3a
[ "Apache-2.0" ]
null
null
null
lib/Cfn/Resource/AWS/EMR/InstanceFleetConfig.pm
lominorama/cfn-perl
d4aafdd58cc06fe749cd65f51ce5e08e67c30e3a
[ "Apache-2.0" ]
null
null
null
# AWS::EMR::InstanceFleetConfig generated from spec 2.25.0 use Moose::Util::TypeConstraints; coerce 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig', from 'HashRef', via { Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig->new( %$_ ) }; package Cfn::Resource::AWS::EMR::InstanceFleetConfig { use Moose; extends 'Cfn::Resource'; has Properties => (isa => 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig', is => 'rw', coerce => 1); sub AttributeList { [ ] } sub supported_regions { [ 'ap-northeast-1','ap-northeast-2','ap-northeast-3','ap-south-1','ap-southeast-1','ap-southeast-2','ca-central-1','eu-central-1','eu-north-1','eu-west-1','eu-west-2','eu-west-3','sa-east-1','us-east-1','us-east-2','us-west-1','us-west-2' ] } } subtype 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::VolumeSpecification', as 'Cfn::Value'; coerce 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::VolumeSpecification', from 'HashRef', via { if (my $f = Cfn::TypeLibrary::try_function($_)) { return $f } else { return Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::VolumeSpecificationValue->new( %$_ ); } }; package Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::VolumeSpecificationValue { use Moose; use MooseX::StrictConstructor; extends 'Cfn::Value::TypedValue'; has Iops => (isa => 'Cfn::Value::Integer', is => 'rw', coerce => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); has SizeInGB => (isa => 'Cfn::Value::Integer', is => 'rw', coerce => 1, required => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); has VolumeType => (isa => 'Cfn::Value::String', is => 'rw', coerce => 1, required => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); } subtype 'ArrayOfCfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::EbsBlockDeviceConfig', as 'Cfn::Value', where { $_->isa('Cfn::Value::Array') or $_->isa('Cfn::Value::Function') }, message { "$_ is not a Cfn::Value or a Cfn::Value::Function" }; coerce 'ArrayOfCfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::EbsBlockDeviceConfig', from 'HashRef', via { if (my $f = Cfn::TypeLibrary::try_function($_)) { return $f } else { die 'Only accepts functions'; } }, from 'ArrayRef', via { Cfn::Value::Array->new(Value => [ map { Moose::Util::TypeConstraints::find_type_constraint('Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::EbsBlockDeviceConfig')->coerce($_) } @$_ ]); }; subtype 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::EbsBlockDeviceConfig', as 'Cfn::Value'; coerce 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::EbsBlockDeviceConfig', from 'HashRef', via { if (my $f = Cfn::TypeLibrary::try_function($_)) { return $f } else { return Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::EbsBlockDeviceConfigValue->new( %$_ ); } }; package Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::EbsBlockDeviceConfigValue { use Moose; use MooseX::StrictConstructor; extends 'Cfn::Value::TypedValue'; has VolumeSpecification => (isa => 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::VolumeSpecification', is => 'rw', coerce => 1, required => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); has VolumesPerInstance => (isa => 'Cfn::Value::Integer', is => 'rw', coerce => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); } subtype 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::SpotProvisioningSpecification', as 'Cfn::Value'; coerce 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::SpotProvisioningSpecification', from 'HashRef', via { if (my $f = Cfn::TypeLibrary::try_function($_)) { return $f } else { return Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::SpotProvisioningSpecificationValue->new( %$_ ); } }; package Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::SpotProvisioningSpecificationValue { use Moose; use MooseX::StrictConstructor; extends 'Cfn::Value::TypedValue'; has BlockDurationMinutes => (isa => 'Cfn::Value::Integer', is => 'rw', coerce => 1, traits => [ 'CfnMutability' ], mutability => 'Mutable'); has TimeoutAction => (isa => 'Cfn::Value::String', is => 'rw', coerce => 1, required => 1, traits => [ 'CfnMutability' ], mutability => 'Mutable'); has TimeoutDurationMinutes => (isa => 'Cfn::Value::Integer', is => 'rw', coerce => 1, required => 1, traits => [ 'CfnMutability' ], mutability => 'Mutable'); } subtype 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::EbsConfiguration', as 'Cfn::Value'; coerce 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::EbsConfiguration', from 'HashRef', via { if (my $f = Cfn::TypeLibrary::try_function($_)) { return $f } else { return Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::EbsConfigurationValue->new( %$_ ); } }; package Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::EbsConfigurationValue { use Moose; use MooseX::StrictConstructor; extends 'Cfn::Value::TypedValue'; has EbsBlockDeviceConfigs => (isa => 'ArrayOfCfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::EbsBlockDeviceConfig', is => 'rw', coerce => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); has EbsOptimized => (isa => 'Cfn::Value::Boolean', is => 'rw', coerce => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); } subtype 'ArrayOfCfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::Configuration', as 'Cfn::Value', where { $_->isa('Cfn::Value::Array') or $_->isa('Cfn::Value::Function') }, message { "$_ is not a Cfn::Value or a Cfn::Value::Function" }; coerce 'ArrayOfCfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::Configuration', from 'HashRef', via { if (my $f = Cfn::TypeLibrary::try_function($_)) { return $f } else { die 'Only accepts functions'; } }, from 'ArrayRef', via { Cfn::Value::Array->new(Value => [ map { Moose::Util::TypeConstraints::find_type_constraint('Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::Configuration')->coerce($_) } @$_ ]); }; subtype 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::Configuration', as 'Cfn::Value'; coerce 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::Configuration', from 'HashRef', via { if (my $f = Cfn::TypeLibrary::try_function($_)) { return $f } else { return Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::ConfigurationValue->new( %$_ ); } }; package Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::ConfigurationValue { use Moose; use MooseX::StrictConstructor; extends 'Cfn::Value::TypedValue'; has Classification => (isa => 'Cfn::Value::String', is => 'rw', coerce => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); has ConfigurationProperties => (isa => 'Cfn::Value::Hash|Cfn::DynamicValue', is => 'rw', coerce => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); has Configurations => (isa => 'ArrayOfCfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::Configuration', is => 'rw', coerce => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); } subtype 'ArrayOfCfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::InstanceTypeConfig', as 'Cfn::Value', where { $_->isa('Cfn::Value::Array') or $_->isa('Cfn::Value::Function') }, message { "$_ is not a Cfn::Value or a Cfn::Value::Function" }; coerce 'ArrayOfCfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::InstanceTypeConfig', from 'HashRef', via { if (my $f = Cfn::TypeLibrary::try_function($_)) { return $f } else { die 'Only accepts functions'; } }, from 'ArrayRef', via { Cfn::Value::Array->new(Value => [ map { Moose::Util::TypeConstraints::find_type_constraint('Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::InstanceTypeConfig')->coerce($_) } @$_ ]); }; subtype 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::InstanceTypeConfig', as 'Cfn::Value'; coerce 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::InstanceTypeConfig', from 'HashRef', via { if (my $f = Cfn::TypeLibrary::try_function($_)) { return $f } else { return Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::InstanceTypeConfigValue->new( %$_ ); } }; package Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::InstanceTypeConfigValue { use Moose; use MooseX::StrictConstructor; extends 'Cfn::Value::TypedValue'; has BidPrice => (isa => 'Cfn::Value::String', is => 'rw', coerce => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); has BidPriceAsPercentageOfOnDemandPrice => (isa => 'Cfn::Value::Double', is => 'rw', coerce => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); has Configurations => (isa => 'ArrayOfCfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::Configuration', is => 'rw', coerce => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); has EbsConfiguration => (isa => 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::EbsConfiguration', is => 'rw', coerce => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); has InstanceType => (isa => 'Cfn::Value::String', is => 'rw', coerce => 1, required => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); has WeightedCapacity => (isa => 'Cfn::Value::Integer', is => 'rw', coerce => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); } subtype 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::InstanceFleetProvisioningSpecifications', as 'Cfn::Value'; coerce 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::InstanceFleetProvisioningSpecifications', from 'HashRef', via { if (my $f = Cfn::TypeLibrary::try_function($_)) { return $f } else { return Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::InstanceFleetProvisioningSpecificationsValue->new( %$_ ); } }; package Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::InstanceFleetProvisioningSpecificationsValue { use Moose; use MooseX::StrictConstructor; extends 'Cfn::Value::TypedValue'; has SpotSpecification => (isa => 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::SpotProvisioningSpecification', is => 'rw', coerce => 1, required => 1, traits => [ 'CfnMutability' ], mutability => 'Mutable'); } package Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig { use Moose; use MooseX::StrictConstructor; extends 'Cfn::Resource::Properties'; has ClusterId => (isa => 'Cfn::Value::String', is => 'rw', coerce => 1, required => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); has InstanceFleetType => (isa => 'Cfn::Value::String', is => 'rw', coerce => 1, required => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); has InstanceTypeConfigs => (isa => 'ArrayOfCfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::InstanceTypeConfig', is => 'rw', coerce => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); has LaunchSpecifications => (isa => 'Cfn::Resource::Properties::AWS::EMR::InstanceFleetConfig::InstanceFleetProvisioningSpecifications', is => 'rw', coerce => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); has Name => (isa => 'Cfn::Value::String', is => 'rw', coerce => 1, traits => [ 'CfnMutability' ], mutability => 'Immutable'); has TargetOnDemandCapacity => (isa => 'Cfn::Value::Integer', is => 'rw', coerce => 1, traits => [ 'CfnMutability' ], mutability => 'Mutable'); has TargetSpotCapacity => (isa => 'Cfn::Value::Integer', is => 'rw', coerce => 1, traits => [ 'CfnMutability' ], mutability => 'Mutable'); } 1;
45.909091
244
0.658168
edf0b08a79ce6bc8da82139a9f0b651b6276efeb
4,424
t
Perl
test/rule/Array.t
rewriting/tom
2918e95c78006f08a2a0919ef440413fa5c2342a
[ "BSD-3-Clause" ]
36
2016-02-19T12:09:49.000Z
2022-02-03T13:13:21.000Z
test/rule/Array.t
rewriting/tom
2918e95c78006f08a2a0919ef440413fa5c2342a
[ "BSD-3-Clause" ]
null
null
null
test/rule/Array.t
rewriting/tom
2918e95c78006f08a2a0919ef440413fa5c2342a
[ "BSD-3-Clause" ]
6
2017-11-30T17:07:10.000Z
2022-03-12T14:46:21.000Z
import aterm.*; import aterm.pure.*; import java.util.*; public class Array { private static ATermFactory factory = SingletonFactory.getInstance(); private AFun fzero, fsuc, fplus,ffib; public ATermAppl tzero; %typeterm L { implement { ArrayList } is_sort(t) { t instanceof ArrayList } equals(l1,l2) { l1.equals(l2) } } %oparray L conc( E* ) { is_fsym(t) { t instanceof ArrayList } make_empty(n) { new ArrayList(n) } make_append(e,l) { myAdd(e,(ArrayList)l) } get_element(l,n) { (ATerm)((ArrayList)l).get(n) } get_size(l) { ((ArrayList)l).size() } } private static ArrayList myAdd(Object e, ArrayList l) { l.add(e); return l; } %typeterm E { implement { ATerm } is_sort(t) { t instanceof Array } equals(t1, t2) { (t1.equals(t2)) } } %op E a() { is_fsym(t) { ((ATermAppl)t).getName() == "a" } make() { factory.makeAppl(factory.makeAFun("a", 0, false)) } } %op E b() { is_fsym(t) { ((ATermAppl)t).getName() == "b" } make() { factory.makeAppl(factory.makeAFun("b", 0, false)) } } %op E c() { is_fsym(t) { ((ATermAppl)t).getName() == "c" } make() { factory.makeAppl(factory.makeAFun("c", 0, false)) } } /* %op L double3(s1:L) { is_fsym(t) { ((ATermAppl)t).getName() == "double3" } //get_slot(s1,t) { return null; } make(l) { double3(l) } } %rule { double3(conc(X1*,x,X2*,x,X3*)) -> double3(conc(X1*,X2*,x,X3*)) double3(conc(X*)) -> conc(X*) } */ public final static void main(String[] args) { Array test = new Array(); test.testArray1(); } public void testArray1() { ATerm ta = factory.makeAppl(factory.makeAFun("a", 0, false)); ATerm tb = factory.makeAppl(factory.makeAFun("b", 0, false)); ATerm tc = factory.makeAppl(factory.makeAFun("c", 0, false)); ArrayList l = new ArrayList(); l.add(ta); l.add(tb); l.add(tc); l.add(ta); l.add(tb); l.add(tc); ArrayList res = new ArrayList(); res.add(ta); res.add(ta); res.add(tb); res.add(tb); res.add(tc); res.add(tc); assertTrue(sort1(l).equals(res)); assertTrue(sort2(l).equals(res)); } public void testArray2() { ArrayList l = `conc(a(),b(),c(),a(),b(),c(),a()); ArrayList res = `conc(a(),b(),c()); assertTrue(double1(sort1(l)).equals(res)); assertTrue(double2(sort2(l)).equals(res)); //assertTrue(double3(sort2(l)).equals(res)); assertTrue(double4(sort2(l)).equals(res)); assertTrue(double5(sort2(l)).equals(res)); } public ArrayList sort1(ArrayList l) { %match(L l) { conc(X1*,x,X2*,y,X3*) -> { String xname = ((ATermAppl)`x).getName(); String yname = ((ATermAppl)`y).getName(); if(xname.compareTo(yname) > 0) { ArrayList result = `X1; result.add(`y); result.addAll(`X2); result.add(`x); result.addAll(`X3); return sort1(result); } } } return l; } public ArrayList double1(ArrayList l) { %match(L l) { conc(X1*,x,X2*,x,X3*) -> { ArrayList result = `X1; result.addAll(`X2); result.add(`x); result.addAll(`X3); return double1(result); } } return l; } public ArrayList sort2(ArrayList l) { %match(L l) { conc(X1*,x,X2*,y,X3*) -> { String xname = ((ATermAppl)`x).getName(); String yname = ((ATermAppl)`y).getName(); if(xname.compareTo(yname) > 0) { return `sort2(conc(X1*,y,X2*,x,X3*)); } } } return l; } public ArrayList double2(ArrayList l) { %match(L l) { conc(X1*,x,X2*,x,X3*) -> { return `double2(conc(X1*,X2*,x,X3*)); } } return l; } public ArrayList double4(ArrayList l) { %match(L l) { conc(X1*,x@_,X2@_*,x,X3@_*) -> { return `double4(conc(X1*,X2*,x,X3*)); } } return l; } public ArrayList double5(ArrayList l) { %match(L l) { conc(X1*,x@a(),X2*,x@a(),X3*) -> { return `double5(conc(X1*,X2*,x,X3*)); } conc(X1*,x@_,X2*,x@_,X3*) -> { return `double5(conc(X1*,X2*,x,X3*)); } conc(X1*,x@y,X2*,y@x,X3*) -> { return `double5(conc(X1*,X2*,x,X3*)); } } return l; } static void assertTrue(boolean condition) { if(!condition) { throw new RuntimeException("assertion failed."); } } }
24.043478
80
0.541817
ede6c9e9f9a656c472e9bf7b1617480a99a0d18e
624
pm
Perl
lib/Circleator/FeatFunction/Numeric/read_depth.pm
jonathancrabtree/Circleator
ff9b0dc8a6af53a5ff894922d4e2495c649a7639
[ "Artistic-2.0" ]
36
2015-04-23T07:42:42.000Z
2022-02-22T15:56:05.000Z
lib/Circleator/FeatFunction/Numeric/read_depth.pm
jonathancrabtree/Circleator
ff9b0dc8a6af53a5ff894922d4e2495c649a7639
[ "Artistic-2.0" ]
20
2015-04-21T18:57:19.000Z
2021-10-30T14:15:26.000Z
lib/Circleator/FeatFunction/Numeric/read_depth.pm
jonathancrabtree/Circleator
ff9b0dc8a6af53a5ff894922d4e2495c649a7639
[ "Artistic-2.0" ]
8
2015-12-15T15:31:33.000Z
2021-12-16T10:46:19.000Z
package Circleator::FeatFunction::Numeric::read_depth; use Circleator::Parser::SNP; my $SNP = Circleator::Parser::SNP->new(); my $SNP_TP = $SNP->tag_prefix(); my $SNP_TBTP = $SNP->target_base_tag_prefix(); sub get_function { my($track, $tname) = @_; my $query = $track->{'snp-query'}; return sub { my $f = shift; my $ftype = $f->primary_tag(); die "snp_type can only be used on SNPs, not features of type $ftype" unless ($ftype eq 'SNP'); my $ad_key = 'DP'; if ($f->has_tag($ad_key)) { my @adepths = $f->get_tag_values($ad_key); return \@adepths; } return undef; }; } 1;
23.111111
98
0.615385
edbfa0d96ac9eaa393063894f5882408f5e7140d
1,732
pm
Perl
auto-lib/Paws/CloudDirectory/BatchRemoveFacetFromObject.pm
galenhuntington/aws-sdk-perl
13b775dcb5f0b3764f0a82f3679ed5c7721e67d3
[ "Apache-2.0" ]
null
null
null
auto-lib/Paws/CloudDirectory/BatchRemoveFacetFromObject.pm
galenhuntington/aws-sdk-perl
13b775dcb5f0b3764f0a82f3679ed5c7721e67d3
[ "Apache-2.0" ]
1
2021-05-26T19:13:58.000Z
2021-05-26T19:13:58.000Z
auto-lib/Paws/CloudDirectory/BatchRemoveFacetFromObject.pm
galenhuntington/aws-sdk-perl
13b775dcb5f0b3764f0a82f3679ed5c7721e67d3
[ "Apache-2.0" ]
null
null
null
package Paws::CloudDirectory::BatchRemoveFacetFromObject; use Moose; has ObjectReference => (is => 'ro', isa => 'Paws::CloudDirectory::ObjectReference', required => 1); has SchemaFacet => (is => 'ro', isa => 'Paws::CloudDirectory::SchemaFacet', required => 1); 1; ### main pod documentation begin ### =head1 NAME Paws::CloudDirectory::BatchRemoveFacetFromObject =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::CloudDirectory::BatchRemoveFacetFromObject object: $service_obj->Method(Att1 => { ObjectReference => $value, ..., SchemaFacet => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::CloudDirectory::BatchRemoveFacetFromObject object: $result = $service_obj->Method(...); $result->Att1->ObjectReference =head1 DESCRIPTION A batch operation to remove a facet from an object. =head1 ATTRIBUTES =head2 B<REQUIRED> ObjectReference => L<Paws::CloudDirectory::ObjectReference> A reference to the object whose facet will be removed. =head2 B<REQUIRED> SchemaFacet => L<Paws::CloudDirectory::SchemaFacet> The facet to remove from the object. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::CloudDirectory> =head1 BUGS and CONTRIBUTIONS The source code is located here: L<https://github.com/pplu/aws-sdk-perl> Please report bugs to: L<https://github.com/pplu/aws-sdk-perl/issues> =cut
27.492063
119
0.748268
ed7ad701c5cf14036819565a13d4f790c47ec2f7
6,831
pm
Perl
lib/perl/Bio/EnsEMBL/EGPipeline/BlastAlignment/FilterHits.pm
manuelcarbajo/ensembl-production-imported
3e3d28f8698415954b79fa67e6e9c71d9bc22cb0
[ "Apache-2.0" ]
null
null
null
lib/perl/Bio/EnsEMBL/EGPipeline/BlastAlignment/FilterHits.pm
manuelcarbajo/ensembl-production-imported
3e3d28f8698415954b79fa67e6e9c71d9bc22cb0
[ "Apache-2.0" ]
5
2021-05-26T13:41:58.000Z
2022-01-25T15:03:50.000Z
lib/perl/Bio/EnsEMBL/EGPipeline/BlastAlignment/FilterHits.pm
manuelcarbajo/ensembl-production-imported
3e3d28f8698415954b79fa67e6e9c71d9bc22cb0
[ "Apache-2.0" ]
3
2021-05-13T16:13:04.000Z
2021-07-01T11:57:42.000Z
=head1 LICENSE See the NOTICE file distributed with this work for additional information regarding copyright ownership. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut =pod =head1 NAME Bio::EnsEMBL::EGPipeline::BlastAlignment::FilterHits =head1 DESCRIPTION Retain the top X hits across a genome, by selecting those with the best E-value. Note that a single hit might map to multiple locations, but each of those alignments corresponds to unique protein sequence. In other words, the 'h' coordinates will not overlap. =head1 Author James Allen =cut package Bio::EnsEMBL::EGPipeline::BlastAlignment::FilterHits; use strict; use warnings; use base ('Bio::EnsEMBL::EGPipeline::Common::RunnableDB::Base'); sub param_defaults { return { 'db_type' => 'core', 'query_type' => 'dna', 'database_type' => 'pep', 'filter_top_x' => 1, 'create_gff' => 0, }; } sub run { my ($self) = @_; my $db_type = $self->param_required('db_type'); my $query_type = $self->param_required('query_type'); my $database_type = $self->param_required('database_type'); my $filter_top_x = $self->param_required('filter_top_x'); my $logic_name = $self->param_required('logic_name'); $self->dbc && $self->dbc->disconnect_if_idle(); if ($filter_top_x) { my $dba = $self->get_DBAdaptor($db_type); if ($database_type eq 'pep') { if ($query_type eq 'pep') { $self->best_pep_pep($dba, $filter_top_x, $logic_name); } else { $self->best_pep_dna($dba, $filter_top_x, $logic_name); } } else { $self->best_dna_dna($dba, $filter_top_x, $logic_name); } } } sub write_output { my ($self) = @_; my $create_gff = $self->param_required('create_gff'); my $logic_name = $self->param_required('logic_name'); if ($create_gff) { $self->dataflow_output_id({'logic_name' => [$logic_name]}, 2); } } sub best_dna_dna { my ($self, $dba, $top_x, $logic_name) = @_; my %grouped_features; my $sa = $dba->get_adaptor("Slice"); my $dafa = $dba->get_adaptor("DNAAlignFeature"); my $slices = $sa->fetch_all('toplevel'); foreach my $slice (@$slices) { my $dafs = $dafa->fetch_all_by_Slice($slice, $logic_name); $self->process_features($dafs, \%grouped_features); } $self->remove_features($top_x, $dafa, \%grouped_features); } sub best_pep_dna { my ($self, $dba, $top_x, $logic_name) = @_; my %grouped_features; my $sa = $dba->get_adaptor("Slice"); my $pafa = $dba->get_adaptor("ProteinAlignFeature"); my $slices = $sa->fetch_all('toplevel'); foreach my $slice (@$slices) { my $pafs = $pafa->fetch_all_by_Slice($slice, $logic_name); $self->process_features($pafs, \%grouped_features); } $self->remove_features($top_x, $pafa, \%grouped_features); } sub best_pep_pep { my ($self, $dba, $top_x, $logic_name) = @_; my %grouped_features; my $pfa = $dba->get_adaptor("ProteinFeature"); my $pfs = $pfa->fetch_all_by_logic_name($logic_name); $self->process_features($pfs, \%grouped_features); $self->remove_features($top_x, $pfa, \%grouped_features); } sub process_features { my ($self, $features, $grouped_features) = @_; my %features; foreach my $feature (@$features) { push @{$features{$feature->hseqname}}, $feature; } # For hits from the same source on a single seq_region, we want # to group them into sets within which the hits do not overlap. # This means that short hits that would otherwise be lost due to # E-value filtering are retained, by piggy-backing on the higher # scoring hits. foreach my $hit_name (keys %features) { my @features = sort {$a->p_value <=> $b->p_value or $b->score <=> $a->score} @{$features{$hit_name}}; my $groups = $self->group_features(\@features); push @{$$grouped_features{$hit_name}}, @$groups; } } sub group_features { my ($self, $features) = @_; my @groups; while (scalar(@$features)) { my $group = []; $self->disjoint($features, $features, $group); push @groups, $group; } return \@groups; } sub disjoint { my ($self, $features, $features_subset, $group) = @_; my $best_hit = shift @$features_subset; if (scalar(@$group)) { my $offset; for (my $i=0; $i < scalar(@$features); $i++) { if ($$features[$i]->dbID == $best_hit->dbID) { $offset = $i; last; } } splice(@$features, $offset, 1); } push @$group, $best_hit; my @disjoint = (); if (scalar(@$features_subset)) { foreach my $feature (@$features_subset) { if (! $self->hit_overlap($best_hit, $feature)) { push @disjoint, $feature; } } if (scalar(@disjoint)) { $self->disjoint($features, \@disjoint, $group); } } } sub remove_features { my ($self, $top_x, $adaptor, $grouped_features) = @_; # Because the features within each group are sorted such that the best # hit is first, we can sort the groups by sorting on the first element # of each. The top X are then removed from the front of the list of # grouped features, and whatever is left hasn't made the cut and is deleted. foreach my $hit_name (keys %$grouped_features) { my @groups = sort {$a->[0]->p_value <=> $b->[0]->p_value or $b->[0]->score <=> $a->[0]->score} @{$$grouped_features{$hit_name}}; splice(@groups, 0, $top_x); foreach my $group (@groups) { foreach my $feature (@$group) { if ($adaptor->isa('Bio::EnsEMBL::DBSQL::ProteinFeatureAdaptor')) { my $sth = $adaptor->prepare("DELETE FROM protein_feature WHERE protein_feature_id = ?"); $sth->execute($feature->dbID); } else { $adaptor->remove($feature); } } } } } sub hit_overlap { my ($self, $feature1, $feature2) = @_; # The important thing to note here is that we're checking # for overlapping _hit_ coordinates, not seq_region coordinates. my ($s1, $e1) = ($feature1->hstart, $feature1->hend); my ($s2, $e2) = ($feature2->hstart, $feature2->hend); my $overlap = 0; if ($s1 >= $s2 && $e1 <= $e2) { $overlap = 1; } elsif ($s1 <= $s2 && $e1 >= $e2) { $overlap = 2; } elsif ($e1 >= $s2 && $e1 <= $e2) { $overlap = 3; } elsif ($s1 >= $s2 && $s1 <= $e2) { $overlap = 4; } return $overlap; } 1;
26.788235
132
0.632411
ed7a825eba957813421cddc728f60dc11b4dca67
1,792
pm
Perl
lib/Zengin/Perl/Bank.pm
sironekotoro/Zengin-Perl
fdc1a6352537ba4d5a3002bf47c470ba11773f7b
[ "Artistic-1.0" ]
null
null
null
lib/Zengin/Perl/Bank.pm
sironekotoro/Zengin-Perl
fdc1a6352537ba4d5a3002bf47c470ba11773f7b
[ "Artistic-1.0" ]
4
2020-10-04T07:55:45.000Z
2020-10-18T14:06:55.000Z
lib/Zengin/Perl/Bank.pm
sironekotoro/Zengin-Perl
fdc1a6352537ba4d5a3002bf47c470ba11773f7b
[ "Artistic-1.0" ]
null
null
null
#!/usr/bin/env perl package Zengin::Perl::Bank; use Carp; use JSON qw/decode_json/; use Moo 2.004004; use Exporter 'import'; our @EXPORT = qw/branch/; map { has $_ => ( is => 'ro' ) } qw (code name hira kana roma _path); has branches => ( is => "ro", builder => "_branches_builder", lazy => 1, ); sub _branches_builder { my $self = shift; my $file; open my $FH, '<', $self->_path or die; { local $/; $file = <$FH>; } close $FH; my $branches = decode_json($file); my %branches = do { my %hash = (); while ( my ( $key, $value ) = each %{$branches} ) { $hash{$key} = Zengin::Perl::Branch->new($value); } %hash; }; return \%branches; } sub branch { my ( $self, %arg ) = @_; my $branch_code = $arg{branch_code}; return $self->branches->{$branch_code}; } sub branch_name_search { my ( $self, %arg ) = @_; my $branch_name = $arg{branch_name}; my @result = (); for my $branch_code ( sort keys %{ $self->branches } ) { my $branch = $self->branches->{$branch_code}; push @result, $branch if $branch->name =~ /$branch_name/; } return \@result; } sub branch_code_search { my ( $self, %arg ) = @_; my $branch_code = $arg{branch_code}; return $self->branch( branch_code => $branch_code ); } __PACKAGE__->meta->make_immutable(); 1; =encoding utf-8 =head1 NAME Zengin::Perl::Bank - Bank class =head1 METHODS =head2 branch =head2 branch_name_search =head2 branch_code_search =head1 LICENSE Copyright (C) sironekotoro. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 AUTHOR sironekotoro E<lt>develop@sironekotoro.comE<gt> =cut
17.92
69
0.59096
ede12644b815db7f85b3c02b1665b34a214ffbd9
8,831
pm
Perl
example-perl-psgi/.perl/lib/perl5/DateTime/TimeZone/Africa/Tripoli.pm
NINGONDA/apcera
60ccb872a56566bde41594546ba4e97e0d73eae0
[ "MIT" ]
null
null
null
example-perl-psgi/.perl/lib/perl5/DateTime/TimeZone/Africa/Tripoli.pm
NINGONDA/apcera
60ccb872a56566bde41594546ba4e97e0d73eae0
[ "MIT" ]
null
null
null
example-perl-psgi/.perl/lib/perl5/DateTime/TimeZone/Africa/Tripoli.pm
NINGONDA/apcera
60ccb872a56566bde41594546ba4e97e0d73eae0
[ "MIT" ]
null
null
null
# This file is auto-generated by the Perl DateTime Suite time zone # code generator (0.07) This code generator comes with the # DateTime::TimeZone module distribution in the tools/ directory # # Generated from /tmp/4wpj_fAzbR/africa. Olson data version 2016c # # Do not edit this file directly. # package DateTime::TimeZone::Africa::Tripoli; $DateTime::TimeZone::Africa::Tripoli::VERSION = '1.97'; use strict; use Class::Singleton 1.03; use DateTime::TimeZone; use DateTime::TimeZone::OlsonDB; @DateTime::TimeZone::Africa::Tripoli::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' ); my $spans = [ [ DateTime::TimeZone::NEG_INFINITY, # utc_start 60557756836, # utc_end 1919-12-31 23:07:16 (Wed) DateTime::TimeZone::NEG_INFINITY, # local_start 60557760000, # local_end 1920-01-01 00:00:00 (Thu) 3164, 0, 'LMT', ], [ 60557756836, # utc_start 1919-12-31 23:07:16 (Wed) 61560781200, # utc_end 1951-10-14 01:00:00 (Sun) 60557760436, # local_start 1920-01-01 00:07:16 (Thu) 61560784800, # local_end 1951-10-14 02:00:00 (Sun) 3600, 0, 'CET', ], [ 61560781200, # utc_start 1951-10-14 01:00:00 (Sun) 61567596000, # utc_end 1951-12-31 22:00:00 (Mon) 61560788400, # local_start 1951-10-14 03:00:00 (Sun) 61567603200, # local_end 1952-01-01 00:00:00 (Tue) 7200, 1, 'CEST', ], [ 61567596000, # utc_start 1951-12-31 22:00:00 (Mon) 61623507600, # utc_end 1953-10-09 01:00:00 (Fri) 61567599600, # local_start 1951-12-31 23:00:00 (Mon) 61623511200, # local_end 1953-10-09 02:00:00 (Fri) 3600, 0, 'CET', ], [ 61623507600, # utc_start 1953-10-09 01:00:00 (Fri) 61630754400, # utc_end 1953-12-31 22:00:00 (Thu) 61623514800, # local_start 1953-10-09 03:00:00 (Fri) 61630761600, # local_end 1954-01-01 00:00:00 (Fri) 7200, 1, 'CEST', ], [ 61630754400, # utc_start 1953-12-31 22:00:00 (Thu) 61685794800, # utc_end 1955-09-29 23:00:00 (Thu) 61630758000, # local_start 1953-12-31 23:00:00 (Thu) 61685798400, # local_end 1955-09-30 00:00:00 (Fri) 3600, 0, 'CET', ], [ 61685794800, # utc_start 1955-09-29 23:00:00 (Thu) 61693826400, # utc_end 1955-12-31 22:00:00 (Sat) 61685802000, # local_start 1955-09-30 01:00:00 (Fri) 61693833600, # local_end 1956-01-01 00:00:00 (Sun) 7200, 1, 'CEST', ], [ 61693826400, # utc_start 1955-12-31 22:00:00 (Sat) 61788524400, # utc_end 1958-12-31 23:00:00 (Wed) 61693830000, # local_start 1955-12-31 23:00:00 (Sat) 61788528000, # local_end 1959-01-01 00:00:00 (Thu) 3600, 0, 'CET', ], [ 61788524400, # utc_start 1958-12-31 23:00:00 (Wed) 62514367200, # utc_end 1981-12-31 22:00:00 (Thu) 61788531600, # local_start 1959-01-01 01:00:00 (Thu) 62514374400, # local_end 1982-01-01 00:00:00 (Fri) 7200, 0, 'EET', ], [ 62514367200, # utc_start 1981-12-31 22:00:00 (Thu) 62522146800, # utc_end 1982-03-31 23:00:00 (Wed) 62514370800, # local_start 1981-12-31 23:00:00 (Thu) 62522150400, # local_end 1982-04-01 00:00:00 (Thu) 3600, 0, 'CET', ], [ 62522146800, # utc_start 1982-03-31 23:00:00 (Wed) 62537954400, # utc_end 1982-09-30 22:00:00 (Thu) 62522154000, # local_start 1982-04-01 01:00:00 (Thu) 62537961600, # local_end 1982-10-01 00:00:00 (Fri) 7200, 1, 'CEST', ], [ 62537954400, # utc_start 1982-09-30 22:00:00 (Thu) 62553682800, # utc_end 1983-03-31 23:00:00 (Thu) 62537958000, # local_start 1982-09-30 23:00:00 (Thu) 62553686400, # local_end 1983-04-01 00:00:00 (Fri) 3600, 0, 'CET', ], [ 62553682800, # utc_start 1983-03-31 23:00:00 (Thu) 62569490400, # utc_end 1983-09-30 22:00:00 (Fri) 62553690000, # local_start 1983-04-01 01:00:00 (Fri) 62569497600, # local_end 1983-10-01 00:00:00 (Sat) 7200, 1, 'CEST', ], [ 62569490400, # utc_start 1983-09-30 22:00:00 (Fri) 62585305200, # utc_end 1984-03-31 23:00:00 (Sat) 62569494000, # local_start 1983-09-30 23:00:00 (Fri) 62585308800, # local_end 1984-04-01 00:00:00 (Sun) 3600, 0, 'CET', ], [ 62585305200, # utc_start 1984-03-31 23:00:00 (Sat) 62601112800, # utc_end 1984-09-30 22:00:00 (Sun) 62585312400, # local_start 1984-04-01 01:00:00 (Sun) 62601120000, # local_end 1984-10-01 00:00:00 (Mon) 7200, 1, 'CEST', ], [ 62601112800, # utc_start 1984-09-30 22:00:00 (Sun) 62617273200, # utc_end 1985-04-05 23:00:00 (Fri) 62601116400, # local_start 1984-09-30 23:00:00 (Sun) 62617276800, # local_end 1985-04-06 00:00:00 (Sat) 3600, 0, 'CET', ], [ 62617273200, # utc_start 1985-04-05 23:00:00 (Fri) 62632648800, # utc_end 1985-09-30 22:00:00 (Mon) 62617280400, # local_start 1985-04-06 01:00:00 (Sat) 62632656000, # local_end 1985-10-01 00:00:00 (Tue) 7200, 1, 'CEST', ], [ 62632648800, # utc_start 1985-09-30 22:00:00 (Mon) 62648636400, # utc_end 1986-04-03 23:00:00 (Thu) 62632652400, # local_start 1985-09-30 23:00:00 (Mon) 62648640000, # local_end 1986-04-04 00:00:00 (Fri) 3600, 0, 'CET', ], [ 62648636400, # utc_start 1986-04-03 23:00:00 (Thu) 62664357600, # utc_end 1986-10-02 22:00:00 (Thu) 62648643600, # local_start 1986-04-04 01:00:00 (Fri) 62664364800, # local_end 1986-10-03 00:00:00 (Fri) 7200, 1, 'CEST', ], [ 62664357600, # utc_start 1986-10-02 22:00:00 (Thu) 62679913200, # utc_end 1987-03-31 23:00:00 (Tue) 62664361200, # local_start 1986-10-02 23:00:00 (Thu) 62679916800, # local_end 1987-04-01 00:00:00 (Wed) 3600, 0, 'CET', ], [ 62679913200, # utc_start 1987-03-31 23:00:00 (Tue) 62695720800, # utc_end 1987-09-30 22:00:00 (Wed) 62679920400, # local_start 1987-04-01 01:00:00 (Wed) 62695728000, # local_end 1987-10-01 00:00:00 (Thu) 7200, 1, 'CEST', ], [ 62695720800, # utc_start 1987-09-30 22:00:00 (Wed) 62711535600, # utc_end 1988-03-31 23:00:00 (Thu) 62695724400, # local_start 1987-09-30 23:00:00 (Wed) 62711539200, # local_end 1988-04-01 00:00:00 (Fri) 3600, 0, 'CET', ], [ 62711535600, # utc_start 1988-03-31 23:00:00 (Thu) 62727343200, # utc_end 1988-09-30 22:00:00 (Fri) 62711542800, # local_start 1988-04-01 01:00:00 (Fri) 62727350400, # local_end 1988-10-01 00:00:00 (Sat) 7200, 1, 'CEST', ], [ 62727343200, # utc_start 1988-09-30 22:00:00 (Fri) 62743071600, # utc_end 1989-03-31 23:00:00 (Fri) 62727346800, # local_start 1988-09-30 23:00:00 (Fri) 62743075200, # local_end 1989-04-01 00:00:00 (Sat) 3600, 0, 'CET', ], [ 62743071600, # utc_start 1989-03-31 23:00:00 (Fri) 62758879200, # utc_end 1989-09-30 22:00:00 (Sat) 62743078800, # local_start 1989-04-01 01:00:00 (Sat) 62758886400, # local_end 1989-10-01 00:00:00 (Sun) 7200, 1, 'CEST', ], [ 62758879200, # utc_start 1989-09-30 22:00:00 (Sat) 62777458800, # utc_end 1990-05-03 23:00:00 (Thu) 62758882800, # local_start 1989-09-30 23:00:00 (Sat) 62777462400, # local_end 1990-05-04 00:00:00 (Fri) 3600, 0, 'CET', ], [ 62777458800, # utc_start 1990-05-03 23:00:00 (Thu) 62979717600, # utc_end 1996-09-29 22:00:00 (Sun) 62777466000, # local_start 1990-05-04 01:00:00 (Fri) 62979724800, # local_end 1996-09-30 00:00:00 (Mon) 7200, 0, 'EET', ], [ 62979717600, # utc_start 1996-09-29 22:00:00 (Sun) 62995791600, # utc_end 1997-04-03 23:00:00 (Thu) 62979721200, # local_start 1996-09-29 23:00:00 (Sun) 62995795200, # local_end 1997-04-04 00:00:00 (Fri) 3600, 0, 'CET', ], [ 62995791600, # utc_start 1997-04-03 23:00:00 (Thu) 63011599200, # utc_end 1997-10-03 22:00:00 (Fri) 62995798800, # local_start 1997-04-04 01:00:00 (Fri) 63011606400, # local_end 1997-10-04 00:00:00 (Sat) 7200, 1, 'CEST', ], [ 63011599200, # utc_start 1997-10-03 22:00:00 (Fri) 63488188800, # utc_end 2012-11-10 00:00:00 (Sat) 63011606400, # local_start 1997-10-04 00:00:00 (Sat) 63488196000, # local_end 2012-11-10 02:00:00 (Sat) 7200, 0, 'EET', ], [ 63488188800, # utc_start 2012-11-10 00:00:00 (Sat) 63500198400, # utc_end 2013-03-29 00:00:00 (Fri) 63488192400, # local_start 2012-11-10 01:00:00 (Sat) 63500202000, # local_end 2013-03-29 01:00:00 (Fri) 3600, 0, 'CET', ], [ 63500198400, # utc_start 2013-03-29 00:00:00 (Fri) 63518342400, # utc_end 2013-10-25 00:00:00 (Fri) 63500205600, # local_start 2013-03-29 02:00:00 (Fri) 63518349600, # local_end 2013-10-25 02:00:00 (Fri) 7200, 1, 'CEST', ], [ 63518342400, # utc_start 2013-10-25 00:00:00 (Fri) DateTime::TimeZone::INFINITY, # utc_end 63518349600, # local_start 2013-10-25 02:00:00 (Fri) DateTime::TimeZone::INFINITY, # local_end 7200, 0, 'EET', ], ]; sub olson_version {'2016c'} sub has_dst_changes {13} sub _max_year {2026} sub _new_instance { return shift->_init( @_, spans => $spans ); } 1;
26.361194
89
0.645567
edb0848fae5de570a744cbbf4f5ee1ab3eb32bd8
10,140
pm
Perl
apps/vmware/connector/mode/healthhost.pm
xdrive05/centreon-plugins
8227ba680fdfd2bb0d8a806ea61ec1611c2779dc
[ "Apache-2.0" ]
1
2021-03-16T22:20:32.000Z
2021-03-16T22:20:32.000Z
apps/vmware/connector/mode/healthhost.pm
xdrive05/centreon-plugins
8227ba680fdfd2bb0d8a806ea61ec1611c2779dc
[ "Apache-2.0" ]
null
null
null
apps/vmware/connector/mode/healthhost.pm
xdrive05/centreon-plugins
8227ba680fdfd2bb0d8a806ea61ec1611c2779dc
[ "Apache-2.0" ]
null
null
null
# # Copyright 2020 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package apps::vmware::connector::mode::healthhost; use base qw(centreon::plugins::templates::counter); use strict; use warnings; use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold); sub custom_status_output { my ($self, %options) = @_; my $msg = 'status ' . $self->{result_values}->{status}; return $msg; } sub custom_status_calc { my ($self, %options) = @_; $self->{result_values}->{status} = $options{new_datas}->{$self->{instance} . '_state'}; return 0; } sub custom_summary_output { my ($self, %options) = @_; my $msg; if ($self->{result_values}->{type_absolute} ne '') { $msg = $self->{result_values}->{type_absolute} . " sensor " . $self->{result_values}->{name_absolute} . ": ". $self->{result_values}->{summary_absolute}; } else { $msg = $self->{result_values}->{name_absolute} . ": ". $self->{result_values}->{summary_absolute}; } return $msg; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'global', type => 0, skipped_code => { -10 => 1 } }, { name => 'host', type => 3, cb_prefix_output => 'prefix_host_output', cb_long_output => 'host_long_output', indent_long_output => ' ', message_multiple => 'All ESX hosts are ok', group => [ { name => 'global_host', type => 0, skipped_code => { -10 => 1 } }, { name => 'global_problems', type => 0, skipped_code => { -10 => 1 } }, { name => 'global_summary', type => 1 }, ] } ]; $self->{maps_counters}->{global} = [ { label => 'total-problems', nlabel => 'host.health.problems.current.count', set => { key_values => [ { name => 'total_problems' }, { name => 'total' } ], output_template => '%s total health issue(s) found', perfdatas => [ { label => 'total_problems', value => 'total_problems_absolute', template => '%s', min => 0, max => 'total_absolute' }, ], } }, ]; $self->{maps_counters}->{global_host} = [ { label => 'status', threshold => 0, set => { key_values => [ { name => 'state' } ], closure_custom_calc => $self->can('custom_status_calc'), closure_custom_output => $self->can('custom_status_output'), closure_custom_perfdata => sub { return 0; }, closure_custom_threshold_check => \&catalog_status_threshold, } }, ]; $self->{maps_counters}->{global_problems} = [ { label => 'ok', threshold => 0, set => { key_values => [ { name => 'ok' } ], output_template => '%s health checks are green', closure_custom_perfdata => sub { return 0; }, } }, { label => 'problems', nlabel => 'host.health.problems.current.count', set => { key_values => [ { name => 'total_problems' }, { name => 'total' } ], output_template => '%s total health issue(s) found', perfdatas => [ { label => 'problems', value => 'total_problems_absolute', template => '%s', min => 0, max => 'total_absolute', label_extra_instance => 1 }, ], } }, { label => 'problems-yellow', nlabel => 'host.health.yellow.current.count', set => { key_values => [ { name => 'yellow' }, { name => 'total' } ], output_template => '%s yellow health issue(s) found', perfdatas => [ { label => 'problems_yellow', value => 'yellow_absolute', template => '%s', min => 0, max => 'total_absolute', label_extra_instance => 1 }, ], } }, { label => 'problems-red', nlabel => 'host.health.red.current.count', set => { key_values => [ { name => 'red' }, { name => 'total' } ], output_template => '%s red health issue(s) found', perfdatas => [ { label => 'problems_red', value => 'red_absolute', template => '%s', min => 0, max => 'total_absolute', label_extra_instance => 1 }, ], } }, ]; $self->{maps_counters}->{global_summary} = [ { label => 'global-summary', threshold => 0, set => { key_values => [ { name => 'type' }, { name => 'name' }, { name => 'summary' } ], closure_custom_output => $self->can('custom_summary_output'), closure_custom_perfdata => sub { return 0; }, } }, ]; } sub prefix_host_output { my ($self, %options) = @_; return "Host '" . $options{instance_value}->{display} . "' : "; } sub host_long_output { my ($self, %options) = @_; return "checking host '" . $options{instance_value}->{display} . "'"; } sub prefix_global_cpu_output { my ($self, %options) = @_; return "cpu total average : "; } sub prefix_cpu_output { my ($self, %options) = @_; return "cpu '" . $options{instance_value}->{display} . "' "; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { "esx-hostname:s" => { name => 'esx_hostname' }, "filter" => { name => 'filter' }, "scope-datacenter:s" => { name => 'scope_datacenter' }, "scope-cluster:s" => { name => 'scope_cluster' }, "storage-status" => { name => 'storage_status' }, "unknown-status:s" => { name => 'unknown_status', default => '%{status} !~ /^connected$/i' }, "warning-status:s" => { name => 'warning_status', default => '' }, "critical-status:s" => { name => 'critical_status', default => '' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); $self->change_macros(macros => ['unknown_status', 'warning_status', 'critical_status']); } sub manage_selection { my ($self, %options) = @_; $self->{global} = { total_problems => 0, total => 0 }; $self->{host} = {}; my $response = $options{custom}->execute(params => $self->{option_results}, command => 'healthhost'); foreach my $host_id (keys %{$response->{data}}) { my $host_name = $response->{data}->{$host_id}->{name}; $self->{host}->{$host_name} = { display => $host_name, global_host => { state => $response->{data}->{$host_id}->{state}, }, global_summary => {}, global_problems => { ok => 0, total_problems => 0, red => 0, yellow => 0, total => 0, }, }; my $i = 0; foreach (('memory_info', 'cpu_info', 'sensor_info', 'storage_info')) { if (defined($response->{data}->{$host_id}->{$_})) { foreach my $entry (@{$response->{data}->{$host_id}->{$_}}) { my $status = 'ok'; $status = lc($1) if ($entry->{status} =~ /(yellow|red)/i); $self->{host}->{$host_name}->{global_problems}->{$status}++; $self->{host}->{$host_name}->{global_problems}->{total}++; if ($status eq 'ok') { $self->{host}->{$host_name}->{global_problems}->{total_problems}++ } else { $self->{host}->{$host_name}->{global_summary}->{$i} = { type => defined($entry->{type}) ? $entry->{type} : '', name => $entry->{name}, summary => $entry->{summary}, }; } } $i++; } } $self->{global}->{total_problems} += $self->{host}->{$host_name}->{global_problems}->{red} + $self->{host}->{$host_name}->{global_problems}->{yellow}; $self->{global}->{total} += $self->{host}->{$host_name}->{global_problems}->{total}; } } 1; __END__ =head1 MODE Check health of ESX hosts. =over 8 =item B<--esx-hostname> ESX hostname to check. If not set, we check all ESX. =item B<--filter> ESX hostname is a regexp. =item B<--scope-datacenter> Search in following datacenter(s) (can be a regexp). =item B<--scope-cluster> Search in following cluster(s) (can be a regexp). =item B<--storage-status> Check storage(s) status. =item B<--unknown-status> Set warning threshold for status (Default: '%{status} !~ /^connected$/i'). Can used special variables like: %{status} =item B<--warning-status> Set warning threshold for status (Default: ''). Can used special variables like: %{status} =item B<--critical-status> Set critical threshold for status (Default: ''). Can used special variables like: %{status} =item B<--warning-*> Threshold warning. Can be: 'total-problems', 'problems', 'problems-yellow', 'problems-red'. =item B<--critical-*> Threshold critical. Can be: 'total-problems', 'problems', 'problems-yellow', 'problems-red'. =back =cut
34.372881
191
0.530671
edd96bb6d36f066ff8eb33eff30bb6e0853c66e6
970
pm
Perl
tools/test_modules/m11760.pm
vbalyasnyy/hashcat
84d3981e7b6bc4efe3c1bcbaa6f4198f4c523204
[ "MIT" ]
3
2019-02-08T11:12:44.000Z
2021-05-09T13:43:50.000Z
tools/test_modules/m11760.pm
e-ago/hashcat
dbbdb7e5ac4f7db2dd503c1820b91fbbcfc37c92
[ "MIT" ]
null
null
null
tools/test_modules/m11760.pm
e-ago/hashcat
dbbdb7e5ac4f7db2dd503c1820b91fbbcfc37c92
[ "MIT" ]
1
2021-05-01T09:38:27.000Z
2021-05-01T09:38:27.000Z
#!/usr/bin/env perl ## ## Author......: See docs/credits.txt ## License.....: MIT ## use strict; use warnings; sub module_constraints { [[0, 256], [0, 256], [-1, -1], [-1, -1], [-1, -1]] } sub module_generate_hash { my $word = shift; my $salt = shift; my $python_code = <<"END_CODE"; import binascii import hmac import sys from pygost import gost34112012256 key = b"$salt" msg = b"$word" digest = hmac.new(key, msg, gost34112012256).digest() sys.stdout.write(binascii.hexlify(digest[::-1])) END_CODE my $digest = `python2 -c '$python_code'`; my $hash = sprintf ("%s:%s", $digest, $salt); return $hash; } sub module_verify_hash { my $line = shift; my ($hash, $salt, $word) = split (':', $line); return unless defined $hash; return unless defined $salt; return unless defined $word; my $word_packed = pack_if_HEX_notation ($word); my $new_hash = module_generate_hash ($word_packed, $salt); return ($new_hash, $word); } 1;
17.636364
77
0.637113
eded75f189b4daaabcb18473feedd86cfd574124
4,510
pl
Perl
scripts/EST/clip_cdnas.pl
vsitnik/ensembl-pipeline
3d12427eb0536812906fe5fd0cf5e90cc27d89ad
[ "Apache-2.0" ]
51
2015-01-09T06:15:42.000Z
2022-01-09T19:03:36.000Z
scripts/EST/clip_cdnas.pl
vsitnik/ensembl-pipeline
3d12427eb0536812906fe5fd0cf5e90cc27d89ad
[ "Apache-2.0" ]
4
2017-08-03T11:06:57.000Z
2022-01-21T17:23:19.000Z
scripts/EST/clip_cdnas.pl
vsitnik/ensembl-pipeline
3d12427eb0536812906fe5fd0cf5e90cc27d89ad
[ "Apache-2.0" ]
31
2015-01-11T08:22:41.000Z
2022-03-10T00:48:24.000Z
#!/usr/bin/env perl # Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute # Copyright [2016-2020] EMBL-European Bioinformatics Institute # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # script to clip the ends of the given fasta file of cDNAs # clipping can be hard (physically remove bases; default) or # soft (replace clipped seq with Ns), and can be based # on a given clip-range X i.e. clip X bases from each end) # and/or on poly-A/T sequence occurring at the ends. If both # range and polya clipping are asked for, the range clipping # is performed first. use warnings ; use strict; use Getopt::Long qw(:config no_ignore_case); use Bio::Seq; use Bio::SeqIO; use Bio::EnsEMBL::Utils::PolyA; my ($mask, $softmask, $poly_a_clip, $clip_len, $min_length, $outfile, $help); GetOptions( 'mask' => \$mask, 'softmask' => \$softmask, 'hardclip=s' => \$clip_len, 'polyaclip' => \$poly_a_clip, 'minlen=s' => \$min_length, 'outfile=s' => \$outfile, 'help' => \$help ); &usage if $help; die "You must give the name of an output filw with -outfile\n" if not defined $outfile; $min_length = 100 if not defined $min_length; # fasta format my $seqout = new Bio::SeqIO( '-format' => "fasta", '-file' => ">$outfile" ); my $polyA_clipper = Bio::EnsEMBL::Utils::PolyA->new(); foreach my $file (@ARGV) { my $seqin = new Bio::SeqIO( '-format' => "fasta", '-file' => $file ); while( my $cdna = $seqin->next_seq ){ my $new_cdna; if ( $clip_len ){ my $seq = $cdna->seq; my $seq_length = length( $seq ); # skip it if you are going to clip more than the actual length of the EST if ( 2*$clip_len >= $seq_length ){ next SEQFETCH; } my $seq_left = substr( $seq, 0, $clip_len ); my $new_seq = substr( $seq, $clip_len, $seq_length - 2*$clip_len ); my $seq_right = substr( $seq, $clip_len + $seq_length - 2*$clip_len); if ($mask) { $new_seq = "N" x $clip_len . $new_seq . "N" x $clip_len; } elsif ($softmask) { $new_seq = lc($seq_left) . $new_seq . lc($seq_right); } # skip it if you are left with an EST of less than 100bp if ( length( $new_seq ) < $min_length ){ next SEQFETCH; } $new_cdna = new Bio::Seq; $new_cdna->display_id( $cdna->display_id ); $new_cdna->desc( $cdna->desc ); $new_cdna->seq($new_seq); } else{ $new_cdna = $cdna; } if ($poly_a_clip){ #print STDERR "going to pass ".$new_cdna->display_id."\n"; if ($mask or $softmask) { $new_cdna = $polyA_clipper->mask($new_cdna, $softmask); } else { $new_cdna = $polyA_clipper->clip($new_cdna); } if (not $new_cdna or $new_cdna->length < $min_length) { next; } } # write sequence $seqout->write_seq($new_cdna); } } sub usage { print "Usage: clip_dnas.pl -outfile out.fa <-mask|-softmask> <-hardclip n> <-polyaclip> <-minlen n> file1.fa file2.fa ...\n\n"; print "Recommended settings:\n clip_cdnas.pl -outfile out.fa -polyaclip -minlen 100 file1.fa file.fa...\n"; print " (clips polyAs only, rejecting if result is less than 100 bp)\n"; print "Other examples:\n"; print "To softmask polyA:\n clip_cdnas.pl -outfile out.fa -softmask -polyaclip file1.fa file2.fa ...\n"; print "To hardmask polyA:\n clip_cdnas.pl -outfile out.fa -mask -polyaclip file1.fa file2.fa ...\n"; print "To hard clip 20bp from each end:\n clip_cdnas.pl -outfile out.fa -hardclip 20 file1.fa file2.fa ...\n"; print "Hard clip 20bp followed by polyA clip:\n clip_cdnas.pl -outfile out.fa -hardclip 20 -polyA file1.fa file2.fa ...\n"; print "To reject entries < 60bp after clipping:\n clip_cdnas.pl -outfile out.fa -hardclip 20 -polyA -minlen 60 file1.fa file2.fa ...\n"; print "To do nothing(!):\n clip_cdnas.pl -outfile out.fa file1.fa file2.fa ...\n"; exit(0); }
32.446043
142
0.638581
edbdb9589fade67d4e1a972388862ebdb69d24d9
1,064
t
Perl
t/O2/Obj/PropertyDefinition-2.t
haakonsk/O2-Framework
50f2f2def517b90dec647b914128ad8f949f51d9
[ "MIT" ]
1
2016-05-24T08:13:09.000Z
2016-05-24T08:13:09.000Z
t/O2/Obj/PropertyDefinition-2.t
haakonsk/O2-Framework
50f2f2def517b90dec647b914128ad8f949f51d9
[ "MIT" ]
null
null
null
t/O2/Obj/PropertyDefinition-2.t
haakonsk/O2-Framework
50f2f2def517b90dec647b914128ad8f949f51d9
[ "MIT" ]
null
null
null
use strict; use Test::More qw(no_plan); use_ok 'O2::Context'; use_ok 'O2::Mgr::PropertyDefinitionManager'; my $context = O2::Context->new(); my $propertyDefinitionMgr = O2::Mgr::PropertyDefinitionManager->new( context => $context ); my $definition = $propertyDefinitionMgr->newObject(); $definition->setPropertyName( 'My property definition' ); $definition->setMetaName( 'My property definition' ); $definition->setOptionsType('static'); $definition->setOptionsData('[{name=>"name", value=>"value"}]'); is_deeply([$definition->getOptions()], [{name=>"name", value=>"value"}], 'getOptions() static options type'); $definition->setOptionsType('method'); $definition->setOptionsData('O2::Obj::PropertyDefinition::StandardOptions::test'); $definition->save(); is_deeply([$definition->getOptions()], [{name=>"Test1", value=>"test1"}], 'getOptions() method options type'); ok( $propertyDefinitionMgr->getPropertyDefinitionByName( $definition->getPropertyName() ), 'getPropertyDefinitionByName()'); END { $definition->deletePermanently() if $definition; }
35.466667
124
0.727444
edbc4f978f40770b6ee567b2892268c601607a07
14,723
pm
Perl
extlib/Mojo/Headers.pm
jamadam/mojo-checkbot
ec3e39d43f7915ba61ad90234b6b3582f33e0f69
[ "MIT" ]
2
2017-04-03T14:11:18.000Z
2020-01-16T05:35:20.000Z
extlib/Mojo/Headers.pm
jamadam/mojo-checkbot
ec3e39d43f7915ba61ad90234b6b3582f33e0f69
[ "MIT" ]
null
null
null
extlib/Mojo/Headers.pm
jamadam/mojo-checkbot
ec3e39d43f7915ba61ad90234b6b3582f33e0f69
[ "MIT" ]
null
null
null
package Mojo::Headers; use Mojo::Base -base; use Mojo::Util 'monkey_patch'; has max_line_size => sub { $ENV{MOJO_MAX_LINE_SIZE} || 10240 }; # Common headers my %NORMALCASE = map { lc($_) => $_ } ( qw(Accept Accept-Charset Accept-Encoding Accept-Language Accept-Ranges), qw(Allow Authorization Cache-Control Connection Content-Disposition), qw(Content-Encoding Content-Length Content-Range Content-Type Cookie DNT), qw(Date ETag Expect Expires Host If-Modified-Since Last-Modified Link), qw(Location Origin Proxy-Authenticate Proxy-Authorization Range), qw(Sec-WebSocket-Accept Sec-WebSocket-Extensions Sec-WebSocket-Key), qw(Sec-WebSocket-Protocol Sec-WebSocket-Version Server Set-Cookie Status), qw(TE Trailer Transfer-Encoding Upgrade User-Agent Vary WWW-Authenticate) ); for my $header (values %NORMALCASE) { my $name = lc $header; $name =~ y/-/_/; monkey_patch __PACKAGE__, $name, sub { shift->header($header => @_) }; } sub add { my ($self, $name) = (shift, shift); # Make sure we have a normal case entry for name my $key = lc $name; $self->{normalcase}{$key} = defined $self->{normalcase}{$key} ? $self->{normalcase}{$key} : $name unless $NORMALCASE{$key}; push @{$self->{headers}{$key}}, @_; return $self; } sub append { my ($self, $name, $value) = @_; my $old = $self->header($name); return $self->header($name => defined $old ? "$old, $value" : $value); } sub clone { $_[0]->new->from_hash($_[0]->to_hash(1)) } sub from_hash { my ($self, $hash) = @_; # Empty hash deletes all headers delete $self->{headers} if keys %{$hash} == 0; # Merge for my $header (keys %$hash) { my $value = $hash->{$header}; $self->add($header => ref $value eq 'ARRAY' ? @$value : $value); } return $self; } sub header { my ($self, $name) = (shift, shift); # Replace return $self->remove($name)->add($name, @_) if @_; return undef unless my $headers = $self->{headers}{lc $name}; return join ', ', @$headers; } sub is_finished { do {my $tmp = shift->{state}; defined $tmp ? $tmp : ''} eq 'finished' } sub is_limit_exceeded { !!shift->{limit} } sub leftovers { delete shift->{buffer} } sub names { my $self = shift; return [map { $NORMALCASE{$_} || $self->{normalcase}{$_} || $_ } keys %{$self->{headers}}]; } sub parse { my $self = shift; $self->{state} = 'headers'; $self->{buffer} .= do {my $buffer = shift; defined $buffer ? $buffer : ''}; my $headers = $self->{cache} ||= []; my $max = $self->max_line_size; while ($self->{buffer} =~ s/^(.*?)\x0d?\x0a//) { my $line = $1; # Check line size limit if (length $line > $max) { @$self{qw(state limit)} = ('finished', 1); return $self; } # New header if ($line =~ /^(\S[^:]*)\s*:\s*(.*)$/) { push @$headers, $1, $2 } # Multiline elsif (@$headers && $line =~ s/^\s+//) { $headers->[-1] .= " $line" } # Empty line else { $self->add(splice @$headers, 0, 2) while @$headers; $self->{state} = 'finished'; return $self; } } # Check line size limit @$self{qw(state limit)} = ('finished', 1) if length $self->{buffer} > $max; return $self; } sub referrer { shift->header(Referer => @_) } sub remove { my ($self, $name) = @_; delete $self->{headers}{lc $name}; return $self; } sub to_hash { my ($self, $multi) = @_; return {map { $_ => $multi ? $self->{headers}{lc $_} : $self->header($_) } @{$self->names}}; } sub to_string { my $self = shift; # Make sure multiline values are formatted correctly my @headers; for my $name (@{$self->names}) { push @headers, "$name: $_" for @{$self->{headers}{lc $name}}; } return join "\x0d\x0a", @headers; } 1; =encoding utf8 =head1 NAME Mojo::Headers - Headers =head1 SYNOPSIS use Mojo::Headers; # Parse my $headers = Mojo::Headers->new; $headers->parse("Content-Length: 42\x0d\x0a"); $headers->parse("Content-Type: text/html\x0d\x0a\x0d\x0a"); say $headers->content_length; say $headers->content_type; # Build my $headers = Mojo::Headers->new; $headers->content_length(42); $headers->content_type('text/plain'); say $headers->to_string; =head1 DESCRIPTION L<Mojo::Headers> is a container for HTTP headers based on L<RFC 7230|http://tools.ietf.org/html/rfc7230> and L<RFC 7231|http://tools.ietf.org/html/rfc7231>. =head1 ATTRIBUTES L<Mojo::Headers> implements the following attributes. =head2 max_line_size my $size = $headers->max_line_size; $headers = $headers->max_line_size(1024); Maximum header line size in bytes, defaults to the value of the C<MOJO_MAX_LINE_SIZE> environment variable or C<10240> (10KB). =head1 METHODS L<Mojo::Headers> inherits all methods from L<Mojo::Base> and implements the following new ones. =head2 accept my $accept = $headers->accept; $headers = $headers->accept('application/json'); Shortcut for the C<Accept> header. =head2 accept_charset my $charset = $headers->accept_charset; $headers = $headers->accept_charset('UTF-8'); Shortcut for the C<Accept-Charset> header. =head2 accept_encoding my $encoding = $headers->accept_encoding; $headers = $headers->accept_encoding('gzip'); Shortcut for the C<Accept-Encoding> header. =head2 accept_language my $language = $headers->accept_language; $headers = $headers->accept_language('de, en'); Shortcut for the C<Accept-Language> header. =head2 accept_ranges my $ranges = $headers->accept_ranges; $headers = $headers->accept_ranges('bytes'); Shortcut for the C<Accept-Ranges> header. =head2 add $headers = $headers->add(Foo => 'one value'); $headers = $headers->add(Foo => 'first value', 'second value'); Add one or more header values with one or more lines. # "Vary: Accept" # "Vary: Accept-Encoding" $headers->vary('Accept')->add(Vary => 'Accept-Encoding')->to_string; =head2 allow my $allow = $headers->allow; $headers = $headers->allow('GET, POST'); Shortcut for the C<Allow> header. =head2 append $headers = $headers->append(Vary => 'Accept-Encoding'); Append value to header and flatten it if necessary. # "Vary: Accept" $headers->append(Vary => 'Accept')->to_string; # "Vary: Accept, Accept-Encoding" $headers->vary('Accept')->append(Vary => 'Accept-Encoding')->to_string; =head2 authorization my $authorization = $headers->authorization; $headers = $headers->authorization('Basic Zm9vOmJhcg=='); Shortcut for the C<Authorization> header. =head2 cache_control my $cache_control = $headers->cache_control; $headers = $headers->cache_control('max-age=1, no-cache'); Shortcut for the C<Cache-Control> header. =head2 clone my $clone = $headers->clone; Clone headers. =head2 connection my $connection = $headers->connection; $headers = $headers->connection('close'); Shortcut for the C<Connection> header. =head2 content_disposition my $disposition = $headers->content_disposition; $headers = $headers->content_disposition('foo'); Shortcut for the C<Content-Disposition> header. =head2 content_encoding my $encoding = $headers->content_encoding; $headers = $headers->content_encoding('gzip'); Shortcut for the C<Content-Encoding> header. =head2 content_length my $len = $headers->content_length; $headers = $headers->content_length(4000); Shortcut for the C<Content-Length> header. =head2 content_range my $range = $headers->content_range; $headers = $headers->content_range('bytes 2-8/100'); Shortcut for the C<Content-Range> header. =head2 content_type my $type = $headers->content_type; $headers = $headers->content_type('text/plain'); Shortcut for the C<Content-Type> header. =head2 cookie my $cookie = $headers->cookie; $headers = $headers->cookie('f=b'); Shortcut for the C<Cookie> header from L<RFC 6265|http://tools.ietf.org/html/rfc6265>. =head2 date my $date = $headers->date; $headers = $headers->date('Sun, 17 Aug 2008 16:27:35 GMT'); Shortcut for the C<Date> header. =head2 dnt my $dnt = $headers->dnt; $headers = $headers->dnt(1); Shortcut for the C<DNT> (Do Not Track) header, which has no specification yet, but is very commonly used. =head2 etag my $etag = $headers->etag; $headers = $headers->etag('abc321'); Shortcut for the C<ETag> header. =head2 expect my $expect = $headers->expect; $headers = $headers->expect('100-continue'); Shortcut for the C<Expect> header. =head2 expires my $expires = $headers->expires; $headers = $headers->expires('Thu, 01 Dec 1994 16:00:00 GMT'); Shortcut for the C<Expires> header. =head2 from_hash $headers = $headers->from_hash({'Cookie' => 'a=b'}); $headers = $headers->from_hash({'Cookie' => ['a=b', 'c=d']}); $headers = $headers->from_hash({}); Parse headers from a hash reference, an empty hash removes all headers. =head2 header my $value = $headers->header('Foo'); $headers = $headers->header(Foo => 'one value'); $headers = $headers->header(Foo => 'first value', 'second value'); Get or replace the current header values. =head2 host my $host = $headers->host; $headers = $headers->host('127.0.0.1'); Shortcut for the C<Host> header. =head2 if_modified_since my $date = $headers->if_modified_since; $headers = $headers->if_modified_since('Sun, 17 Aug 2008 16:27:35 GMT'); Shortcut for the C<If-Modified-Since> header. =head2 is_finished my $bool = $headers->is_finished; Check if header parser is finished. =head2 is_limit_exceeded my $bool = $headers->is_limit_exceeded; Check if a header has exceeded C<max_line_size>. =head2 last_modified my $date = $headers->last_modified; $headers = $headers->last_modified('Sun, 17 Aug 2008 16:27:35 GMT'); Shortcut for the C<Last-Modified> header. =head2 leftovers my $bytes = $headers->leftovers; Get leftover data from header parser. =head2 link my $link = $headers->link; $headers = $headers->link('<http://127.0.0.1/foo/3>; rel="next"'); Shortcut for the C<Link> header from L<RFC 5988|http://tools.ietf.org/html/rfc5988>. =head2 location my $location = $headers->location; $headers = $headers->location('http://127.0.0.1/foo'); Shortcut for the C<Location> header. =head2 names my $names = $headers->names; Return a list of all currently defined headers. # Names of all headers say for @{$headers->names}; =head2 origin my $origin = $headers->origin; $headers = $headers->origin('http://example.com'); Shortcut for the C<Origin> header from L<RFC 6454|http://tools.ietf.org/html/rfc6454>. =head2 parse $headers = $headers->parse("Content-Type: text/plain\x0d\x0a\x0d\x0a"); Parse formatted headers. =head2 proxy_authenticate my $authenticate = $headers->proxy_authenticate; $headers = $headers->proxy_authenticate('Basic "realm"'); Shortcut for the C<Proxy-Authenticate> header. =head2 proxy_authorization my $authorization = $headers->proxy_authorization; $headers = $headers->proxy_authorization('Basic Zm9vOmJhcg=='); Shortcut for the C<Proxy-Authorization> header. =head2 range my $range = $headers->range; $headers = $headers->range('bytes=2-8'); Shortcut for the C<Range> header. =head2 referrer my $referrer = $headers->referrer; $headers = $headers->referrer('http://example.com'); Shortcut for the C<Referer> header, there was a typo in L<RFC 2068|http://tools.ietf.org/html/rfc2068> which resulted in C<Referer> becoming an official header. =head2 remove $headers = $headers->remove('Foo'); Remove a header. =head2 sec_websocket_accept my $accept = $headers->sec_websocket_accept; $headers = $headers->sec_websocket_accept('s3pPLMBiTxaQ9kYGzzhZRbK+xOo='); Shortcut for the C<Sec-WebSocket-Accept> header from L<RFC 6455|http://tools.ietf.org/html/rfc6455>. =head2 sec_websocket_extensions my $extensions = $headers->sec_websocket_extensions; $headers = $headers->sec_websocket_extensions('foo'); Shortcut for the C<Sec-WebSocket-Extensions> header from L<RFC 6455|http://tools.ietf.org/html/rfc6455>. =head2 sec_websocket_key my $key = $headers->sec_websocket_key; $headers = $headers->sec_websocket_key('dGhlIHNhbXBsZSBub25jZQ=='); Shortcut for the C<Sec-WebSocket-Key> header from L<RFC 6455|http://tools.ietf.org/html/rfc6455>. =head2 sec_websocket_protocol my $proto = $headers->sec_websocket_protocol; $headers = $headers->sec_websocket_protocol('sample'); Shortcut for the C<Sec-WebSocket-Protocol> header from L<RFC 6455|http://tools.ietf.org/html/rfc6455>. =head2 sec_websocket_version my $version = $headers->sec_websocket_version; $headers = $headers->sec_websocket_version(13); Shortcut for the C<Sec-WebSocket-Version> header from L<RFC 6455|http://tools.ietf.org/html/rfc6455>. =head2 server my $server = $headers->server; $headers = $headers->server('Mojo'); Shortcut for the C<Server> header. =head2 set_cookie my $cookie = $headers->set_cookie; $headers = $headers->set_cookie('f=b; path=/'); Shortcut for the C<Set-Cookie> header from L<RFC 6265|http://tools.ietf.org/html/rfc6265>. =head2 status my $status = $headers->status; $headers = $headers->status('200 OK'); Shortcut for the C<Status> header from L<RFC 3875|http://tools.ietf.org/html/rfc3875>. =head2 te my $te = $headers->te; $headers = $headers->te('chunked'); Shortcut for the C<TE> header. =head2 to_hash my $single = $headers->to_hash; my $multi = $headers->to_hash(1); Turn headers into hash reference, array references to represent multiple headers with the same name are disabled by default. say $headers->to_hash->{DNT}; =head2 to_string my $str = $headers->to_string; Turn headers into a string, suitable for HTTP messages. =head2 trailer my $trailer = $headers->trailer; $headers = $headers->trailer('X-Foo'); Shortcut for the C<Trailer> header. =head2 transfer_encoding my $encoding = $headers->transfer_encoding; $headers = $headers->transfer_encoding('chunked'); Shortcut for the C<Transfer-Encoding> header. =head2 upgrade my $upgrade = $headers->upgrade; $headers = $headers->upgrade('websocket'); Shortcut for the C<Upgrade> header. =head2 user_agent my $agent = $headers->user_agent; $headers = $headers->user_agent('Mojo/1.0'); Shortcut for the C<User-Agent> header. =head2 vary my $vary = $headers->vary; $headers = $headers->vary('*'); Shortcut for the C<Vary> header. =head2 www_authenticate my $authenticate = $headers->www_authenticate; $headers = $headers->www_authenticate('Basic realm="realm"'); Shortcut for the C<WWW-Authenticate> header. =head1 SEE ALSO L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicio.us>. =cut
23.594551
125
0.676832
edbc4be717a42c7c933b2b1aa60ad82e5b9d48f1
4,464
pm
Perl
auto-lib/Paws/GameLift/PlayerSession.pm
galenhuntington/aws-sdk-perl
13b775dcb5f0b3764f0a82f3679ed5c7721e67d3
[ "Apache-2.0" ]
null
null
null
auto-lib/Paws/GameLift/PlayerSession.pm
galenhuntington/aws-sdk-perl
13b775dcb5f0b3764f0a82f3679ed5c7721e67d3
[ "Apache-2.0" ]
null
null
null
auto-lib/Paws/GameLift/PlayerSession.pm
galenhuntington/aws-sdk-perl
13b775dcb5f0b3764f0a82f3679ed5c7721e67d3
[ "Apache-2.0" ]
null
null
null
package Paws::GameLift::PlayerSession; use Moose; has CreationTime => (is => 'ro', isa => 'Str'); has FleetId => (is => 'ro', isa => 'Str'); has GameSessionId => (is => 'ro', isa => 'Str'); has IpAddress => (is => 'ro', isa => 'Str'); has PlayerData => (is => 'ro', isa => 'Str'); has PlayerId => (is => 'ro', isa => 'Str'); has PlayerSessionId => (is => 'ro', isa => 'Str'); has Port => (is => 'ro', isa => 'Int'); has Status => (is => 'ro', isa => 'Str'); has TerminationTime => (is => 'ro', isa => 'Str'); 1; ### main pod documentation begin ### =head1 NAME Paws::GameLift::PlayerSession =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::GameLift::PlayerSession object: $service_obj->Method(Att1 => { CreationTime => $value, ..., TerminationTime => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::GameLift::PlayerSession object: $result = $service_obj->Method(...); $result->Att1->CreationTime =head1 DESCRIPTION Properties describing a player session. Player session objects are created either by creating a player session for a specific game session, or as part of a game session placement. A player session represents either a player reservation for a game session (status C<RESERVED>) or actual player activity in a game session (status C<ACTIVE>). A player session object (including player data) is automatically passed to a game session when the player connects to the game session and is validated. When a player disconnects, the player session status changes to C<COMPLETED>. Once the session ends, the player session object is retained for 30 days and then removed. Player-session-related operations include: =over =item * CreatePlayerSession =item * CreatePlayerSessions =item * DescribePlayerSessions =item * Game session placements =over =item * StartGameSessionPlacement =item * DescribeGameSessionPlacement =item * StopGameSessionPlacement =back =back =head1 ATTRIBUTES =head2 CreationTime => Str Time stamp indicating when this data object was created. Format is a number expressed in Unix time as milliseconds (for example "1469498468.057"). =head2 FleetId => Str Unique identifier for a fleet that the player's game session is running on. =head2 GameSessionId => Str Unique identifier for the game session that the player session is connected to. =head2 IpAddress => Str IP address of the game session. To connect to a Amazon GameLift game server, an app needs both the IP address and port number. =head2 PlayerData => Str Developer-defined information related to a player. Amazon GameLift does not use this data, so it can be formatted as needed for use in the game. =head2 PlayerId => Str Unique identifier for a player that is associated with this player session. =head2 PlayerSessionId => Str Unique identifier for a player session. =head2 Port => Int Port number for the game session. To connect to a Amazon GameLift server process, an app needs both the IP address and port number. =head2 Status => Str Current status of the player session. Possible player session statuses include the following: =over =item * B<RESERVED> -- The player session request has been received, but the player has not yet connected to the server process and/or been validated. =item * B<ACTIVE> -- The player has been validated by the server process and is currently connected. =item * B<COMPLETED> -- The player connection has been dropped. =item * B<TIMEDOUT> -- A player session request was received, but the player did not connect and/or was not validated within the timeout limit (60 seconds). =back =head2 TerminationTime => Str Time stamp indicating when this data object was terminated. Format is a number expressed in Unix time as milliseconds (for example "1469498468.057"). =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::GameLift> =head1 BUGS and CONTRIBUTIONS The source code is located here: L<https://github.com/pplu/aws-sdk-perl> Please report bugs to: L<https://github.com/pplu/aws-sdk-perl/issues> =cut
22.32
102
0.732303
edbb7db72b01a5cc54343b90dac4408eb83850e5
27,582
al
Perl
Apps/W1/AMCBanking365Fundamentals/test/src/Bank/ERMAMCbankingSetupATDD.Codeunit.al
kwettermann/ALAppExtensions
4519eea4a265dda64dd53c0ff5d60d89333842ad
[ "MIT" ]
337
2019-05-07T06:04:40.000Z
2022-03-31T10:07:42.000Z
Apps/W1/AMCBanking365Fundamentals/test/src/Bank/ERMAMCbankingSetupATDD.Codeunit.al
kwettermann/ALAppExtensions
4519eea4a265dda64dd53c0ff5d60d89333842ad
[ "MIT" ]
14,850
2019-05-07T06:04:27.000Z
2022-03-31T19:53:28.000Z
Apps/W1/AMCBanking365Fundamentals/test/src/Bank/ERMAMCbankingSetupATDD.Codeunit.al
kwettermann/ALAppExtensions
4519eea4a265dda64dd53c0ff5d60d89333842ad
[ "MIT" ]
374
2019-05-09T10:08:14.000Z
2022-03-31T17:48:32.000Z
codeunit 134410 "ERM AMC banking Setup ATDD" { Subtype = Test; TestPermissions = NonRestrictive; trigger OnRun() begin // [FEATURE] [AMC Banking Fundamentals] end; var Assert: Codeunit Assert; LibraryTestInitialize: Codeunit "Library - Test Initialize"; LibraryUtility: Codeunit "Library - Utility"; IsolatedStorageManagement: Codeunit "Isolated Storage Management"; UnsecureUriErr: Label 'The URI is not secure.'; InvalidUriErr: Label 'The URI is not valid.'; PasswordDoesNotMatchErr: Label 'The password from the database does not match the one that was introduced.'; EncryptionIsNotActiveErr: Label 'The encryption was not activated.'; EncryptionIsActiveErr: Label 'The encryption is activated and it should not be.'; HandlerResponse: Boolean; MissingCredentialsErr: Label 'The user name and password must be filled'; [Test] [HandlerFunctions('ConfirmHandlerYes,BlankAMCBankingSetupModalHandler,DataEncryprtionHandler')] [Scope('OnPrem')] procedure CheckCredentialsShouldOpenSetupPageInRealCompany() var AMCBankingSetup: Record "AMC Banking Setup"; AMCBankingMgt: Codeunit "AMC Banking Mgt."; begin Initialize(); // [GIVEN] "AMC Bank Service Setup" table is empty AMCBankingSetup.DeleteAll(); // [GIVEN] The Company is NOT Demo Company SetDemoCompany(false); // [GIVEN] Run CheckCredentials()() AMCBankingMgt.CheckCredentials(); // [WHEN] Answer 'Yes' to the confirmation 'Do you want to open the Setup page?' // answer Yes by ConfirmHandlerYes // [THEN] "AMC Bank Service Setup" page is open, // [THEN] Where User/Password are empty, the links are filled // verify by BlankAMCBankingSetupModalHandler end; [Test] [HandlerFunctions('ConfirmHandlerYes,AMCBankingSetupModalHandlerBlankPassword')] [Scope('OnPrem')] procedure CheckCredentialsShouldFailIfPasswordIsBlank() var AMCBankingSetup: Record "AMC Banking Setup"; AMCBankingMgt: Codeunit "AMC Banking Mgt."; begin Initialize(); // [GIVEN] AMC Bank Service Setup table is empty AMCBankingSetup.DeleteAll(true); // [GIVEN] The Company is NOT a Demo Company SetDemoCompany(false); // [GIVEN] Run CheckCredentials()() asserterror AMCBankingMgt.CheckCredentials(); // [GIVEN] Answer 'Yes' to the confirmation 'Do you want to open the Setup page?' // answer Yes by ConfirmHandlerYes // [WHEN] Keep the blank Password on the "AMC Bank Service Setup" page and close page // handled by AMCBankingSetupModalHandlerBlankPassword // [THEN] Error message: 'The user name and password must be filled' Assert.ExpectedError(MissingCredentialsErr); end; [Test] [HandlerFunctions('ConfirmHandlerNo')] [Scope('OnPrem')] procedure CheckCredentialsShouldFailIfUserCancelConfirmation() var AMCBankingSetup: Record "AMC Banking Setup"; AMCBankingMgt: Codeunit "AMC Banking Mgt."; begin Initialize(); // [GIVEN] AMC Bank Service Setup table is empty AMCBankingSetup.DeleteAll(); // [GIVEN] The Company is NOT a Demo Company SetDemoCompany(false); // [GIVEN] Run CheckCredentials() asserterror AMCBankingMgt.CheckCredentials(); // [GIVEN] Answer 'No' to the confirmation 'Do you want to open the Setup page?' // answer No by ConfirmHandlerNo // [THEN] Error message: 'The user name and password must be filled' Assert.ExpectedError(MissingCredentialsErr); end; [Test] [Scope('OnPrem')] procedure UserCanStoreHisAMCSetupInformation() var AMCBankingSetup: Record "AMC Banking Setup"; PasswordAMC: Text; UserNameAMC: Text[50]; begin // [FEATURE] [Password] // [SCENARIO 1] As a an Administrator I will store the User ID and Password obtained from the AMC Service site into Dynamics Nav, // this is used to enable bank data file conversion to happen from DynamicsNav. // [GIVEN] A User ID and password obtained from the AMC service site. // [WHEN] Username and Password is entered into the AMC Bank Service Setup // [THEN] The AMC Integration would be able to obtain User ID and Password to make use of the AMC Service, the Service URL was // automaticaly prepopulated Initialize(); // Setup: Clear the existing setup if AMCBankingSetup.Get() then AMCBankingSetup.Delete(); // Setup: Optain username and password UserNameAMC := LibraryUtility.GenerateRandomCode(AMCBankingSetup.FieldNo("User Name"), DATABASE::"AMC Banking Setup"); PasswordAMC := GenerateRandomPassword(); // Execute: Save username and password in service setup AMCBankingSetup.Init(); AMCBankingSetup.Validate("User Name", UserNameAMC); AMCBankingSetup.SavePassword(PasswordAMC); AMCBankingSetup."AMC Enabled" := true; AMCBankingSetup.Insert(); AMCBankingSetup.SetURLsToDefault(); // Validate ValidateSetup(UserNameAMC, PasswordAMC); end; [Test] [Scope('OnPrem')] procedure UserCanChangeHisAMCPassword() var AMCBankingSetup: Record "AMC Banking Setup"; PasswordAMC: Text; UserNameAMC: Text[50]; begin // [FEATURE] [Password] // [SCENARIO 2] As a an Administrator I will update the User ID and Password obtained from the AMC Service site into Dynamics Nav, // this is used to enable bank data file conversion to happen from DynamicsNav. // [GIVEN] A new User ID and password obtained from the AMC service site and an existing AMC Bank Service Setup. // [WHEN] The new Username and Password is entered into the existing AMC Bank Service Setup // [THEN] The AMC Integration would be able to obtain the updated User ID and Password to make use of the AMC Service, the // Service URL will remain unchanged. Initialize(); // Setup: Optain username and password UserNameAMC := LibraryUtility.GenerateRandomCode(AMCBankingSetup.FieldNo("User Name"), DATABASE::"AMC Banking Setup"); PasswordAMC := GenerateRandomPassword(); // Execute: Save username and password in service setup AMCBankingSetup.Get(); AMCBankingSetup.Validate("User Name", UserNameAMC); AMCBankingSetup.SavePassword(PasswordAMC); AMCBankingSetup.Modify(); // Validate ValidateSetup(UserNameAMC, PasswordAMC); end; [Test] [Scope('OnPrem')] procedure UserCanChangeTheAMCSetupURL() var AMCBankingSetup: Record "AMC Banking Setup"; PasswordAMC: Text; SignupAMC: Text[250]; begin // [FEATURE] [URL] // [SCENARIO 3] As a an Administrator I will be able to update the Sign-up URL for the AMC service, // this is used to enable bank data file conversion to happen from DynamicsNav. // [GIVEN] A Sign-up URL and an existing AMC Bank Service Setup. // [WHEN] The Sign-up URL is entered into the existing AMC Bank Service Setup // [THEN] The Sign-up URL is save to make it simple to do the AMC Sign-up, User ID and Password // will remain unchanged. Initialize(); // Setup: Optain username and SignupURL AMCBankingSetup.Get(); PasswordAMC := AMCBankingSetup.GetPassword(); SignupAMC := LibraryUtility.GenerateRandomCode(AMCBankingSetup.FieldNo("Sign-up URL"), DATABASE::"AMC Banking Setup"); // Execute: Save username and password in service setup AMCBankingSetup.Get(); AMCBankingSetup.Validate("Sign-up URL", SignupAMC); AMCBankingSetup.Modify(); // Validate AMCBankingSetup.Get(); Assert.AreEqual(PasswordAMC, AMCBankingSetup.GetPassword(), 'Password invalid'); Assert.AreEqual(SignupAMC, AMCBankingSetup."Sign-up URL", 'Sign-up invalid'); end; [Test] [Scope('OnPrem')] procedure UserCanChangeTheAMCServiceURL() var AMCBankingSetup: Record "AMC Banking Setup"; LibraryRandom: Codeunit "Library - Random"; PasswordAMC: Text; ServiceURLAMC: Text[250]; UserNameAMC: Text[50]; begin // [FEATURE] [URL] // [SCENARIO 4] As a an Administrator I will be able to update the Service URL for the AMC service, // this is used to enable bank data file conversion to happen from DynamicsNav. // [GIVEN] A Service URL and an existing AMC Bank Service Setup. // [WHEN] The Service URL is entered into the existing AMC Bank Service Setup // [THEN] The AMC Integration would be able to get the changed Service URL and use it to connect to the AMC service, User ID and Password // will be reset. Initialize(); // Setup: Optain password and Service URL AMCBankingSetup.Get(); AMCBankingSetup."User Name" := CopyStr(LibraryRandom.RandText(50), 1, MaxStrLen(AMCBankingSetup."User Name")); AMCBankingSetup.SavePassword(LibraryRandom.RandText(50)); AMCBankingSetup.Modify(); PasswordAMC := AMCBankingSetup.GetPassword(); UserNameAMC := AMCBankingSetup.GetUserName(); ServiceURLAMC := GenerateRandomUrl(true); // Execute: Save username and password in service setup AMCBankingSetup.Get(); AMCBankingSetup.Validate("Service URL", ServiceURLAMC); AMCBankingSetup.Modify(); // Validate AMCBankingSetup.Get(); Assert.AreNotEqual(PasswordAMC, AMCBankingSetup.GetPassword(), 'Password must be reset when changing service URL'); Assert.AreNotEqual(UserNameAMC, AMCBankingSetup.GetUserName(), 'Username must be reset when changing service URL'); Assert.AreEqual(ServiceURLAMC, AMCBankingSetup."Service URL", 'Service URL invalid'); end; [Test] [Scope('OnPrem')] procedure UserCanChangeTheAMCServiceURLToBeBlank() var AMCBankingSetup: Record "AMC Banking Setup"; ServiceURLAMC: Text[250]; begin // [FEATURE] [URL] // [SCENARIO 8] As an Administrator I will be able to update the Service URL for the AMC service as BLANK. // [GIVEN] An existing AMC Bank Service Setup. // [WHEN] The existng Service URL is deleted // [THEN] The field validation does not fail on a BLANK value in the Service URL field. Initialize(); // Setup: Create a valid AMC Banking Setup record ServiceURLAMC := GenerateRandomUrl(true); AMCBankingSetup.Get(); AMCBankingSetup.Validate("Service URL", ServiceURLAMC); AMCBankingSetup.Modify(); // Execute: Reset the Service URL to a BLANK AMCBankingSetup.Validate("Service URL", ''); AMCBankingSetup.Modify(); // Validate: That the BLANK is saved AMCBankingSetup.Get(); Assert.AreEqual('', AMCBankingSetup."Service URL", 'Service URL is not set to empty'); end; [Test] [Scope('OnPrem')] procedure UserCanEnterOnlySecureURLAsTheAMCServiceURL() var AMCBankingSetup: Record "AMC Banking Setup"; ServiceURLAMC: Text[250]; begin // [FEATURE] [URL] // [SCENARIO 9] As an Administrator I will only be able to create and update the Service URL for the AMC service that is secure. // [GIVEN] A new AMC Bank Service Setup. // [WHEN] A unsecure URL is entered in the Service URL field of the AMC Bank Service Setup // [THEN] Error is thrown. Initialize(); // Setup: Generate a random unsecure URL ServiceURLAMC := GenerateRandomUrl(false); // Execute: Set the Service URL to the generated unsecure URL AMCBankingSetup.Get(); asserterror AMCBankingSetup.Validate("Service URL", ServiceURLAMC); // Validate: Exception is thrown Assert.ExpectedError(UnsecureUriErr); end; [Test] [Scope('OnPrem')] procedure UserCanEnterOnlyValidURLAsTheAMCServiceURL() var AMCBankingSetup: Record "AMC Banking Setup"; ServiceURLAMC: Text[250]; begin // [FEATURE] [URL] // [SCENARIO 10] As an Administrator I will be able to update the Service URL for the AMC service as BLANK. // [GIVEN] An new AMC Bank Service Setup. // [WHEN] An invalid URL is entered in the Service URL field of the AMC Bank Service Setup // [THEN] Error is thrown. Initialize(); // Setup: Generate a random text URL ServiceURLAMC := CopyStr(LibraryUtility.GenerateRandomText(5), 1, 5); // Execute: Set the Service URL to the generated text which will result in an invalid URL AMCBankingSetup.Get(); asserterror AMCBankingSetup.Validate("Service URL", ServiceURLAMC); // Validate: Exception is thrown Assert.ExpectedError(InvalidUriErr); end; [Test] [Scope('OnPrem')] procedure UserCanChangeTheAMCSupportURL() var AMCBankingSetup: Record "AMC Banking Setup"; PasswordAMC: Text; SupportURLAMC: Text[250]; begin // [FEATURE] [URL] // [SCENARIO 5] As an Administrator I will be able to update the Support URL for the AMC service, // this is used to enable bank data file conversion to show contact information in case of connection issues. // [GIVEN] A Support URL and an existing AMC Bank Service Setup. // [WHEN] The Support URL is entered into the existing AMC Bank Service Setup // [THEN] The AMC Integration would be able to get the changed Support URL and use it to connect to the AMC service error // information, User ID and Password will remain unchanged. Initialize(); // Setup: Optain username and Support URL AMCBankingSetup.Get(); PasswordAMC := AMCBankingSetup.GetPassword(); SupportURLAMC := LibraryUtility.GenerateRandomCode(AMCBankingSetup.FieldNo("Service URL"), DATABASE::"AMC Banking Setup"); // Execute: Save username and password in service setup AMCBankingSetup.Get(); AMCBankingSetup.Validate("Support URL", SupportURLAMC); AMCBankingSetup.Modify(); // Validate AMCBankingSetup.Get(); Assert.AreEqual(PasswordAMC, AMCBankingSetup.GetPassword(), 'Password invalid'); Assert.AreEqual(SupportURLAMC, AMCBankingSetup."Support URL", 'Support URL invalid'); end; [Test] [Scope('OnPrem')] procedure UserCanDeleteTheAMCSetupInformation() var AMCBankingSetup: Record "AMC Banking Setup"; PasswordKey: Guid; begin // [FEATURE] [Password] // [SCENARIO 6] As a an Administrator I will remove the service setup to prevent use of hte AMC serive // [GIVEN] An existing AMC Bank Service Setup. // [WHEN] Delete of existing AMC Bank Service Setup // [THEN] The AMC Integration would NOT be able to obtain the updated User ID and Password to make use of the AMC Service Initialize(); // Execute: Save username and password in service setup AMCBankingSetup.Get(); PasswordKey := AMCBankingSetup."Password Key"; AMCBankingSetup.Delete(true); // Validate Assert.IsFalse(AMCBankingSetup.Get(), 'Setup should not exist'); Assert.IsFalse(IsolatedStorageManagement.Contains(PasswordKey, DATASCOPE::Company), 'Password should not exist'); end; [Test] [Scope('OnPrem')] procedure UserCanSeeThatAPasswordExist() var AMCBankingSetup: Record "AMC Banking Setup"; begin // [FEATURE] [Password] // [SCENARIO 7] As a an Administrator I can see that a password exist // [GIVEN] An existing AMC Bank Service Setup. // [WHEN] Open AMC Bank Service Setup // [THEN] Password should show ****** Initialize(); // Execute: Save username and password in service setup AMCBankingSetup.Get(); // Validate: The HasPassword used by UI Assert.IsTrue(AMCBankingSetup.HasPassword(), 'Password should exist'); end; [Test] [HandlerFunctions('ConfirmHandlerNo')] [Scope('OnPrem')] procedure StorePasswordWithoutEncryption() var AMCBankingSetupRec: Record "AMC Banking Setup"; CryptographyManagement: Codeunit "Cryptography Management"; AMCBankingSetup: TestPage "AMC Banking Setup"; begin // [FEATURE] [Password] // [SCENARIO 11] The user enters a new password. // [GIVEN] There is no password set for the conversion service. // [WHEN] The user enters a new password. // [THEN] The password will be stored in clear text. Initialize(); // Setup if CryptographyManagement.IsEncryptionEnabled() then CryptographyManagement.DisableEncryption(true); AMCBankingSetup.OpenEdit(); AMCBankingSetup.Password.SetValue(''); // Execute AMCBankingSetup.Password.SetValue('Random Words'); AMCBankingSetup.OK().Invoke(); // Verify Assert.IsFalse(EncryptionEnabled(), EncryptionIsActiveErr); AMCBankingSetupRec.Get(); Assert.AreEqual('Random Words', AMCBankingSetupRec.GetPassword(), PasswordDoesNotMatchErr); end; [Test] [Scope('OnPrem')] procedure StorePasswordWithEncryption() var AMCBankingSetupRec: Record "AMC Banking Setup"; CryptographyManagement: Codeunit "Cryptography Management"; AMCBankingSetup: TestPage "AMC Banking Setup"; begin // [FEATURE] [Password] // [SCENARIO 12] The user enters a new password. // [GIVEN] There is no password set for the conversion service. // [WHEN] The user enters a new password. // [THEN] The password will be stored encrypted. Initialize(); // Setup if CryptographyManagement.IsEncryptionEnabled() then CryptographyManagement.DisableEncryption(true); AMCBankingSetup.OpenEdit(); AMCBankingSetup.Password.SetValue(''); CryptographyManagement.EnableEncryption(true); // Execute AMCBankingSetup.Password.SetValue('Random Words 2'); AMCBankingSetup.OK().Invoke(); // Verify AMCBankingSetupRec.Get(); Assert.AreEqual('Random Words 2', AMCBankingSetupRec.GetPassword(), PasswordDoesNotMatchErr); Assert.IsTrue(EncryptionEnabled(), EncryptionIsNotActiveErr); // Clean-up CryptographyManagement.DisableEncryption(true); end; [Test] [HandlerFunctions('ConfirmHandlerYesNo')] [Scope('OnPrem')] procedure StorePasswordWithoutEncryptionAndCheckConfirmDialog() var AMCBankingSetupRec: Record "AMC Banking Setup"; CryptographyManagement: Codeunit "Cryptography Management"; AMCBankingSetup: TestPage "AMC Banking Setup"; DataEncryptionManagement: TestPage "Data Encryption Management"; begin // [FEATURE] [Password] // [SCENARIO 13] The user enters a new password and a confirmation dialog appears. // [GIVEN] There is no password set for the conversion service. // [WHEN] The user enters a new password. // [THEN] The password will be stored in clear text and a confirmation dialog appears. Initialize(); // Setup HandlerResponse := true; if CryptographyManagement.IsEncryptionEnabled() then CryptographyManagement.DisableEncryption(true); DataEncryptionManagement.Trap(); AMCBankingSetup.OpenEdit(); AMCBankingSetup.Password.SetValue(''); // Execute AMCBankingSetup.Password.SetValue('Random Words 3'); AMCBankingSetup.OK().Invoke(); DataEncryptionManagement.OK().Invoke(); // Verify Assert.IsFalse(EncryptionEnabled(), EncryptionIsActiveErr); AMCBankingSetupRec.Get(); Assert.AreEqual('Random Words 3', AMCBankingSetupRec.GetPassword(), PasswordDoesNotMatchErr); end; [Test] [Scope('OnPrem')] procedure AMCBankingSetupIsCreatedIfItDoesNotExist() var AMCBankingSetup: Record "AMC Banking Setup"; AMCBankingSetupPage: TestPage "AMC Banking Setup"; begin // [FEATURE] [URL] [Demo Company] // [SCENARIO 14] As an admin, when I open the conv setup page I can see the default URLs. Initialize(); SetDemoCompany(true); // [GIVEN] There is no conversion setup record. AMCBankingSetup.DeleteAll(); // [WHEN] The user opens the conversion setup page. AMCBankingSetupPage.OpenEdit(); AMCBankingSetupPage.Password.SetValue(''); // to avoid encryption confirmation AMCBankingSetupPage.OK().Invoke(); // [THEN] The defaul URLs are in place. AMCBankingSetup.Get(); ValidateDefaultURLs(AMCBankingSetup); end; [Test] [Scope('OnPrem')] procedure PageInEditAllFieldsEditable() var AMCBankingSetup: TestPage "AMC Banking Setup"; begin // [FEATURE] [UI] // [SCENARIO 16] As an admin, when open AMC Banking Setup in edit all fields should be editable. Initialize(); // [GIVEN] There is a default conversion setup record. // [WHEN] The user opens the conversion setup page in edit mode. AMCBankingSetup.OpenEdit(); // [THEN] All fields editable. Assert.IsTrue(AMCBankingSetup."User Name".Editable(), 'User Name field should be editable'); Assert.IsTrue(AMCBankingSetup.Password.Editable(), 'Password field should be editable'); Assert.IsTrue(AMCBankingSetup."Service URL".Editable(), 'Service URL field should be editable'); end; [Test] [Scope('OnPrem')] procedure PageInViewAllFieldsReadOnly() var AMCBankingSetup: TestPage "AMC Banking Setup"; begin // [FEATURE] [UI] // [SCENARIO 17] As an admin, when open AMC Banking Setup in view all fields should be read only. Initialize(); // [GIVEN] There is a default conversion setup record. // [WHEN] The user opens the conversion setup page in view mode. AMCBankingSetup.OpenView(); // [THEN] All fields read only. Assert.IsFalse(AMCBankingSetup."User Name".Editable(), 'User Name field should not be editable'); Assert.IsFalse(AMCBankingSetup.Password.Editable(), 'Password field should not be editable'); Assert.IsFalse(AMCBankingSetup."Service URL".Editable(), 'Service URL field should not be editable'); end; local procedure Initialize() var AMCBankingSetup: Record "AMC Banking Setup"; EnvironmentInfoTestLibrary: Codeunit "Environment Info Test Library"; begin LibraryTestInitialize.OnTestInitialize(CODEUNIT::"ERM AMC banking Setup ATDD"); EnvironmentInfoTestLibrary.SetTestabilitySoftwareAsAService(false); AMCBankingSetup.DeleteAll(); AMCBankingSetup.Init(); AMCBankingSetup.Validate("User Name", LibraryUtility.GenerateRandomCode(AMCBankingSetup.FieldNo("User Name"), DATABASE::"AMC Banking Setup")); AMCBankingSetup.SavePassword(GenerateRandomPassword()); AMCBankingSetup."AMC Enabled" := true; AMCBankingSetup.Insert(true); end; local procedure SetDemoCompany(DemoCompany: Boolean) var CompanyInformation: Record "Company Information"; begin CompanyInformation.Get(); CompanyInformation."Demo Company" := DemoCompany; CompanyInformation.Modify(); end; local procedure ValidateSetup(ExpectedUserName: Text[50]; ExpectedPassword: Text) var AMCBankingSetup: Record "AMC Banking Setup"; begin AMCBankingSetup.Get(); Assert.AreEqual(ExpectedUserName, AMCBankingSetup."User Name", 'User Name invalid'); Assert.AreEqual(ExpectedPassword, AMCBankingSetup.GetPassword(), 'Password invalid'); ValidateDefaultURLs(AMCBankingSetup); end; local procedure ValidateDefaultURLs(AMCBankingSetup: Record "AMC Banking Setup") var AMCBankingMgt: Codeunit "AMC Banking Mgt."; begin Assert.AreEqual('https://license.amcbanking.com/register', AMCBankingSetup."Sign-up URL", 'Sign-up invalid'); if ((AMCBankingSetup.Solution = AMCBankingMgt.GetDemoSolutionCode()) or (AMCBankingSetup.Solution = '')) then Assert.AreEqual('https://demoxtl.amcbanking.com/nav03', AMCBankingSetup."Service URL", 'Service URL invalid') else Assert.AreEqual('https://nav.amcbanking.com/nav03', AMCBankingSetup."Service URL", 'Service URL invalid'); Assert.AreEqual('https://amcbanking.com/landing365bc/help/', AMCBankingSetup."Support URL", 'Service URL invalid'); end; local procedure GenerateRandomUrl(Secure: Boolean): Text[250] var AMCBankingSetup: Record "AMC Banking Setup"; RandomCode: Code[250]; Prefix: Text[8]; begin if Secure then Prefix := 'https://' else Prefix := 'http://'; RandomCode := LibraryUtility.GenerateRandomCode(AMCBankingSetup.FieldNo("Service URL"), DATABASE::"AMC Banking Setup"); RandomCode := CopyStr(Prefix + RandomCode, 1, 250); exit(RandomCode); end; local procedure GenerateRandomPassword(): Text begin exit(LibraryUtility.GenerateRandomText(251)); end; [ConfirmHandler] [Scope('OnPrem')] procedure ConfirmHandlerNo(Question: Text; var Reply: Boolean) begin Reply := false; end; [ConfirmHandler] [Scope('OnPrem')] procedure ConfirmHandlerYes(Question: Text; var Reply: Boolean) begin Reply := true; end; [ConfirmHandler] [Scope('OnPrem')] procedure ConfirmHandlerYesNo(Question: Text; var Reply: Boolean) begin Reply := HandlerResponse; HandlerResponse := not HandlerResponse; end; [ModalPageHandler] [Scope('OnPrem')] procedure BlankAMCBankingSetupModalHandler(var AMCBankingSetupPage: TestPage "AMC Banking Setup") begin AMCBankingSetupPage."User Name".AssertEquals('demouser'); Assert.ExpectedMessage('amc', AMCBankingSetupPage."Service URL".Value()); // Set not blank Password to avoid an error AMCBankingSetupPage.Password.SetValue('P'); AMCBankingSetupPage.OK().Invoke(); end; [ModalPageHandler] [Scope('OnPrem')] procedure AMCBankingSetupModalHandlerBlankPassword(var AMCBankingSetupPage: TestPage "AMC Banking Setup") begin // Password is blank AMCBankingSetupPage."User Name".SetValue('newuser'); AMCBankingSetupPage.Password.SetValue(''); AMCBankingSetupPage.OK().Invoke(); end; [ModalPageHandler] [Scope('OnPrem')] procedure AMCBankingSetupModalHandler(var AMCBankingSetupPage: TestPage "AMC Banking Setup") begin // Password is blank AMCBankingSetupPage.OK().Invoke(); end; [PageHandler] [Scope('OnPrem')] procedure DataEncryprtionHandler(var DataEncryptionManagement: TestPage "Data Encryption Management") begin DataEncryptionManagement.Close(); end; }
39.01273
145
0.663295
ed25e4e5e1358a0c4a08d682b65428c6633d4876
1,598
pm
Perl
modules/Bio/EnsEMBL/Hive/DBSQL/ResourceClassAdaptor.pm
muffato/ensembl-hive
6d6fa0ef57dd3a76695e255d2e76d96603b4179b
[ "Apache-2.0" ]
null
null
null
modules/Bio/EnsEMBL/Hive/DBSQL/ResourceClassAdaptor.pm
muffato/ensembl-hive
6d6fa0ef57dd3a76695e255d2e76d96603b4179b
[ "Apache-2.0" ]
null
null
null
modules/Bio/EnsEMBL/Hive/DBSQL/ResourceClassAdaptor.pm
muffato/ensembl-hive
6d6fa0ef57dd3a76695e255d2e76d96603b4179b
[ "Apache-2.0" ]
null
null
null
=pod =head1 NAME Bio::EnsEMBL::Hive::DBSQL::ResourceClassAdaptor =head1 SYNOPSIS $resource_class_adaptor = $db_adaptor->get_ResourceClassAdaptor; $resource_class_adaptor = $resource_class_object->adaptor; =head1 DESCRIPTION Module to encapsulate all db access for persistent class ResourceClass. There should be just one per application and database connection. =head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2022] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =head1 CONTACT Please subscribe to the Hive mailing list: http://listserver.ebi.ac.uk/mailman/listinfo/ehive-users to discuss Hive-related questions or to be notified of our updates =cut package Bio::EnsEMBL::Hive::DBSQL::ResourceClassAdaptor; use strict; use warnings; use base ('Bio::EnsEMBL::Hive::DBSQL::ObjectAdaptor'); sub default_table_name { return 'resource_class'; } sub object_class { return 'Bio::EnsEMBL::Hive::ResourceClass'; } 1;
27.551724
172
0.7597
edca17ec3fa797535964da8d9fa9374f897e5b13
666
t
Perl
tests/impl/uJIT-tests-Lua/suite/profile-leaf.t
luavela/luavela
56c6e8d833cad56ae524ae82d6ae370bedcd2a45
[ "MIT" ]
64
2020-08-18T18:44:47.000Z
2022-03-30T23:14:30.000Z
tests/impl/uJIT-tests-Lua/suite/profile-leaf.t
luavela/luavela
56c6e8d833cad56ae524ae82d6ae370bedcd2a45
[ "MIT" ]
5
2020-08-24T08:15:24.000Z
2021-01-13T08:49:02.000Z
tests/impl/uJIT-tests-Lua/suite/profile-leaf.t
luavela/luavela
56c6e8d833cad56ae524ae82d6ae370bedcd2a45
[ "MIT" ]
3
2020-09-09T09:12:49.000Z
2021-03-19T11:56:07.000Z
#!/usr/bin/perl # # Tests for leaf profiler. # Copyright (C) 2020-2021 LuaVela Authors. See Copyright Notice in COPYRIGHT # Copyright (C) 2015-2020 IPONWEB Ltd. See Copyright Notice in COPYRIGHT use 5.010; use warnings; use strict; use lib './lib'; use UJit::Test; my $tester = UJit::Test->new( chunks_dir => './chunks/profile-leaf', ); my @chunks = qw/ simple.lua mm-continuation.lua ff-vm-state.lua tail-call.lua tail-call-ff.lua coro-yield-resume.lua coro-vm-state.lua callgraph.lua restart.lua /; for my $jit_mode (0, 1) { for my $chunk (@chunks) { $tester->run($chunk, jit => $jit_mode)->exit_ok; } } exit;
19.028571
76
0.651652
73da17c097bb94cba3e57333e422d34422e7afb7
1,219
t
Perl
bundle/srcache-nginx-module-0.31/t/disk.t
zyqCSL/openresty-1.13.6.1-instrumented
21be1c9e8e57a894a38865e34bccb2d3a97a6c18
[ "BSD-2-Clause" ]
147
2015-01-06T05:12:03.000Z
2022-01-13T11:02:44.000Z
bundle/srcache-nginx-module-0.31/t/disk.t
zyqCSL/openresty-1.13.6.1-instrumented
21be1c9e8e57a894a38865e34bccb2d3a97a6c18
[ "BSD-2-Clause" ]
19
2015-01-20T13:50:03.000Z
2021-11-30T15:54:32.000Z
bundle/srcache-nginx-module-0.31/t/disk.t
zyqCSL/openresty-1.13.6.1-instrumented
21be1c9e8e57a894a38865e34bccb2d3a97a6c18
[ "BSD-2-Clause" ]
59
2015-02-13T09:28:51.000Z
2022-02-11T13:37:33.000Z
# vi:filetype= use lib 'lib'; use Test::Nginx::Socket; #repeat_each(100); plan tests => repeat_each() * (2 * blocks() + 1); $ENV{TEST_NGINX_MEMCACHED_PORT} ||= 11211; no_shuffle(); run_tests(); __DATA__ === TEST 1: flush all --- config location /flush { set $memc_cmd 'flush_all'; memc_pass 127.0.0.1:$TEST_NGINX_MEMCACHED_PORT; } --- request GET /flush --- response_body eval: "OK\r\n" === TEST 2: cache miss --- config location /index.html { srcache_fetch GET /memc $uri; srcache_store PUT /memc $uri; } location /memc { internal; set $memc_key $query_string; set $memc_exptime 300; memc_pass 127.0.0.1:$TEST_NGINX_MEMCACHED_PORT; } --- request GET /index.html --- response_headers Accept-Ranges: bytes --- response_body_like: It works! === TEST 3: cache hit --- config location /index.html { srcache_fetch GET /memc $uri; srcache_store PUT /memc $uri; } location /memc { internal; set $memc_key $query_string; set $memc_exptime 300; memc_pass 127.0.0.1:$TEST_NGINX_MEMCACHED_PORT; } --- request GET /index.html --- response_body_like: It works!
17.414286
55
0.61936
ed6382d5dd800d7d738a6f7ca56859f581de3ea2
5,169
pm
Perl
scripts/local/lib/perl5/Test2/Util.pm
ashkanx/binary-mt
ca9d040abb3ee1ac0e79964d79b86ff1bc0446fe
[ "Apache-2.0" ]
null
null
null
scripts/local/lib/perl5/Test2/Util.pm
ashkanx/binary-mt
ca9d040abb3ee1ac0e79964d79b86ff1bc0446fe
[ "Apache-2.0" ]
3
2016-09-22T07:23:29.000Z
2017-02-01T01:39:44.000Z
scripts/local/lib/perl5/Test2/Util.pm
ashkanx/binary-mt
ca9d040abb3ee1ac0e79964d79b86ff1bc0446fe
[ "Apache-2.0" ]
10
2016-09-13T02:10:40.000Z
2021-07-11T23:11:01.000Z
package Test2::Util; use strict; use warnings; our $VERSION = '1.302015'; use Config qw/%Config/; our @EXPORT_OK = qw{ try pkg_to_file get_tid USE_THREADS CAN_THREAD CAN_REALLY_FORK CAN_FORK }; use base 'Exporter'; sub _can_thread { return 0 unless $] >= 5.008001; return 0 unless $Config{'useithreads'}; # Threads are broken on perl 5.10.0 built with gcc 4.8+ if ($] == 5.010000 && $Config{'ccname'} eq 'gcc' && $Config{'gccversion'}) { my @parts = split /\./, $Config{'gccversion'}; return 0 if $parts[0] >= 4 && $parts[1] >= 8; } # Change to a version check if this ever changes return 0 if $INC{'Devel/Cover.pm'}; return 1; } sub _can_fork { return 1 if $Config{d_fork}; return 0 unless $^O eq 'MSWin32' || $^O eq 'NetWare'; return 0 unless $Config{useithreads}; return 0 unless $Config{ccflags} =~ /-DPERL_IMPLICIT_SYS/; return _can_thread(); } BEGIN { no warnings 'once'; *CAN_REALLY_FORK = $Config{d_fork} ? sub() { 1 } : sub() { 0 }; *CAN_THREAD = _can_thread() ? sub() { 1 } : sub() { 0 }; *CAN_FORK = _can_fork() ? sub() { 1 } : sub() { 0 }; } sub _manual_try(&;@) { my $code = shift; my $args = \@_; my $err; my $die = delete $SIG{__DIE__}; eval { $code->(@$args); 1 } or $err = $@ || "Error was squashed!\n"; $die ? $SIG{__DIE__} = $die : delete $SIG{__DIE__}; return (!defined($err), $err); } sub _local_try(&;@) { my $code = shift; my $args = \@_; my $err; no warnings; local $SIG{__DIE__}; eval { $code->(@$args); 1 } or $err = $@ || "Error was squashed!\n"; return (!defined($err), $err); } # Older versions of perl have a nasty bug on win32 when localizing a variable # before forking or starting a new thread. So for those systems we use the # non-local form. When possible though we use the faster 'local' form. BEGIN { if ($^O eq 'MSWin32' && $] < 5.020002) { *try = \&_manual_try; } else { *try = \&_local_try; } } BEGIN { if(CAN_THREAD) { if ($INC{'threads.pm'}) { # Threads are already loaded, so we do not need to check if they # are loaded each time *USE_THREADS = sub() { 1 }; *get_tid = sub { threads->tid() }; } else { # :-( Need to check each time to see if they have been loaded. *USE_THREADS = sub { $INC{'threads.pm'} ? 1 : 0 }; *get_tid = sub { $INC{'threads.pm'} ? threads->tid() : 0 }; } } else { # No threads, not now, not ever! *USE_THREADS = sub() { 0 }; *get_tid = sub() { 0 }; } } sub pkg_to_file { my $pkg = shift; my $file = $pkg; $file =~ s{(::|')}{/}g; $file .= '.pm'; return $file; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Util - Tools used by Test2 and friends. =head1 DESCRIPTION Collection of tools used by L<Test2> and friends. =head1 EXPORTS All exports are optional, you must specify subs to import. =over 4 =item ($success, $error) = try { ... } Eval the codeblock, return success or failure, and the error message. This code protects $@ and $!, they will be restored by the end of the run. This code also temporarily blocks $SIG{DIE} handlers. =item protect { ... } Similar to try, except that it does not catch exceptions. The idea here is to protect $@ and $! from changes. $@ and $! will be restored to whatever they were before the run so long as it is successful. If the run fails $! will still be restored, but $@ will contain the exception being thrown. =item CAN_FORK True if this system is capable of true or psuedo-fork. =item CAN_REALLY_FORK True if the system can really fork. This will be false for systems where fork is emulated. =item CAN_THREAD True if this system is capable of using threads. =item USE_THREADS Returns true if threads are enabled, false if they are not. =item get_tid This will return the id of the current thread when threads are enabled, otherwise it returns 0. =item my $file = pkg_to_file($package) Convert a package name to a filename. =back =head1 NOTES && CAVEATS =over 4 =item 5.10.0 Perl 5.10.0 has a bug when compiled with newer gcc versions. This bug causes a segfault whenever a new thread is launched. Test2 will attempt to detect this, and note that the system is not capable of forking when it is detected. =item Devel::Cover Devel::Cover does not support threads. CAN_THREAD will return false if Devel::Cover is loaded before the check is first run. =back =head1 SOURCE The source code repository for Test2 can be found at F<http://github.com/Test-More/test-more/>. =head1 MAINTAINERS =over 4 =item Chad Granum E<lt>exodist@cpan.orgE<gt> =back =head1 AUTHORS =over 4 =item Chad Granum E<lt>exodist@cpan.orgE<gt> =item Kent Fredric E<lt>kentnl@cpan.orgE<gt> =back =head1 COPYRIGHT Copyright 2016 Chad Granum E<lt>exodist@cpan.orgE<gt>. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F<http://dev.perl.org/licenses/> =cut
22.184549
80
0.631457
edc780b8455a201ee1316d8f0f34ab05c12e2475
1,267
pm
Perl
auto-lib/Azure/StorSimple/GetStorageAccountCredentials.pm
pplu/azure-sdk-perl
26cbef2d926f571bc1617c26338c106856f95568
[ "Apache-2.0" ]
null
null
null
auto-lib/Azure/StorSimple/GetStorageAccountCredentials.pm
pplu/azure-sdk-perl
26cbef2d926f571bc1617c26338c106856f95568
[ "Apache-2.0" ]
null
null
null
auto-lib/Azure/StorSimple/GetStorageAccountCredentials.pm
pplu/azure-sdk-perl
26cbef2d926f571bc1617c26338c106856f95568
[ "Apache-2.0" ]
1
2021-04-08T15:26:39.000Z
2021-04-08T15:26:39.000Z
package Azure::StorSimple::GetStorageAccountCredentials; use Moose; use MooseX::ClassAttribute; has 'api_version' => (is => 'ro', required => 1, isa => 'Str', default => '2017-06-01', traits => [ 'Azure::ParamInQuery', 'Azure::LocationInResponse' ], location => 'api-version', ); has 'managerName' => (is => 'ro', required => 1, isa => 'Str', traits => [ 'Azure::ParamInPath' ], ); has 'resourceGroupName' => (is => 'ro', required => 1, isa => 'Str', traits => [ 'Azure::ParamInPath' ], ); has 'storageAccountCredentialName' => (is => 'ro', required => 1, isa => 'Str', traits => [ 'Azure::ParamInPath' ], ); has 'subscriptionId' => (is => 'ro', required => 1, isa => 'Str', traits => [ 'Azure::ParamInPath' ], ); class_has _api_uri => (is => 'ro', default => '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/storageAccountCredentials/{storageAccountCredentialName}'); class_has _returns => (is => 'ro', isa => 'HashRef', default => sub { { 200 => 'Azure::StorSimple::GetStorageAccountCredentialsResult', } }); class_has _is_async => (is => 'ro', default => 0); class_has _api_method => (is => 'ro', default => 'GET'); 1;
42.233333
229
0.617995
ed84d1633de12301d2a91691cd9129b23061a3b2
494
pl
Perl
scripting/japh_map.pl
bheckel/code
98309e8aa145901e49460546643c911eaaff54e6
[ "Apache-2.0" ]
1
2019-08-11T00:39:34.000Z
2019-08-11T00:39:34.000Z
scripting/japh_map.pl
bheckel/code
98309e8aa145901e49460546643c911eaaff54e6
[ "Apache-2.0" ]
null
null
null
scripting/japh_map.pl
bheckel/code
98309e8aa145901e49460546643c911eaaff54e6
[ "Apache-2.0" ]
1
2020-07-28T05:58:47.000Z
2020-07-28T05:58:47.000Z
#!/usr/bin/perl -w ############################################################################## # Name: japh_map.pl # # Summary: Demo of map (and obfuscation). # # Adapted: Fri 16 Mar 2001 08:54:20 (Bob Heckel -- from RayCosoft website) ############################################################################## $octalstr = '106117115116032097110111116104101114032112101114108032104097' . '099107101114'; @japh = map { chr $_ } ($octalstr =~ /.../g); print @japh, "\n";
30.875
78
0.44332
ed42e13c7404e80c0a1b4c8bff093afbb1c52512
6,655
pl
Perl
msys64/usr/share/perl5/core_perl/unicore/lib/CWU/Y.pl
andresfaagit/sg-desarrollo-ruby
2c9bc5dad657d9713cc0f7fc4e883a85b83537e5
[ "Ruby" ]
9
2018-04-19T05:08:30.000Z
2021-11-23T07:36:58.000Z
msys64/usr/share/perl5/core_perl/unicore/lib/CWU/Y.pl
andresfaagit/sg-desarrollo-ruby
2c9bc5dad657d9713cc0f7fc4e883a85b83537e5
[ "Ruby" ]
98
2017-11-02T19:00:44.000Z
2022-03-22T16:15:39.000Z
msys64/usr/share/perl5/core_perl/unicore/lib/CWU/Y.pl
andresfaagit/sg-desarrollo-ruby
2c9bc5dad657d9713cc0f7fc4e883a85b83537e5
[ "Ruby" ]
9
2017-10-24T21:53:36.000Z
2021-11-23T07:36:59.000Z
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 12.1.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. Use Unicode::UCD to access the Unicode character data # base. return <<'END'; V1232 97 123 181 182 223 247 248 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 378 379 380 381 382 385 387 388 389 390 392 393 396 397 402 403 405 406 409 411 414 415 417 418 419 420 421 422 424 425 429 430 432 433 436 437 438 439 441 442 445 446 447 448 453 455 456 458 459 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 497 498 500 501 502 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 572 573 575 577 578 579 583 584 585 586 587 588 589 590 591 597 598 600 601 602 603 605 608 610 611 612 613 615 616 621 623 624 625 627 629 630 637 638 640 641 642 644 647 653 658 659 669 671 837 838 881 882 883 884 887 888 891 894 912 913 940 975 976 978 981 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1012 1013 1014 1016 1017 1019 1020 1072 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1377 1416 4304 4347 4349 4352 5112 5118 7296 7305 7545 7546 7549 7550 7566 7567 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7836 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7944 7952 7958 7968 7976 7984 7992 8000 8006 8016 8024 8032 8040 8048 8062 8064 8117 8118 8120 8124 8125 8126 8127 8130 8133 8134 8136 8140 8141 8144 8148 8150 8152 8160 8168 8178 8181 8182 8184 8188 8189 8526 8527 8560 8576 8580 8581 9424 9450 11312 11359 11361 11362 11365 11367 11368 11369 11370 11371 11372 11373 11379 11380 11382 11383 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11500 11501 11502 11503 11507 11508 11520 11558 11559 11560 11565 11566 42561 42562 42563 42564 42565 42566 42567 42568 42569 42570 42571 42572 42573 42574 42575 42576 42577 42578 42579 42580 42581 42582 42583 42584 42585 42586 42587 42588 42589 42590 42591 42592 42593 42594 42595 42596 42597 42598 42599 42600 42601 42602 42603 42604 42605 42606 42625 42626 42627 42628 42629 42630 42631 42632 42633 42634 42635 42636 42637 42638 42639 42640 42641 42642 42643 42644 42645 42646 42647 42648 42649 42650 42651 42652 42787 42788 42789 42790 42791 42792 42793 42794 42795 42796 42797 42798 42799 42800 42803 42804 42805 42806 42807 42808 42809 42810 42811 42812 42813 42814 42815 42816 42817 42818 42819 42820 42821 42822 42823 42824 42825 42826 42827 42828 42829 42830 42831 42832 42833 42834 42835 42836 42837 42838 42839 42840 42841 42842 42843 42844 42845 42846 42847 42848 42849 42850 42851 42852 42853 42854 42855 42856 42857 42858 42859 42860 42861 42862 42863 42864 42874 42875 42876 42877 42879 42880 42881 42882 42883 42884 42885 42886 42887 42888 42892 42893 42897 42898 42899 42901 42903 42904 42905 42906 42907 42908 42909 42910 42911 42912 42913 42914 42915 42916 42917 42918 42919 42920 42921 42922 42933 42934 42935 42936 42937 42938 42939 42940 42941 42942 42943 42944 42947 42948 43859 43860 43888 43968 64256 64263 64275 64280 65345 65371 66600 66640 66776 66812 68800 68851 71872 71904 93792 93824 125218 125252 END
5.336808
77
0.791585
edaa5ad3b1cd8359e642487f08484b6bfed20186
3,658
pl
Perl
qeynos2/Knargon_Lanenda.pl
GiverofMemory/FVProject-Quests
8754c17305f1b9f56fff5e2952127f628be10646
[ "MIT" ]
1
2021-11-25T23:33:55.000Z
2021-11-25T23:33:55.000Z
qeynos2/Knargon_Lanenda.pl
GiverofMemory/FVProject-Quests
8754c17305f1b9f56fff5e2952127f628be10646
[ "MIT" ]
6
2020-02-12T16:39:52.000Z
2021-08-16T22:12:59.000Z
qeynos2/Knargon_Lanenda.pl
GiverofMemory/FVProject-Quests
8754c17305f1b9f56fff5e2952127f628be10646
[ "MIT" ]
7
2019-12-28T20:06:14.000Z
2021-11-23T17:21:38.000Z
sub EVENT_SAY { if ($text=~/hail/i) { quest::say("Hey.. What's up? My name's Knargon Lanenda. I just came over here from [Freeport] a couple of months ago. I used to run a big business importing goods from [Faydwer]. If you've been to [Freeport]. I'm sure you've heard of me."); } elsif ($text=~/freeport/i) { quest::say("It's a long way from here. . .which is a good thing for me."); } elsif ($text=~/faydwer/i) { quest::say("It's a long way from here. . .which is a good thing for me."); } elsif ($text=~/jracol/i) { quest::say("I don't know why [Carson] likes that guy ... he's certainly been nothing but trouble for me."); } elsif (($text=~/carson/i) || ($text=~/mccabe/i)) { quest::say("Carson McCabe? He runs that sham of a fortress called [Highpass Hold]. We've been dealing with him for a few years, now. But, lately he seems to be losing control of his business. [Hanns] will whip him into shape pretty soon though, I bet."); } elsif ($text=~/highpass hold/i) { quest::say("It's a long way from here. . .which is a good thing for me."); } elsif ($text=~/hanns/i) { quest::say("He is genuinely dangerous. If you think otherwise, you won't be thinking for long."); } elsif ($text=~/shipment/i) { quest::say("We have a small shipment of goods coming in later tonight. The [courier] will be waiting outside the city gates. Casually tell the courier [Lovely night for a stroll], and give him this old card as proof that you work for us. Make certain that you are not followed, and return the shipment to me."); #:: Give a 13903 - Bent Playing Card quest::summonitem(13903); } elsif ($text=~/courier/i) { quest::say("The courier that usually runs [McCabe]'s shipment, is that good for nothing J'Racol. I don't trust his kind."); } } sub EVENT_WAYPOINT_ARRIVE { #:: Match waypoint 2 if ($wp == 2) { quest::say("Hey Pelshia, how's business?"); #:: Send a signal "1" to North Qeynos >> Pelshia_Thuxpire (2073) quest::signalwith(2073, 1, 0); } #:: Match waypoint 7 elsif ($wp == 7) { quest::say("And what about you, gorgeous? Looking as delightful as ever, I must say."); #:: This seems to be aimed at Renux, response not found yet } #:: Match waypoint 18 elsif ($wp == 18) { quest::say("So, yeah, that Pelshia, she's all over me. And Renux, too. She was giving me the look, man. I'm telling ya. Zan, all the ladies want a piece of the Knargman."); #:: Send a signal "1" to North Qeynos >> Zannsin_Resdinet (2085) #:: Send a signal "1" to North Qeynos >> Zannsin_Resdinet (2085) with no delay quest::signalwith(2085, 1, 0); } } sub EVENT_SIGNAL { #:: Match a signal "1" from /qeynos2/Pelshia_Thuxpire.pl if ($signal == 1) { quest::say("How about you and I go take a stroll under the docks tonight?"); #:: Send a signal "2" to North Qeynos >> Pelshia_Thuxpire (2073) quest::signalwith(2073, 2, 0); } } sub EVENT_ITEM { #:: Match a 18722 - Sealed Note For Knargon if (plugin::takeItems(18722 => 1)) { quest::say("Hmm. Carson better deal with his little 'problem' soon, it's costing us a lot of money. Hanns is gonna skin us all when he hears this. Go tell Hanns that [Carson has a mole in the Highpass] guards, and see what he wants us to do."); #:: Ding! quest::ding(); #:: Set factions quest::faction(223, 5); #:: + Circle Of Unseen Hands quest::faction(291, -1); #:: - Merchants of Qeynos quest::faction(230, 1); #:: + Corrupt Qeynos Guards quest::faction(262, -1); #:: - Guards of Qeynos quest::faction(273, 1); #:: + Kane Bayle #:: Grant a small amount of experience quest::exp(500); } #:: Return unused items plugin::returnUnusedItems(); }
45.725
313
0.668398
ed155713976c23f43496abb2b1a154c202e45350
1,738
pl
Perl
bin/tests/system/statschannel/traffic-json.pl
goby/bind9
a179cbdf652095d00e7774320592f25eab0210d8
[ "Apache-2.0" ]
1
2019-02-06T14:25:43.000Z
2019-02-06T14:25:43.000Z
bin/tests/system/statschannel/traffic-json.pl
muks/bind9
c762e15991fb24fce6d877c61ddd702e9c7ae9d6
[ "Apache-2.0" ]
null
null
null
bin/tests/system/statschannel/traffic-json.pl
muks/bind9
c762e15991fb24fce6d877c61ddd702e9c7ae9d6
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/perl # # Copyright (C) 2015 Internet Systems Consortium, Inc. ("ISC") # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY # AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR # PERFORMANCE OF THIS SOFTWARE. # traffic-json.pl: # Parses the JSON version of the RSSAC002 traffic stats into a # normalized format. use JSON; my $file = $ARGV[0]; open(INPUT, "<$file"); my $text = do{local$/;<INPUT>}; close(INPUT); my $ref = decode_json($text); my $tcprcvd = $ref->{traffic}->{"tcp-requests-received"}; my $type = "tcp request-size "; foreach $key (keys $tcprcvd) { print $type . $key . ": ". $tcprcvd->{$key} ."\n"; } my $tcpsent = $ref->{traffic}->{"tcp-responses-sent"}; my $type = "tcp response-size "; foreach $key (keys $tcpsent) { print $type . $key . ": ". $tcpsent->{$key} ."\n"; } my $udprcvd = $ref->{traffic}->{"udp-requests-received"}; my $type = "udp request-size "; foreach $key (keys $udprcvd) { print $type . $key . ": ". $udprcvd->{$key} ."\n"; } my $udpsent = $ref->{traffic}->{"udp-responses-sent"}; my $type = "udp response-size "; foreach $key (keys $udpsent) { print $type . $key . ": ". $udpsent->{$key} ."\n"; }
32.792453
77
0.674914
eddccd7159cc4f96e40e287c448e694d39753a08
3,834
pm
Perl
lib/DDG/Spice/PackageTracking.pm
ManrajGrover/zeroclickinfo-spice
f52ecd7a7246dc306b94ab9bbfa93174b8ec8b40
[ "Apache-2.0" ]
null
null
null
lib/DDG/Spice/PackageTracking.pm
ManrajGrover/zeroclickinfo-spice
f52ecd7a7246dc306b94ab9bbfa93174b8ec8b40
[ "Apache-2.0" ]
null
null
null
lib/DDG/Spice/PackageTracking.pm
ManrajGrover/zeroclickinfo-spice
f52ecd7a7246dc306b94ab9bbfa93174b8ec8b40
[ "Apache-2.0" ]
null
null
null
package DDG::Spice::PackageTracking; use strict; use DDG::Spice; use Text::Trim; use YAML::XS 'LoadFile'; spice is_cached => 1; spice proxy_cache_valid => "200 1m"; spice wrap_jsonp_callback => 1; spice to => 'https://api.packagetrackr.com/ddg/v1/track/simple?n=$1&api_key={{ENV{DDG_SPICE_PACKAGETRACKR_API_KEY}}}'; my @carriers = sort { length $b <=> length $a } @{LoadFile(share('carriers.yml'))}; my $triggers_re = qr/(package|parcel)|track(ing)?( num(ber)?)?|shipping status/i; my $carriers_re = join "|", @carriers; # allow carrier names without spaces (e.g royal mail OR royalmail) $carriers_re =~ s/ /\\s*/g; my $strip_re = qr/\b(?:$carriers_re|$triggers_re)\b/i; ### Regex triggers for queries containing carrier names ### or words related to pacakge tracking # Carrier names triggers query_lc => qr/\b(?:$carriers_re)\b/i; # Package words triggers query_lc => qr/^$triggers_re .+|.+ $triggers_re$/i; ### Regex triggers for queries only containing a tracking number ## UPS # Soure: https://www.ups.com/content/ca/en/tracking/help/tracking/tnh.html # To Do: Some additional formats exist triggers query_nowhitespace => qr/^ (?: 1Z[0-9A-Z]{16} | \d{9} | \d{12} | T\d{10} ) $/xi; ## Fedex # Source: https://www.trackingex.com/fedex-tracking.html # https://www.trackingex.com/fedexuk-tracking.html # https://www.trackingex.com/fedex-poland-domestic-tracking.html triggers query_nowhitespace => qr/^ \d{12,22} $/xi; ## USPS # Source: https://tools.usps.com/go/TrackConfirmAction!input.action triggers query_nowhitespace => qr/^ (?: (94001|92055|94073|93033|92701|92088|92021)\d{17} | 82\d{8} | [A-Z]{2}\d{9}US ) $/xi; ## Parcelforce # Source: http://www.parcelforce.com/help-and-advice/sending-worldwide/tracking-number-formats # Note: May need to restrict pattern #3 if overtriggering # https://github.com/duckduckgo/zeroclickinfo-goodies/issues/3900 triggers query_nowhitespace => qr/^ (?: [A-Z]{2}\d{7} | [A-Z]{4}\d{10} | [A-Z]{2}\d{9}[A-Z]{2} | \d{12} ) $/xi; handle query => sub { # remove trigger words & carrier names s/\b$strip_re\b//ixg; trim($_); return unless $_; # remainder should be numeric or alphanumeric, not alpha return if m/^[A-Z]+$/i; # ignore remainder with 2+ words return if m/\b[A-Z]+\s+[A-Z]+\b/i; # ignore phone numbers return if m/^(\d(-|\s))?\d{3}(-|\s)\d{3}(-|\s)\d{4}$/; return if m/^\d{5} \d{7}$/; return if m/^\d{4} \d{3} \d{3}$/; # ignore address lookup return if m/^#\d+ [A-Z\s]+$/i; # ignore Microsoft knowledge base codes and Luhn Check queries # e.g. KB2553549 return if m/^(kb|luhn)\s?\d+/i; # ignore pattern: "word number word" # e.g. ups building 2 worldport return if m/\b[A-Z]+ \d{1,8} [A-Z]+\b/i; # remove spaces/dashes s/(\s|-)//g; # ignore repeated strings of single digit (e.g. 0000 0000 0000) return if m/^(\d)\1+$/; # remainder should be 6-30 characters long return unless m/^[A-Z0-9]{6,30}$/i; # ignore if isbn is present return if m/isbn/i; return $_; }; 1;
31.42623
118
0.518519
73f5ef1c666911d0c7abd950803fcf1c59b0af5b
967
pl
Perl
check_kzp.pl
0xAF/check_kzp
a8fdd069730886a280e897446e7790203d4350d9
[ "Unlicense" ]
null
null
null
check_kzp.pl
0xAF/check_kzp
a8fdd069730886a280e897446e7790203d4350d9
[ "Unlicense" ]
null
null
null
check_kzp.pl
0xAF/check_kzp
a8fdd069730886a280e897446e7790203d4350d9
[ "Unlicense" ]
null
null
null
#!/usr/bin/perl # Stanislav Lechev [0xAF] # mail: af@0xAF.org use strict; use Digest::MD5 qw( md5_hex ); use File::Fetch; my $kzp_url = 'http://www.kzp.bg/download.php?mode=fileDownload&p_attached_file_id=4956'; die "usage: $0 mails_file.txt [kzp_file.txt]\n" unless ($#ARGV >= 0); die "cannot open mails file: $!" unless (open(my $f_mails, '<', $ARGV[0])); my %kzp; my $kzp_content; if ($ARGV[1] and -e $ARGV[1]) { # open kzp file die "cannot open kzp file: $!" unless (open(my $f_kzp, '<', $ARGV[1])); local $/; $kzp_content = <$f_kzp>; } else { # or download the latest version of the file print STDERR "- downloading last KZP file...\n"; my $ff = File::Fetch->new(uri => $kzp_url); my $file = $ff->fetch( to => \$kzp_content ) or die $ff->error; } $kzp_content =~ s/\r//g; foreach (split(/\n/, $kzp_content)) { $kzp{lc($_)} = 1; } while ( <$f_mails> ) { chomp; my $md5 = md5_hex(lc($_)); $kzp{$md5} ? print STDERR "- KZP: $_\n" : print "$_\n"; }
26.135135
89
0.616339
ed72b8d8cd5ac6ceefe603df5a889085f107dff0
2,668
pm
Perl
SeccubusV2.pm
Web5design/Seccubus_v2
0b9d3c5a9bac08fc316cee9795388cbbed0e78f0
[ "Apache-2.0" ]
1
2021-04-08T12:16:18.000Z
2021-04-08T12:16:18.000Z
SeccubusV2.pm
Web5design/Seccubus_v2
0b9d3c5a9bac08fc316cee9795388cbbed0e78f0
[ "Apache-2.0" ]
null
null
null
SeccubusV2.pm
Web5design/Seccubus_v2
0b9d3c5a9bac08fc316cee9795388cbbed0e78f0
[ "Apache-2.0" ]
null
null
null
# ------------------------------------------------------------------------------ # Copyright 2013 Frank Breedijk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. package SeccubusV2; =head1 NAME $RCSfile: SeccubusV2.pm,v $ This Pod documentation generated from the module SeccubusV2 gives a list of all functions within the module. =cut @ISA = ('Exporter'); @EXPORT = qw( VERSION get_config check_param ); use XML::Simple; use Data::Dumper; our $config = "config.xml"; # Change this value to match your setup # if your configuration file cannot be # found $config = "/home/seccubus/etc/config.xml" unless -e $config; # Bug #62 - /home/seccubus/etc missing $config = "/etc/seccubus/config.xml" unless -e $config; $config = "/opt/seccubus/etc/config.xml" unless -e $config; # This line should prevent issue 21 dummy.config.xml should never exist $config = "etc/dummy.config.xml" unless -e $config; # Module directory use lib "/opt/seccubus/SeccubusV2"; push (@main::INC, @INC); $VERSION = '2.5'; use strict; use Carp; #use SeccubusConfig; use SeccubusHelpers; push (@main::INC, @INC); $ENV{REMOTE_USER} = "admin" unless $ENV{REMOTE_USER}; # Run as admin user if the web server auth is not setup check_config(); =head1 Utility functions =head2 get_config =over 2 =item Returns Reference to a hash containing the config in XML =back =cut sub get_config() { if ( ! ref($config) ) { $config = XMLin($config); } return $config; } =head2 check_param Function to check CGI parameters =over 2 =item Parameters =over 4 =item name - name of the parameter =item value - value of the parameter =item is_numeric - Optional parameter, if set the function checks if the parameter is numeric =item Returns False if parameter is ok, error text if otherwise =back =cut sub check_param($$;$) { my $name = shift or die "No name provided"; my $value = shift; my $is_numeric = shift; if ( not defined $value ) { return "Parameter $name is missing"; } elsif ( $is_numeric ) { if ( $value + 0 eq $value ) { return undef; } else { return "Parameter $name is not numeric"; } } } # Close the PM file. return 1;
21.174603
110
0.685907
ede08d0e22ef12f7f6c53b4c0e2b024d7263f96d
610
ph
Perl
febe/Common/AppFrontEnd/fe_Core/fe_ChooseRibbonScriptFileDlg/chooseRibbonScriptFileDlg.ph
PdcVipSolutions/SpbExamples
70b9767910316720fc3adf04b640027e3391f2c0
[ "MIT" ]
1
2020-03-26T12:32:53.000Z
2020-03-26T12:32:53.000Z
AppData/ProjectTemplates/febe/Common/AppFrontEnd/fe_Core/fe_ChooseRibbonScriptFileDlg/chooseRibbonScriptFileDlg.ph
PdcVipSolutions/SpbVipTools
0c77a6af97df6f826f8a898bf0aefe6b4e8420da
[ "MIT" ]
null
null
null
AppData/ProjectTemplates/febe/Common/AppFrontEnd/fe_Core/fe_ChooseRibbonScriptFileDlg/chooseRibbonScriptFileDlg.ph
PdcVipSolutions/SpbVipTools
0c77a6af97df6f826f8a898bf0aefe6b4e8420da
[ "MIT" ]
null
null
null
#requires @"..\Common\AppFrontEnd\fe_Core\fe_chooseRibbonScriptFileDlg\chooseRibbonScriptFileDlg.pack" % publicly used packages #include @"..\Common\AppFrontEnd\fe_Core\fe_ChooseRibbonScriptFileDlg\chooseRibbonScriptFileDlg.ph" #include @"pfc\core.ph" #include @"pfc\gui\gui.ph" % exported interfaces #include @"Interfaces\Logic\dictionary.i" #include @"Interfaces\Logic\coreDictionary.i" #include @"..\Common\AppFrontEnd\fe_Core\fe_ChooseRibbonScriptFileDlg\chooseRibbonScriptFileDlg.i" % exported classes #include @"..\Common\AppFrontEnd\fe_Core\fe_chooseRibbonScriptFileDlg\chooseRibbonScriptFileDlg.cl"
43.571429
103
0.82459
ed98ca08f2e23ffe93eb81515b031959a16ada83
3,058
pm
Perl
modules/EnsEMBL/Web/Command/UserData/FviewRedirect.pm
pblins/ensembl-webcode
1b70534380de5e46f3778b03296ffad6eaf739db
[ "Apache-2.0" ]
null
null
null
modules/EnsEMBL/Web/Command/UserData/FviewRedirect.pm
pblins/ensembl-webcode
1b70534380de5e46f3778b03296ffad6eaf739db
[ "Apache-2.0" ]
null
null
null
modules/EnsEMBL/Web/Command/UserData/FviewRedirect.pm
pblins/ensembl-webcode
1b70534380de5e46f3778b03296ffad6eaf739db
[ "Apache-2.0" ]
null
null
null
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2022] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut package EnsEMBL::Web::Command::UserData::FviewRedirect; ### Redirects from the 'FeatureView' form to Location/Genome use strict; use warnings; use URI::Escape qw(uri_escape); use EnsEMBL::Web::Builder; use base qw(EnsEMBL::Web::Command::UserData); sub process { my $self = shift; my $hub = $self->hub; my $site_type = $hub->species_defs->ENSEMBL_SITETYPE; my $ftype = $hub->param('ftype'); my $builder = $hub->controller->builder; my $object = $builder->create_object('Feature'); my $features = $object && $object->can('convert_to_drawing_parameters') ? $object->convert_to_drawing_parameters : {}; my $desc = $hub->param('name') || "Selected ${ftype}s"; my $content = sprintf qq{track name=%s description="%s" useScore=1 color=%s style=%s\n}, $ftype, $desc, $hub->param('colour'), $hub->param('style'); ## Write out features as GFF file while (my ($type, $feat) = each %$features) { foreach my $f (@{$feat->[0] || []}) { ## Skip features (genes) on LRGs next if $f->{'region'} =~ /^LRG/; my $strand = $f->{'strand'} == 1 ? '+' : '-'; my @attribs; if ($ftype eq 'Gene') { @attribs = ( 'ID ' . $f->{'gene_id'}[0], 'extname ' . $f->{'extname'}, 'description ' . uri_escape($f->{'extra'}{'description'}) ); } else { @attribs = ( 'length ' . $f->{'length'}, 'label ' . uri_escape($f->{'label'}), 'align ' . $f->{'extra'}{'align'}, 'ori ' . $f->{'extra'}{'ori'}, 'id ' . $f->{'extra'}{'id'}, 'score ' . $f->{'extra'}{'score'}, 'p-value ' . $f->{'extra'}{'p-value'}, ); } $content .= join "\t", $f->{'region'}, $site_type, $ftype, $f->{'start'}, $f->{'end'}, '.', $strand, '.', join('; ', @attribs); $content .= "\n"; } } $hub->param('text', $content); $hub->param('format', 'GTF'); $hub->param('name', $desc); my $upload = $self->upload('text'); ## Upload munged data my $url = $hub->url({ species => $hub->param('species'), type => 'Location', action => 'Genome', function => undef, __clear => 1 }); my $params = { Vkaryotype => "upload_$upload->{'code'}=on" }; $self->ajax_redirect($url, $params, undef, 'page'); } 1;
35.149425
152
0.581426
edbd6fc7c52125dd214ca76eb23ad1fb1a929758
369
pm
Perl
perl/vendor/lib/XML/SAX/PurePerl/UnicodeExt.pm
mnikolop/Thesis_project_CyberDoc
9a37fdd5a31de24cb902ee31ef19eb992faa1665
[ "Apache-2.0" ]
7
2016-01-29T21:34:09.000Z
2020-05-20T13:36:14.000Z
perl/vendor/lib/XML/SAX/PurePerl/UnicodeExt.pm
mnikolop/Thesis_project_CyberDoc
9a37fdd5a31de24cb902ee31ef19eb992faa1665
[ "Apache-2.0" ]
7
2018-10-07T10:55:46.000Z
2019-04-02T17:04:28.000Z
perl/vendor/lib/XML/SAX/PurePerl/UnicodeExt.pm
mnikolop/Thesis_project_CyberDoc
9a37fdd5a31de24cb902ee31ef19eb992faa1665
[ "Apache-2.0" ]
11
2015-09-24T01:35:57.000Z
2021-06-08T19:00:55.000Z
# $Id$ package XML::SAX::PurePerl; use strict; no warnings 'utf8'; sub chr_ref { return chr(shift); } if ($] >= 5.007002) { require Encode; Encode::define_alias( "UTF-16" => "UCS-2" ); Encode::define_alias( "UTF-16BE" => "UCS-2" ); Encode::define_alias( "UTF-16LE" => "ucs-2le" ); Encode::define_alias( "UTF16LE" => "ucs-2le" ); } 1;
16.043478
52
0.571816
ede8ed05acaebca4d33411f7742d2536f6bfc400
12,773
pl
Perl
test/layer_factory/layer_factory.pl
guimaraes13/NeuralLog
63cca557257ec67905b79048718db385cc4c3aab
[ "Apache-2.0" ]
6
2021-05-04T12:24:17.000Z
2021-07-28T03:20:48.000Z
test/layer_factory/layer_factory.pl
guimaraes13/NeuralLog
63cca557257ec67905b79048718db385cc4c3aab
[ "Apache-2.0" ]
null
null
null
test/layer_factory/layer_factory.pl
guimaraes13/NeuralLog
63cca557257ec67905b79048718db385cc4c3aab
[ "Apache-2.0" ]
null
null
null
set_parameter(initial_value, class_name, random_uniform). set_parameter(initial_value, config, minval, 0.02). set_parameter(initial_value, config, maxval, 0.05). learn(predicate_0_trainable). learn("century/1"). learn("female/1"). learn("it_female/1"). learn("multiply_2/2"). learn("height/2"). learn("it_height/2"). learn("inv_age/2"). learn("it_inv_age/2"). learn("uncle/2"). learn("it_uncle/2"). learn("aunt/2"). learn("it_aunt/2"). learn("nephew/2"). learn("niece/2"). learn("it_niece/2"). 0.3::predicate_0_not_trainable. 0.5::predicate_0_trainable. 0.7::year(2019). 0.9::century(21). 0.5::multiply(2, 3). 0.25::multiply_2(4, 3). 0.02::male(alfonso). 0.03::male(andrew). 0.05::male(arthur). male(charles). 0.07::male(christopher). 0.07::male(some_male). 0.11::male(colin). 0.13::male(emilio). 0.17::male(james). 0.19::male(marco). 0.23::male(pierro). 0.31::male(roberto). 0.37::male(tomaso). 0.101::female(angela). 0.103::female(charlotte). 0.107::female(christine). 0.107::female(some_female). 0.109::female(francesca). 0.113::female(gina). 0.127::female(jennifer). 0.137::female(lucia). 0.139::female(margaret). 0.149::female(maria). 0.151::female(penelope). 0.157::female(sophia). 0.163::female(victoria). 0.02::it_male(alfonso). 0.03::it_male(andrew). 0.05::it_male(arthur). it_male(charles). 0.07::it_male(christopher). 0.07::it_male(some_male). 0.11::it_male(colin). 0.13::it_male(emilio). 0.17::it_male(james). 0.19::it_male(marco). 0.23::it_male(pierro). 0.31::it_male(roberto). 0.37::it_male(tomaso). 0.101::it_female(angela). 0.103::it_female(charlotte). 0.107::it_female(christine). 0.107::it_female(some_female). 0.109::it_female(francesca). 0.113::it_female(gina). 0.127::it_female(jennifer). 0.137::it_female(lucia). 0.139::it_female(margaret). 0.149::it_female(maria). 0.151::it_female(penelope). 0.157::it_female(sophia). 0.163::it_female(victoria). 0.211::age(some_male, 30). 0.223::age(colin, 41). 0.227::age(emilio, 27). 0.239::age(some_female, 23). 0.241::age(francesca, 27). 0.251::age(gina, 81). 0.211::it_age(some_male, 30). 0.223::it_age(colin, 41). 0.227::it_age(emilio, 27). 0.239::it_age(some_female, 23). 0.241::it_age(francesca, 27). 0.251::it_age(gina, 81). 0.307::height(some_male, 1.73). 0.311::height(colin, 1.57). 0.313::height(emilio, 2.06). 0.317::height(james, 1.70). 0.331::height(marco, 1.65). 0.337::height(some_female, 1.72). 0.347::height(francesca, 1.70). 0.349::height(gina, 1.45). 0.353::height(jennifer, 1.73). 0.359::height(lucia, 1.59). 0.367::height(pierro, 1.82). 0.373::height(charlotte, 1.81). 0.307::it_height(some_male, 1.73). 0.311::it_height(colin, 1.57). 0.313::it_height(emilio, 2.06). 0.317::it_height(james, 1.70). 0.331::it_height(marco, 1.65). 0.337::it_height(some_female, 1.72). 0.347::it_height(francesca, 1.70). 0.349::it_height(gina, 1.45). 0.353::it_height(jennifer, 1.73). 0.359::it_height(lucia, 1.59). 0.367::it_height(pierro, 1.82). 0.373::it_height(charlotte, 1.81). 0.211::inv_age(30, some_male). 0.223::inv_age(41, colin). 0.227::inv_age(27, emilio). 0.239::inv_age(23, some_female). 0.241::inv_age(27, francesca). 0.251::inv_age(81, gina). 0.211::it_inv_age(30, some_male). 0.223::it_inv_age(41, colin). 0.227::it_inv_age(27, emilio). 0.239::it_inv_age(23, some_female). 0.241::it_inv_age(27, francesca). 0.251::it_inv_age(81, gina). 0.307::inv_height(1.73, some_male). 0.311::inv_height(1.57, colin). 0.313::inv_height(2.06, emilio). 0.317::inv_height(1.70, james). 0.331::inv_height(1.65, marco). 0.337::inv_height(1.72, some_female). 0.347::inv_height(1.70, francesca). 0.349::inv_height(1.45, gina). 0.353::inv_height(1.73, jennifer). 0.359::inv_height(1.65, lucia). 0.367::inv_height(1.65, pierro). 0.373::inv_height(1.81, charlotte). 0.307::it_inv_height(1.73, some_male). 0.311::it_inv_height(1.57, colin). 0.313::it_inv_height(2.06, emilio). 0.317::it_inv_height(1.70, james). 0.331::it_inv_height(1.65, marco). 0.337::it_inv_height(1.72, some_female). 0.347::it_inv_height(1.70, francesca). 0.349::it_inv_height(1.45, gina). 0.353::it_inv_height(1.73, jennifer). 0.359::it_inv_height(1.65, lucia). 0.367::it_inv_height(1.65, pierro). 0.373::it_inv_height(1.81, charlotte). 0.547::husband(andrew, christine). 0.557::husband(arthur, margaret). 0.563::husband(charles, jennifer). 0.569::husband(christopher, penelope). 0.571::husband(emilio, gina). 0.577::husband(james, victoria). 0.587::husband(marco, lucia). 0.593::husband(pierro, francesca). 0.599::husband(roberto, maria). 0.601::husband(tomaso, angela). 0.6012::husband(some_male, some_female). 0.7019::husband(james, some_female). 0.547::it_husband(andrew, christine). 0.557::it_husband(arthur, margaret). 0.563::it_husband(charles, jennifer). 0.569::it_husband(christopher, penelope). 0.571::it_husband(emilio, gina). 0.577::it_husband(james, victoria). 0.587::it_husband(marco, lucia). 0.593::it_husband(pierro, francesca). 0.599::it_husband(roberto, maria). 0.601::it_husband(tomaso, angela). 0.6012::it_husband(some_male, some_female). 0.7019::it_husband(james, some_female). 0.547::it_husband_2(andrew, christine). 0.557::it_husband_2(arthur, margaret). 0.563::it_husband_2(charles, jennifer). 0.569::it_husband_2(christopher, penelope). 0.571::it_husband_2(emilio, gina). 0.577::it_husband_2(james, victoria). 0.587::it_husband_2(marco, lucia). 0.593::it_husband_2(pierro, francesca). 0.599::it_husband_2(roberto, maria). 0.601::it_husband_2(tomaso, angela). 0.6012::it_husband_2(some_male, some_female). 0.7019::it_husband_2(james, some_female). 0.6015::wife(some_female, some_male). 0.607::wife(angela, tomaso). 0.613::wife(christine, andrew). 0.617::wife(francesca, pierro). 0.619::wife(gina, emilio). 0.631::wife(jennifer, charles). 0.641::wife(lucia, marco). 0.643::wife(maria, roberto). 0.647::wife(penelope, christopher). 0.653::wife(victoria, james). 0.701::father(andrew, james). 0.709::father(andrew, jennifer). 0.006::father(andrew, andrew). 0.719::father(christopher, arthur). 0.727::father(christopher, victoria). 0.733::father(james, charlotte). 0.739::father(james, colin). 0.743::father(marco, alfonso). 0.751::father(marco, sophia). 0.003::father(marco, marco). 0.757::father(pierro, angela). 0.761::father(pierro, marco). 0.769::father(roberto, emilio). 0.773::father(roberto, lucia). 0.787::mother(christine, jennifer). 0.797::mother(francesca, angela). 0.809::mother(francesca, marco). 0.811::mother(lucia, sophia). 0.821::mother(maria, emilio). 0.823::mother(maria, lucia). 0.827::mother(penelope, arthur). 0.829::mother(penelope, victoria). 0.839::mother(victoria, charlotte). 0.853::mother(victoria, colin). 0.859::son(alfonso, lucia). 0.863::son(alfonso, marco). 0.877::son(arthur, christopher). 0.881::son(arthur, penelope). 0.883::son(colin, james). 0.887::son(colin, victoria). 0.907::son(emilio, roberto). 0.911::son(james, andrew). 0.919::son(james, christine). 0.929::son(marco, francesca). 0.937::son(marco, pierro). 0.941::daughter(angela, pierro). 0.9415::daughter(some_female, jennifer). 0.947::daughter(charlotte, james). 0.094::daughter(jennifer, james). 0.953::daughter(charlotte, victoria). 0.967::daughter(jennifer, andrew). 0.971::daughter(jennifer, christine). 0.977::daughter(lucia, maria). 0.983::daughter(lucia, roberto). 0.991::daughter(sophia, lucia). 0.997::daughter(sophia, marco). 0.2::daughter(victoria, christopher). 0.3::daughter(victoria, penelope). 0.941::it_daughter(angela, pierro). 0.9415::it_daughter(some_female, jennifer). 0.947::it_daughter(charlotte, james). 0.094::it_daughter(jennifer, james). 0.953::it_daughter(charlotte, victoria). 0.967::it_daughter(jennifer, andrew). 0.971::it_daughter(jennifer, christine). 0.977::it_daughter(lucia, maria). 0.983::it_daughter(lucia, roberto). 0.991::it_daughter(sophia, lucia). 0.997::it_daughter(sophia, marco). 0.2::it_daughter(victoria, christopher). 0.3::it_daughter(victoria, penelope). 0.5::brother(alfonso, sophia). 0.7::brother(arthur, victoria). 0.11::brother(colin, charlotte). 0.13::brother(emilio, lucia). 0.17::brother(james, jennifer). 0.19::brother(marco, angela). 0.5853::brother(jennifer, some_female). 0.6853::brother(angela, some_female). 0.7853::brother(marco, some_female). 0.5::it_brother(alfonso, sophia). 0.7::it_brother(arthur, victoria). 0.11::it_brother(colin, charlotte). 0.13::it_brother(emilio, lucia). 0.17::it_brother(james, jennifer). 0.19::it_brother(marco, angela). 0.5853::it_brother(jennifer, some_female). 0.6853::it_brother(angela, some_female). 0.7853::it_brother(marco, some_female). 0.23::sister(angela, marco). 0.29::sister(charlotte, colin). 0.31::sister(lucia, emilio). 0.37::sister(sophia, alfonso). 0.41::sister(victoria, arthur). 0.5853::sister(some_female, jennifer). 0.6853::sister(some_female, angela). 0.7853::sister(some_female, marco). 0.23::it_sister(angela, marco). 0.29::it_sister(charlotte, colin). 0.31::it_sister(lucia, emilio). 0.37::it_sister(sophia, alfonso). 0.41::it_sister(victoria, arthur). 0.5853::it_sister(some_female, jennifer). 0.6853::it_sister(some_female, angela). 0.7853::it_sister(some_female, marco). 0.449::uncle(arthur, charlotte). 0.029::uncle(arthur, arthur). 0.049::uncle(some_male, some_female). 0.457::uncle(charles, charlotte). 0.461::uncle(charles, colin). 0.463::uncle(emilio, alfonso). 0.013::uncle(emilio, emilio). 0.467::uncle(emilio, sophia). 0.479::uncle(tomaso, alfonso). 0.487::uncle(tomaso, sophia). 0.449::it_uncle(arthur, charlotte). 0.029::it_uncle(arthur, arthur). 0.049::it_uncle(some_male, some_female). 0.457::it_uncle(charles, charlotte). 0.461::it_uncle(charles, colin). 0.463::it_uncle(emilio, alfonso). 0.013::it_uncle(emilio, emilio). 0.467::it_uncle(emilio, sophia). 0.479::it_uncle(tomaso, alfonso). 0.487::it_uncle(tomaso, sophia). 0.419::aunt(angela, alfonso). 0.421::aunt(gina, alfonso). 0.431::aunt(gina, sophia). 0.433::aunt(jennifer, charlotte). 0.0433::aunt(jennifer, some_male). 0.21::aunt(some_female, alfonso). 0.31::aunt(some_female, arthur). 0.33::aunt(some_female, charlotte). 0.439::aunt(jennifer, colin). 0.443::aunt(margaret, charlotte). 0.449::aunt(margaret, colin). 0.419::it_aunt(angela, alfonso). 0.421::it_aunt(gina, alfonso). 0.431::it_aunt(gina, sophia). 0.433::it_aunt(jennifer, charlotte). 0.0433::it_aunt(jennifer, some_male). 0.21::it_aunt(some_female, alfonso). 0.31::it_aunt(some_female, arthur). 0.33::it_aunt(some_female, charlotte). 0.439::it_aunt(jennifer, colin). 0.443::it_aunt(margaret, charlotte). 0.449::it_aunt(margaret, colin). 0.73::nephew(alfonso, angela). 0.079::nephew(alfonso, arthur). 0.083::nephew(alfonso, charlotte). 0.03::nephew(alfonso, alfonso). 0.79::nephew(alfonso, gina). 0.83::nephew(alfonso, tomaso). 0.89::nephew(colin, arthur). 0.012::nephew(colin, colin). 0.083::nephew(alfonso, tomaso). 0.089::nephew(colin, arthur). 0.97::nephew(colin, charles). 0.101::nephew(colin, jennifer). 0.103::nephew(colin, margaret). 0.107::niece(charlotte, arthur). 0.109::niece(charlotte, charles). 0.113::niece(charlotte, jennifer). 0.127::niece(charlotte, margaret). 0.0107::niece(jennifer, some_female). 0.0109::niece(lucia, some_female). 0.0149::niece(lucia, jennifer). 0.0113::niece(angela, some_female). 0.0131::niece(angela, jennifer). 0.0127::niece(charlotte, some_female). 0.131::niece(sophia, angela). 0.137::niece(sophia, emilio). 0.139::niece(sophia, gina). 0.149::niece(sophia, tomaso). 0.107::it_niece(charlotte, arthur). 0.109::it_niece(charlotte, charles). 0.113::it_niece(charlotte, jennifer). 0.127::it_niece(charlotte, margaret). 0.0107::it_niece(jennifer, some_female). 0.0109::it_niece(lucia, some_female). 0.0149::it_niece(lucia, jennifer). 0.0113::it_niece(angela, some_female). 0.0131::it_niece(angela, jennifer). 0.0127::it_niece(charlotte, some_female). 0.131::it_niece(sophia, angela). 0.137::it_niece(sophia, emilio). 0.139::it_niece(sophia, gina). 0.149::it_niece(sophia, tomaso). male_human(X) :- it_male(X). female_human(X) :- it_female(X). has_inv_height(X, Y) :- it_inv_height(X, Y). has_height(X, Y) :- it_height(X, Y). has_age(X, Y) :- it_age(X, Y). has_inv_age(X, Y) :- it_inv_age(X, Y). has_daughter(maria, Y) :- it_daughter(maria, Y). has_sister(angela, Y) :- it_sister(angela, Y). has_husband(X, victoria) :- it_husband(X, victoria). has_husband_2(X, Y) :- it_husband_2(X, Y). has_brother(X, angela) :- it_brother(X, angela). has_aunt(X, Y) :- it_aunt(X, Y). has_uncle(arthur, Y) :- it_uncle(arthur, Y). has_niece(X, gina) :- it_niece(X, gina). has_nephew(X, Y) :- nephew(X, X). #has_nephew(X, Y) :- nephew(X, Y). #human(X) :- {P}(X, Y), score(b_{P}). #human(X) :- {P}(Y, X), score(b_{P}). # for x in father mother do for y in father mother do grand_{x}(X, Y) :- {x}(X, Z), {y}(Z, Y), w(grand_{x}). done done # #grand_father(X, Y) :- father(X, Z), father(Z, Y), w(x, y).
28.89819
62
0.714632
edec6e591447474d681343414f28f75c325103f9
206
t
Perl
t/00-load.t
tlawrence3/FAST
54a7987c04fa151e1fc8657caa13423069a33743
[ "Artistic-2.0", "Unlicense" ]
32
2015-02-12T05:54:00.000Z
2021-02-17T08:09:33.000Z
t/00-load.t
tlawrence3/FAST
54a7987c04fa151e1fc8657caa13423069a33743
[ "Artistic-2.0", "Unlicense" ]
42
2015-02-12T05:53:50.000Z
2019-10-18T12:43:24.000Z
t/00-load.t
tlawrence3/FAST
54a7987c04fa151e1fc8657caa13423069a33743
[ "Artistic-2.0", "Unlicense" ]
13
2015-04-14T06:18:43.000Z
2021-10-11T07:47:52.000Z
#!perl -T use 5.006; use strict; use warnings FATAL => 'all'; use Test::More; plan tests => 1; BEGIN { use_ok( 'FAST' ) || print "Bail out!\n"; } diag( "Testing FAST $FAST::VERSION, Perl $], $^X" );
14.714286
52
0.582524
eda90458a19540b03664caea097e0f8e7a9002e6
2,835
pm
Perl
perl5/Mace/Compiler/ParseTreeObject/ParsedCatch.pm
jojochuang/eventwave
6cb3a8569f12a9127bf326be3231123428cd754d
[ "BSD-3-Clause" ]
null
null
null
perl5/Mace/Compiler/ParseTreeObject/ParsedCatch.pm
jojochuang/eventwave
6cb3a8569f12a9127bf326be3231123428cd754d
[ "BSD-3-Clause" ]
null
null
null
perl5/Mace/Compiler/ParseTreeObject/ParsedCatch.pm
jojochuang/eventwave
6cb3a8569f12a9127bf326be3231123428cd754d
[ "BSD-3-Clause" ]
null
null
null
# # ParsedCatch.pm : part of the Mace toolkit for building distributed systems # # Copyright (c) 2010, Sunghwan Yoo, Charles Killian # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the names of Duke University nor The University of # California, San Diego, nor the names of the authors or contributors # may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ----END-OF-LEGAL-STUFF---- package Mace::Compiler::ParseTreeObject::ParsedCatch; use strict; use v5.10.1; use feature 'switch'; use Class::MakeMethods::Template::Hash ( 'new' => 'new', 'scalar' => 'type', 'object' => ["parsed_var" => { class => "Mace::Compiler::ParseTreeObject::ParsedVar" }], 'object' => ["stmt_block" => { class => "Mace::Compiler::ParseTreeObject::StatementBlock" }], ); sub toString { my $this = shift; given ($this->type()) { when ("parsed_var") { return "catch (".$this->parsed_var()->toString().") {".$this->stmt_block()->toString()."}";} when ("...") { return "catch (...) {".$this->stmt_block()->toString()."}"; } default { return "ParsedCatch:NOT-PARSED"; } } } sub usedVar { my $this = shift; my @array = (); my $type = $this->type(); given ($type) { when ("parsed_var") { @array = ($this->parsed_var()->usedVar(),$this->stmt_block()->usedVar()); } when ("...") { @array = $this->stmt_block()->usedVar(); } default { @array = (); } } return @array; } 1;
38.835616
122
0.679012
edf0c11d24a9709f9535d3743a594dad51eba701
6,561
pm
Perl
apps/vmware/connector/mode/datastoresnapshot.pm
fprwi6labs/centreon-plugins
acba6cf2baa7aac02dccfff4f07b449af20a9116
[ "Apache-2.0" ]
null
null
null
apps/vmware/connector/mode/datastoresnapshot.pm
fprwi6labs/centreon-plugins
acba6cf2baa7aac02dccfff4f07b449af20a9116
[ "Apache-2.0" ]
null
null
null
apps/vmware/connector/mode/datastoresnapshot.pm
fprwi6labs/centreon-plugins
acba6cf2baa7aac02dccfff4f07b449af20a9116
[ "Apache-2.0" ]
null
null
null
# # Copyright 2019 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package apps::vmware::connector::mode::datastoresnapshot; use base qw(centreon::plugins::templates::counter); use strict; use warnings; use centreon::plugins::misc; use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold); sub custom_status_output { my ($self, %options) = @_; my $msg = 'accessible ' . $self->{result_values}->{accessible}; return $msg; } sub custom_status_calc { my ($self, %options) = @_; $self->{result_values}->{accessible} = $options{new_datas}->{$self->{instance} . '_accessible'}; return 0; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'datastore', type => 3, cb_prefix_output => 'prefix_datastore_output', cb_long_output => 'datastore_long_output', indent_long_output => ' ', message_multiple => 'All datastores are ok', group => [ { name => 'global', type => 0, skipped_code => { -10 => 1 } }, { name => 'global_snapshot', type => 0, skipped_code => { -10 => 1 } }, { name => 'files', cb_prefix_output => 'prefix_files_output', message_multiple => 'All snapshot files are ok', type => 1, skipped_code => { -10 => 1 } }, ] } ]; $self->{maps_counters}->{global} = [ { label => 'status', threshold => 0, set => { key_values => [ { name => 'accessible' } ], closure_custom_calc => $self->can('custom_status_calc'), closure_custom_output => $self->can('custom_status_output'), closure_custom_perfdata => sub { return 0; }, closure_custom_threshold_check => \&catalog_status_threshold, } }, ]; $self->{maps_counters}->{global_snapshot} = [ { label => 'total', set => { key_values => [ { name => 'total' } ], output_template => 'total snapshots [size = %s %s]', output_change_bytes => 1, perfdatas => [ { label => 'total_size', value => 'total_absolute', template => '%s', unit => 'B', min => 0, label_extra_instance => 1 }, ], } }, ]; $self->{maps_counters}->{files} = [ { label => 'snapshot', set => { key_values => [ { name => 'total' } ], output_template => '[size = %s %s]', output_change_bytes => 1, closure_custom_perfdata => sub { return 0; }, } }, ]; } sub prefix_datastore_output { my ($self, %options) = @_; return "Datastore '" . $options{instance_value}->{display} . "' : "; } sub datastore_long_output { my ($self, %options) = @_; return "checking datastore '" . $options{instance_value}->{display} . "'"; } sub prefix_files_output { my ($self, %options) = @_; return sprintf("file snapshot [%s]=>[%s] ", $options{instance_value}->{folder_path}, $options{instance_value}->{path}); } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '1.0'; $options{options}->add_options(arguments => { "datastore-name:s" => { name => 'datastore_name' }, "filter" => { name => 'filter' }, "scope-datacenter:s" => { name => 'scope_datacenter' }, "unknown-status:s" => { name => 'unknown_status', default => '%{accessible} !~ /^true|1$/i' }, "warning-status:s" => { name => 'warning_status', default => '' }, "critical-status:s" => { name => 'critical_status', default => '' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); $self->change_macros(macros => ['unknown_status', 'warning_status', 'critical_status']); } sub manage_selection { my ($self, %options) = @_; $self->{datastore} = {}; my $response = $options{custom}->execute(params => $self->{option_results}, command => 'datastoresnapshot'); my $i = 0; foreach my $ds_id (keys %{$response->{data}}) { my $ds_name = $response->{data}->{$ds_id}->{name}; $self->{datastore}->{$ds_name} = { display => $ds_name, files => {}, global => { accessible => $response->{data}->{$ds_id}->{accessible}, }, global_snapshot => { total => 0 }, }; foreach (@{$response->{data}->{$ds_id}->{snapshost}}) { $self->{datastore}->{$ds_name}->{files}->{$i} = { folder_path => $_->{folder_path}, path => $_->{path}, total => $_->{size}, }; $self->{datastore}->{$ds_name}->{global_snapshot}->{total} += $_->{size}; $i++; } } } 1; __END__ =head1 MODE Check snapshots usage on datastores. =over 8 =item B<--datastore-name> datastore name to list. =item B<--filter> Datastore name is a regexp. =item B<--scope-datacenter> Search in following datacenter(s) (can be a regexp). =item B<--unknown-status> Set warning threshold for status (Default: '%{accessible} !~ /^true|1$/i'). Can used special variables like: %{accessible} =item B<--warning-status> Set warning threshold for status (Default: ''). Can used special variables like: %{accessible} =item B<--critical-status> Set critical threshold for status (Default: ''). Can used special variables like: %{accessible} =item B<--warning-*> Threshold warning. Can be: 'total', 'snapshot'. =item B<--critical-*> Threshold critical. Can be: 'total', 'snapshot'. =back =cut
30.235023
207
0.565463
eddde694eb8f016c68214171c9cd52c4d00a0603
2,022
pm
Perl
lib/Chart/Plotly/Trace/Box/Selected.pm
hstejas/p5-Chart-Plotly
c1666613369ff44d0ec984935b02b4024638aacf
[ "MIT" ]
11
2017-01-08T12:08:24.000Z
2021-12-14T15:27:56.000Z
lib/Chart/Plotly/Trace/Box/Selected.pm
hstejas/p5-Chart-Plotly
c1666613369ff44d0ec984935b02b4024638aacf
[ "MIT" ]
28
2016-11-21T20:25:21.000Z
2021-04-20T16:58:38.000Z
lib/Chart/Plotly/Trace/Box/Selected.pm
hstejas/p5-Chart-Plotly
c1666613369ff44d0ec984935b02b4024638aacf
[ "MIT" ]
3
2016-12-14T15:59:41.000Z
2020-07-30T04:39:43.000Z
package Chart::Plotly::Trace::Box::Selected; use Moose; use MooseX::ExtraArgs; use Moose::Util::TypeConstraints qw(enum union); if (!defined Moose::Util::TypeConstraints::find_type_constraint('PDL')) { Moose::Util::TypeConstraints::type('PDL'); } use Chart::Plotly::Trace::Box::Selected::Marker; # VERSION # ABSTRACT: This attribute is one of the possible options for the trace box. =encoding utf-8 =head1 SYNOPSIS # EXAMPLE: examples/traces/box.pl =head1 DESCRIPTION This attribute is part of the possible options for the trace box. This file has been autogenerated from the official plotly.js source. If you like Plotly, please support them: L<https://plot.ly/> Open source announcement: L<https://plot.ly/javascript/open-source-announcement/> Full reference: L<https://plot.ly/javascript/reference/#box> =head1 DISCLAIMER This is an unofficial Plotly Perl module. Currently I'm not affiliated in any way with Plotly. But I think plotly.js is a great library and I want to use it with perl. =head1 METHODS =cut =head2 TO_JSON Serialize the trace to JSON. This method should be called only by L<JSON> serializer. =cut sub TO_JSON { my $self = shift; my $extra_args = $self->extra_args // {}; my $meta = $self->meta; my %hash = %$self; for my $name (sort keys %hash) { my $attr = $meta->get_attribute($name); if (defined $attr) { my $value = $hash{$name}; my $type = $attr->type_constraint; if ($type && $type->equals('Bool')) { $hash{$name} = $value ? \1 : \ 0; } } } %hash = (%hash, %$extra_args); delete $hash{'extra_args'}; if ($self->can('type') && (!defined $hash{'type'})) { $hash{type} = $self->type(); } return \%hash; } =head1 ATTRIBUTES =over =cut =item * marker =cut has marker => ( is => "rw", isa => "Maybe[HashRef]|Chart::Plotly::Trace::Box::Selected::Marker", ); =pod =back =cut __PACKAGE__->meta->make_immutable(); 1;
21.0625
95
0.643422
edf3ebc607a8e98b1ca86d6cee04e1824be3e81f
1,853
pm
Perl
lib/EpitopeDB/sample.pm
MullinsLab/viroverse
fca0c5f81ce9d5fdcef96d661def0699ba4209cb
[ "MIT" ]
7
2019-02-04T20:37:19.000Z
2020-10-07T18:23:09.000Z
lib/EpitopeDB/sample.pm
MullinsLab/viroverse
fca0c5f81ce9d5fdcef96d661def0699ba4209cb
[ "MIT" ]
75
2019-03-07T20:44:04.000Z
2020-01-22T11:27:03.000Z
lib/EpitopeDB/sample.pm
MullinsLab/viroverse
fca0c5f81ce9d5fdcef96d661def0699ba4209cb
[ "MIT" ]
null
null
null
package EpitopeDB::sample; use base qw/DBIx::Class/; # Load required DBIC stuff __PACKAGE__->load_components(qw/PK::Auto Core/); # Set the table name __PACKAGE__->table('epitope.sample'); # Set columns in table __PACKAGE__->add_column( qw/ sample_id tissue sample_date patient patient_id / ); # Set the primary key for the table __PACKAGE__->set_primary_key(qw/sample_id/); __PACKAGE__->has_many(pept_responses => 'EpitopeDB::pept_response', 'sample_id'); __PACKAGE__->has_many(pept_response_corravgs => 'EpitopeDB::pept_response_corravg', 'sample_id'); __PACKAGE__->has_many(titrations => 'EpitopeDB::titration', 'sample_id'); __PACKAGE__->has_many(titration_corravgs => 'EpitopeDB::titration_corravg', 'sample_id'); __PACKAGE__->has_many(hla_responses => 'EpitopeDB::hla_response', 'sample_id'); __PACKAGE__->has_many(hla_response_corravgs => 'EpitopeDB::hla_response_corravg', 'sample_id'); # one to manay relationship between sample and pool_response __PACKAGE__->has_many(pool_response => 'EpitopeDB::pool_response', 'sample_id'); # one to manay relationship between sample and pool_response_corravg __PACKAGE__->has_many(pool_response_corravg => 'EpitopeDB::pool_response_corravg', 'sample_id'); __PACKAGE__->has_many(epitope_mutants => 'EpitopeDB::epitope_mutant', {'foreign.patient_id' => 'self.patient_id'}); __PACKAGE__->belongs_to(test_patient => 'EpitopeDB::test_patient', {'foreign.patient_id' => 'self.patient_id'}); =head1 NAME EpitopeDB::hla - A model object representing a hla type. =head1 DESCRIPTION This is an object that represents a row in the 'gene' table of viroverse database. It uses DBIx::Class (aka, DBIC) to do ORM. For Catalyst, this is designed to be used through Viroverse::Model::EpitopeDB. offline utilities may wish to use this class directly. =cut 1;
33.690909
115
0.756611
edbf22419c6516a2b838fbf209ef4002af9612ef
353
pm
Perl
auto-lib/Paws/Chime/CreateBotResponse.pm
0leksii/aws-sdk-perl
b2132fe3c79a06fd15b6137e8a0eb628de722e0f
[ "Apache-2.0" ]
164
2015-01-08T14:58:53.000Z
2022-02-20T19:16:24.000Z
auto-lib/Paws/Chime/CreateBotResponse.pm
0leksii/aws-sdk-perl
b2132fe3c79a06fd15b6137e8a0eb628de722e0f
[ "Apache-2.0" ]
348
2015-01-07T22:08:38.000Z
2022-01-27T14:34:44.000Z
auto-lib/Paws/Chime/CreateBotResponse.pm
0leksii/aws-sdk-perl
b2132fe3c79a06fd15b6137e8a0eb628de722e0f
[ "Apache-2.0" ]
87
2015-04-22T06:29:47.000Z
2021-09-29T14:45:55.000Z
package Paws::Chime::CreateBotResponse; use Moose; has Bot => (is => 'ro', isa => 'Paws::Chime::Bot'); has _request_id => (is => 'ro', isa => 'Str'); 1; ### main pod documentation begin ### =head1 NAME Paws::Chime::CreateBotResponse =head1 ATTRIBUTES =head2 Bot => L<Paws::Chime::Bot> The bot details. =head2 _request_id => Str =cut
12.607143
53
0.628895
ed3ba1d3844791a1e655adb0ec45a9740e2f109d
4,023
pm
Perl
core/server/OpenXPKI/Server/Authentication/ChallengeX509.pm
aleibl/openxpki
ea27c1c8280a152eef7f4437e489e61575742094
[ "Apache-2.0" ]
null
null
null
core/server/OpenXPKI/Server/Authentication/ChallengeX509.pm
aleibl/openxpki
ea27c1c8280a152eef7f4437e489e61575742094
[ "Apache-2.0" ]
null
null
null
core/server/OpenXPKI/Server/Authentication/ChallengeX509.pm
aleibl/openxpki
ea27c1c8280a152eef7f4437e489e61575742094
[ "Apache-2.0" ]
null
null
null
## OpenXPKI::Server::Authentication::ChallengeX509 ## ## Rewritten 2013 by Oliver Welter for the OpenXPKI Project ## (C) Copyright 2013 by The OpenXPKI Project package OpenXPKI::Server::Authentication::ChallengeX509; use strict; use warnings; use English; use OpenXPKI::Debug; use OpenXPKI::Exception; use OpenXPKI::Server::Context qw( CTX ); use OpenXPKI::Crypto::X509; use MIME::Base64; use Moose; extends 'OpenXPKI::Server::Authentication::X509'; use Data::Dumper; sub login_step { ##! 1: 'start' my $self = shift; my $arg_ref = shift; my $name = $arg_ref->{HANDLER}; my $msg = $arg_ref->{MESSAGE}; if (! exists $msg->{PARAMS}->{CHALLENGE} || ! exists $msg->{PARAMS}->{SIGNATURE}) { ##! 4: 'no login data received (yet)' # The challenge is just the session ID, so we do not have to # remember the challenge (which could only be done in the # session anyways as people might talk to different servers # in different login steps) ... my $challenge = CTX('session')->data->id; ##! 64: 'challenge: ' . $challenge # save the pending challenge to check later that we # received a valid challenge return (undef, undef, { SERVICE_MSG => "GET_X509_LOGIN", PARAMS => { NAME => $self->{NAME}, DESCRIPTION => $self->{DESC}, CHALLENGE => $challenge, }, }, ); } ##! 2: 'login data / signature received' my $challenge = $msg->{PARAMS}->{CHALLENGE}; my $signature = $msg->{PARAMS}->{SIGNATURE}; my $pki_realm = CTX('session')->data->pki_realm; if ($signature !~ m{ \A .* \n \z }xms) { # signature does not end with \n, add it $signature .= "\n"; } ##! 64: 'challenge: ' . $challenge ##! 64: 'signature: ' . $signature if ($challenge ne CTX('session')->data->id) { # the sent challenge is not for this session ID OpenXPKI::Exception->throw( message => 'I18N_OPENXPKI_SERVER_AUTHENTICATION_X509_CHALLENGE_DOES_NOT_MATCH_SESSION_ID', params => { CHALLENGE => $challenge, SESSION_ID => CTX('session')->data->id, }, ); } if (! $signature =~ m{ \A [a-zA-Z\+/=]+ \z }xms) { # the sent signature is not in Base64 format OpenXPKI::Exception->throw( message => 'I18N_OPENXPKI_SERVER_AUTHENTICATION_X509_SIGNATURE_IS_NOT_BASE64', ); } my $pkcs7 = '-----BEGIN PKCS7-----' . "\n" . $signature . '-----END PKCS7-----'; my $default_token = CTX('crypto_layer')->get_system_token({ TYPE => "DEFAULT" }); ##! 64: ' Signature blob: ' . $pkcs7 ##! 64: ' Challenge: ' . $challenge eval { # FIXME - this needs testing $default_token->command({ COMMAND => 'pkcs7_verify', NO_CHAIN => 1, PKCS7 => $pkcs7, CONTENT => $challenge, }); }; if ($EVAL_ERROR) { OpenXPKI::Exception->throw( message => 'I18N_OPENXPKI_SERVER_AUTHENTICATION_X509_INVALID_SIGNATURE', ); } ##! 16: 'signature valid' # Looks like firefox adds \r to the p7 $pkcs7 =~ s/\r//g; my $validate = CTX('api')->validate_certificate({ PKCS7 => $pkcs7, ANCHOR => $self->trust_anchors(), }); return $self->_validation_result( $validate ); } 1; __END__ =head1 Name OpenXPKI::Server::Authentication::ChallengeX509 - certificate based authentication. =head1 Description Send the user a challenge to be signed by the browser. Requires a supported browser. See OpenXPKI::Server::Authentication::X509 for configuration options.
29.580882
106
0.543376
ede7cc9721bf91c569681b614b85d529a691cfbf
2,140
pm
Perl
lib/NewsExtractor.pm
perltaiwan/NewsExtractor
58589d68af55665055ba5ac68e18ffc72b41b05b
[ "CC0-1.0" ]
1
2020-10-22T03:48:53.000Z
2020-10-22T03:48:53.000Z
lib/NewsExtractor.pm
perltaiwan/NewsExtractor
58589d68af55665055ba5ac68e18ffc72b41b05b
[ "CC0-1.0" ]
null
null
null
lib/NewsExtractor.pm
perltaiwan/NewsExtractor
58589d68af55665055ba5ac68e18ffc72b41b05b
[ "CC0-1.0" ]
1
2020-02-06T03:39:42.000Z
2020-02-06T03:39:42.000Z
package NewsExtractor; our $VERSION = v0.44.0; use Moo; use Mojo::UserAgent; use Mojo::UserAgent::Transactor; use Try::Tiny; use Types::Standard qw< Str >; use Types::URI qw< Uri >; use Importer 'NewsExtractor::TextUtil' => qw(u); use NewsExtractor::Error; use NewsExtractor::Download; has url => ( required => 1, is => 'ro', isa => Uri, coerce => 1 ); has user_agent_string => ( required => 1, is => 'ro', isa => Str, default => sub { 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:93.0) Gecko/20100101 Firefox/93.0' } ); sub download { my NewsExtractor $self = shift; my $ua = Mojo::UserAgent->new()->transactor( Mojo::UserAgent::Transactor->new()->name( $self->user_agent_string ) )->max_redirects(3); my ($error, $download); my $tx = $ua->get( "". $self->url ); my $res; try { $res = $tx->result } catch { $error = NewsExtractor::Error->new( is_exception => 0, message => u($_), ) }; if ($res) { if ($res->is_error) { $error = NewsExtractor::Error->new( is_exception => 0, message => u($res->message), ); } else { $download = NewsExtractor::Download->new( tx => $tx ); } } return ($error, $download); } 1; __END__ =head1 NAME NewsExtractor - download and extract news articles from Internet. =head1 SYNOPSIS my ($error, $article) = NewsExtractor->new( url => $url )->download->parse; die $error if $error; # $article is an instance of NewsExtractor::Article say "Headline: " . $article->headline; say "When: " . ($article->dateline // "(unknown)"); say "By: " . ($article->journalist // "(unknown)"); say "\n" . $article->article_body; =head1 SEE Also L<NewsExtractor::Article> =head1 AUTHOR Kang-min Liu <gugod@gugod.org> =head1 LICENSE To the extent possible under law, Kang-min Liu has waived all copyright and related or neighboring rights to NewsExtractor. This work is published from: Taiwan. https://creativecommons.org/publicdomain/zero/1.0/ =cut
22.526316
160
0.593458
ede58a93ca94f77c9738b5b0bdcacf0e4c2a0a87
681
t
Perl
t/external/08_external.t
Grinnz/p5-net-ssleay
6907f9027ba343d2299ab249dec856c63c5eef12
[ "Artistic-2.0" ]
null
null
null
t/external/08_external.t
Grinnz/p5-net-ssleay
6907f9027ba343d2299ab249dec856c63c5eef12
[ "Artistic-2.0" ]
null
null
null
t/external/08_external.t
Grinnz/p5-net-ssleay
6907f9027ba343d2299ab249dec856c63c5eef12
[ "Artistic-2.0" ]
null
null
null
#!/usr/bin/perl # Test complete connection a number of external SSL web servers use strict; use warnings; use Test::More; use Net::SSLeay; my @sites = qw( www.google.com www.microsoft.com www.kernel.org ); @sites = split(/:/, $ENV{SSLEAY_SITES}) if exists $ENV{SSLEAY_SITES}; if (@sites) { plan tests => scalar @sites * 2; } else { plan skip_all => 'No external hosts specified for SSL testing'; } my $site; for $site (@sites) { SKIP: { my ($p, $r, %h) = Net::SSLeay::get_https($site, 443, '/'); skip 'could not connect', 2 unless defined $h{'CONTENT-TYPE'}; pass('connection'); ok($r =~ /^HTTP\/1/s, 'correct response'); } }
21.967742
70
0.612335
edb0bf9f55196735a15a2dd36f810bf831eff5a6
18,778
pm
Perl
perl/vendor/lib/PPM/XML/PPD.pm
mnikolop/Thesis_project_CyberDoc
9a37fdd5a31de24cb902ee31ef19eb992faa1665
[ "Apache-2.0" ]
4
2018-04-20T07:27:13.000Z
2021-12-21T05:19:24.000Z
perl/vendor/lib/PPM/XML/PPD.pm
mnikolop/Thesis_project_CyberDoc
9a37fdd5a31de24cb902ee31ef19eb992faa1665
[ "Apache-2.0" ]
6
2021-11-18T00:39:48.000Z
2021-11-20T00:31:40.000Z
perl/vendor/lib/PPM/XML/PPD.pm
mnikolop/Thesis_project_CyberDoc
9a37fdd5a31de24cb902ee31ef19eb992faa1665
[ "Apache-2.0" ]
1
2019-11-12T02:29:26.000Z
2019-11-12T02:29:26.000Z
# # PPM::XML::PPD # # Definition of the PPD file format. # ############################################################################### use PPM::XML::ValidatingElement; use Exporter; ############################################################################### # Set up PPM::XML::PPD to export its sub-packages so that we can use them in # other XML documents without too much effort. ############################################################################### package PPM::XML::PPD; @ISA = qw( Exporter ); %EXPORT_TAGS = ( 'elements' => [ '%SOFTPKG::', '%IMPLEMENTATION::', '%DEPENDENCY::', '%TITLE::', '%ABSTRACT::', '%AUTHOR::', '%LANGUAGE::', '%LICENSE::', '%OS::', '%OSVERSION::', '%PERLCORE::', '%PROCESSOR::', '%CODEBASE::', '%INSTALL::', '%UNINSTALL::', '%ARCHITECTURE::', '%PROVIDE::', '%REQUIRE::', ] ); Exporter::export_ok_tags( 'elements' ); ############################################################################### # PPD Element: SOFTPKG ############################################################################### package PPM::XML::PPD::SOFTPKG; @ISA = qw( PPM::XML::ValidatingElement ); @oattrs = qw( VERSION ); @rattrs = qw( NAME ); @okids = qw( ABSTRACT AUTHOR IMPLEMENTATION LICENSE TITLE INSTALL UNINSTALL PROVIDE REQUIRE); ############################################################################### # PPD Element: TITLE ############################################################################### package PPM::XML::PPD::TITLE; @ISA = qw( PPM::XML::ValidatingElement ); ############################################################################### # PPD Element: ABSTRACT ############################################################################### package PPM::XML::PPD::ABSTRACT; @ISA = qw( PPM::XML::ValidatingElement ); ############################################################################### # PPD Element: AUTHOR ############################################################################### package PPM::XML::PPD::AUTHOR; @ISA = qw( PPM::XML::ValidatingElement ); ############################################################################### # PPD Element: PROVIDE ############################################################################### package PPM::XML::PPD::PROVIDE; @ISA = qw( PPM::XML::ValidatingElement ); @oattrs = qw( VERSION ); @rattrs = qw( NAME ); ############################################################################### # PPD Element: REQUIRE ############################################################################### package PPM::XML::PPD::REQUIRE; @ISA = qw( PPM::XML::ValidatingElement ); @oattrs = qw( VERSION ); @rattrs = qw( NAME ); ############################################################################### # PPD Element: LICENSE ############################################################################### package PPM::XML::PPD::LICENSE; @ISA = qw( PPM::XML::ValidatingElement ); @rattrs = qw( HREF ); ############################################################################### # PPD Element: IMPLEMENTATION ############################################################################### package PPM::XML::PPD::IMPLEMENTATION; @ISA = qw( PPM::XML::ValidatingElement ); @okids = qw( DEPENDENCY INSTALL LANGUAGE OS OSVERSION PERLCORE PROCESSOR UNINSTALL ARCHITECTURE PROVIDE REQUIRE); @rkids = qw( CODEBASE ); ############################################################################### # PPD Element: OS ############################################################################### package PPM::XML::PPD::OS; @ISA = qw( PPM::XML::ValidatingElement ); @rattrs = qw( VALUE ); sub validate_possible_attrs { my $self = shift; $self->compatibility_check(); $self->SUPER::validate_possible_attrs( @_ ); } sub validate_required_attrs { my $self = shift; $self->compatibility_check(); $self->SUPER::validate_required_attrs( @_ ); } sub compatibility_check { my $self = shift; if (exists $self->{NAME}) { $self->{VALUE} = $self->{NAME}; delete $self->{NAME}; } } ############################################################################### # PPD Element: OSVERSION ############################################################################### package PPM::XML::PPD::OSVERSION; @ISA = qw( PPM::XML::ValidatingElement ); @rattrs = qw( VALUE ); sub validate_possible_attrs { my $self = shift; $self->compatibility_check(); $self->SUPER::validate_possible_attrs( @_ ); } sub validate_required_attrs { my $self = shift; $self->compatibility_check(); $self->SUPER::validate_required_attrs( @_ ); } sub compatibility_check { my $self = shift; if (exists $self->{NAME}) { $self->{VALUE} = $self->{NAME}; delete $self->{NAME}; } } ############################################################################### # PPD Element: PROCESSOR ############################################################################### package PPM::XML::PPD::PROCESSOR; @ISA = qw( PPM::XML::ValidatingElement ); @rattrs = qw( VALUE ); sub validate_possible_attrs { my $self = shift; $self->compatibility_check(); $self->SUPER::validate_possible_attrs( @_ ); } sub validate_required_attrs { my $self = shift; $self->compatibility_check(); $self->SUPER::validate_required_attrs( @_ ); } sub compatibility_check { my $self = shift; if (exists $self->{NAME}) { $self->{VALUE} = $self->{NAME}; delete $self->{NAME}; } } ############################################################################### # PPD Element: ARCHITECTURE ############################################################################### package PPM::XML::PPD::ARCHITECTURE; @ISA = qw( PPM::XML::ValidatingElement ); @rattrs = qw( VALUE ); sub validate_possible_attrs { my $self = shift; $self->compatibility_check(); $self->SUPER::validate_possible_attrs( @_ ); } sub validate_required_attrs { my $self = shift; $self->compatibility_check(); $self->SUPER::validate_required_attrs( @_ ); } sub compatibility_check { my $self = shift; if (exists $self->{NAME}) { $self->{VALUE} = $self->{NAME}; delete $self->{NAME}; } } ############################################################################### # PPD Element: CODEBASE ############################################################################### package PPM::XML::PPD::CODEBASE; @ISA = qw( PPM::XML::ValidatingElement ); @oattrs = qw( FILENAME ); @rattrs = qw( HREF ); ############################################################################### # PPD Element: DEPENDENCY ############################################################################### package PPM::XML::PPD::DEPENDENCY; @ISA = qw( PPM::XML::ValidatingElement ); @rattrs = qw( NAME ); @oattrs = qw( VERSION ); ############################################################################### # PPD Element: LANGUAGE ############################################################################### package PPM::XML::PPD::LANGUAGE; @ISA = qw( PPM::XML::ValidatingElement ); @rattrs = qw( VALUE ); ############################################################################### # PPD Element: PERLCORE ############################################################################### package PPM::XML::PPD::PERLCORE; @ISA = qw( PPM::XML::ValidatingElement ); @rattrs = qw( VERSION ); ############################################################################### # PPD Element: INSTALL ############################################################################### package PPM::XML::PPD::INSTALL; @ISA = qw( PPM::XML::ValidatingElement ); @oattrs = qw( HREF EXEC ); ############################################################################### # PPD Element: UNINSTALL ############################################################################### package PPM::XML::PPD::UNINSTALL; @ISA = qw( PPM::XML::ValidatingElement ); @oattrs = qw( HREF EXEC ); __END__ ############################################################################### # POD ############################################################################### =head1 NAME PPM::XML::PPD - PPD file format and XML parsing elements =head1 SYNOPSIS use XML::Parser; use PPM::XML::PPD; $p = new PPM::XML::Parser( Style => 'Objects', Pkg => 'PPM::XML::PPD' ); ... =head1 DESCRIPTION This module provides a set of classes for parsing PPD files using the C<XML::Parser> module. Each of the classes is derived from C<PPM::XML::ValidatingElement>, with optional/required attributes/children enforced. =head1 MAJOR ELEMENTS =head2 SOFTPKG Defines a Perl Package. The root of a PPD document is B<always> a SOFTPKG element. The SOFTPKG element allows for the following attributes: =over 4 =item NAME Required attribute. Name of the package (e.g. "Foobar"). =item VERSION Version number of the package, in comma-delimited format (e.g. "1,0,0,0"). =back =head2 IMPLEMENTATION Child of SOFTPKG, used to describe a particular implementation of the Perl Package. Multiple instances are valid, and should be used to describe different implementations/ports for different operating systems or architectures. =head2 DEPENDENCY Child of SOFTPKG or IMPLEMENTATION, used to indicate a dependency this Perl Package has on another Perl Package. Multiple instances are valid. The DEPENDENCY element allows for the following attributes: =over 4 =item NAME Name of the package that this implementation is dependant upon. =item VERSION Version number of the dependency, in comma-delimited format (e.g. "1,0,0,0"). =back =head1 MINOR ELEMENTS =head2 TITLE Child of SOFTPKG, used to state the title of the Perl Package. Only one instance should be present. =head2 ABSTRACT Child of SOFTPKG, used to provide a short description outlining the nature and purpose of the Perl Package. Only one instance should be present. =head2 AUTHOR Child of SOFTPKG, used to provide information about the author(s) of the Perl Package. Multiple instances are valid. =head2 LANGUAGE Child of IMPLEMENTATION, used to specify the language used within the given implementation of the Perl Package. Only one instance should be present. =head2 LICENSE Child of SOFTPKG, indicating the location of the appropriate license agreement or copyright notice for the Perl Package. Only one instance should be present. The LICENSE element allows for the following attributes: =over 4 =item HREF Required attribute. A reference to the location of the license agreement or copyright notice for this package. =back =head2 OS Child of IMPLEMENTATION, used to outline the operating system required for this implementation of the Perl Package. Multiple instances are valid. Valid values can be taken from the OSD Specification and it's OS element. The OS element allows for the following attributes: =over 4 =item VALUE The name of the operating system required for this implementation of the Perl Package. This value should be obtained from Config.pm as 'osname'. =back Note that previous versions of the PPD format used a 'NAME' attribute. It's use has been deprecated in preference of the 'VALUE' attribute. Also note that during validation, this element will automatically convert any existing 'NAME' attribute to be a 'VALUE' attribute. =head2 OSVERSION Child of IMPLEMENTATION, used to outline the required version of the operating system required for this implementation of the Perl Package. Only one instance should be present. The OSVERSION element allows for the following attributes: =over 4 =item VALUE The version of the operating system required for installation of this implementation of the package, in a comma-delimited format (e.g. "3,1,0,0"). =back Note that previous versions of the PPD format used a 'NAME' attribute. It's use has been deprecated in preference of the 'VALUE' attribute. Also note that during validation, this element will automatically convert any existing 'NAME' attribute to be a 'VALUE' attribute. =head2 PERLCORE Child of IMPLEMENTATION, used to specify the minimum version of the Perl core distribution that this Perl Package is to be used with. Only one instance should be present. The PERLCORE element allows for the following attributes: =over 4 =item VERSION Version of the Perl core that is required for this implementation of the Perl Package. =back =head2 PROCESSOR Child of IMPLEMENTATION, outlining the cpu required for this implementation of the Perl Package. Only one instance should be present. The PROCESSOR element allows for the following attributes: =over 4 =item VALUE CPU required for the installation of this implementation of the Perl Package. The following values are all valid according to the OSD Specification: x86 alpha mips sparc 680x0 =back Note that previous versions of the PPD format used a 'NAME' attribute. It's use has been deprecated in preference of the 'VALUE' attribute. Also note that during validation, this element will automatically convert any existing 'NAME' attribute to be a 'VALUE' attribute. =head2 CODEBASE Child of IMPLEMENTATION, indicating a location where an archive of the Perl Package can be retrieved. Multiple instances are valid, and can be used to indicate multiple possible locations where the same version of the Perl Package can be retrieved. The CODEBASE element allows for the following attributes: =over 4 =item FILENAME ??? =item HREF Required attribute. A reference to the location of the Perl Package distribution. =back =head2 INSTALL Child of IMPLEMENTATION, used to provide either a reference to an installation script or a series of commands which can be used to install the Perl Package once it has been retrieved. If the EXEC attribute is not specified, the value is assumed to be one or more commands, separated by `;;'. Each such command will be executed by the Perl `system()' function. Only one instance should be present. The INSTALL element allows for the following attributes: =over 4 =item HREF Reference to an external script which should be retrieved and run as part of the installation process. Both filenames and URLs should be considered valid. =item EXEC Name of interpreter/shell used to execute the installation script. If the value of EXEC is `PPM_PERL', the copy of Perl that is executing PPM itself ($^X) is used to execute the install script. =back =head2 UNINSTALL Child of IMPLEMENTATION, used to provide either a reference to an uninstallation script or a raw Perl script which can be used to uninstall the Perl Package at a later point. Only one instance should be present. The UNINSTALL element allows for the following attributs: =over 4 =item HREF Reference to an external script which should be retrieved and run as part of the removal process. Both filenames and URLs should be considered valid. =item EXEC Name of interpreter/shell used to execute the uninstallation script. If the value of EXEC is `PPM_PERL', the copy of Perl that is executing PPM itself ($^X) is used to execute the install script. =back =head1 DOCUMENT TYPE DEFINITION The DTD for PPD documents is available from the ActiveState website and the latest version can be found at http://www.ActiveState.com/PPM/DTD/ppd.dtd This revision of the C<PPM::XML::PPD> module implements the following DTD: <!ELEMENT SOFTPKG (ABSTRACT | AUTHOR | IMPLEMENTATION | LICENSE | TITLE)*> <!ATTLIST SOFTPKG NAME CDATA #REQUIRED VERSION CDATA #IMPLIED> <!ELEMENT TITLE (#PCDATA)> <!ELEMENT ABSTRACT (#PCDATA)> <!ELEMENT AUTHOR (#PCDATA)> <!ELEMENT LICENSE EMPTY> <!ATTLIST LICENSE HREF CDATA #REQUIRED> <!ELEMENT IMPLEMENTATION (CODEBASE | DEPENDENCY | LANGUAGE | OS | OSVERSION | PERLCORE | PROCESSOR | INSTALL | UNINSTALL) *> <!ELEMENT CODEBASE EMPTY> <!ATTLIST CODEBASE FILENAME CDATA #IMPLIED HREF CDATA #REQUIRED> <!ELEMENT DEPENDENCY EMPTY> <!ATTLIST DEPENDENCY VERSION CDATA #IMPLIED NAME CDATA #REQUIRED> <!ELEMENT LANGUAGE EMPTY> <!ATTLIST LANGUAGE VALUE CDATA #REQUIRED> <!ELEMENT OS EMPTY> <!ATTLIST OS VALUE CDATA #REQUIRED> <!ELEMENT OSVERSION EMPTY> <!ATTLIST OSVERSION VALUE CDATA #REQUIRED> <!ELEMENT PERLCORE EMPTY> <!ATTLIST PERLCORE VERSION CDATA #REQUIRED> <!ELEMENT PROCESSOR EMPTY> <!ATTLIST PROCESSOR VALUE CDATA #REQUIRED> <!ELEMENT INSTALL (#PCDATA)> <!ATTLIST INSTALL HREF CDATA #IMPLIED EXEC CDATA #IMPLIED> <!ELEMENT UNINSTALL (#PCDATA)> <!ATTLIST UNINSTALL HREF CDATA #IMPLIED EXEC CDATA #IMPLIED> =head1 SAMPLE PPD FILE The following is a sample PPD file describing the C<Math-MatrixBool> module. Note that this may B<not> be a current/proper description of this module and is for sample purposes only. <SOFTPKG NAME="Math-MatrixBool" VERSION="4,2,0,0"> <TITLE>Math-MatrixBool</TITLE> <ABSTRACT>Easy manipulation of matrices of booleans (Boolean Algebra)</ABSTRACT> <AUTHOR>Steffen Beyer (sb@sdm.de)</AUTHOR> <LICENSE HREF="http://www.ActiveState.com/packages/Math-MatrixBool/license.html" /> <IMPLEMENTATION> <OS VALUE="WinNT" /> <OS VALUE="Win95" /> <PROCESSOR VALUE="x86" /> <CODEBASE HREF="http://www.ActiveState.com/packages/Math-MatrixBool/Math-MatrixBool-4.2-bin-1-Win32.tar.gz" /> <DEPENDENCY NAME="Bit-Vector" /> <INSTALL> </INSTALL> <UNINSTALL> </UNINSTALL> </IMPLEMENTATION> <IMPLEMENTATION> <DEPENDENCY NAME="Bit-Vector" /> <CODEBASE HREF="&CPAN;/CPAN/modules/by-module/Math/Math-MatrixBool-4.2.tar.gz" /> <INSTALL> system("make"); ;; system("make test"); ;; system("make install"); ;; </INSTALL> </IMPLEMENTATION> </SOFTPKG> =head1 KNOWN BUGS/ISSUES Elements which are required to be empty (e.g. LICENSE) are not enforced as such. Notations above about elements for which "only one instance" or "multiple instances" are valid are not enforced; this primarily a guideline for generating your own PPD files. =head1 AUTHORS Graham TerMarsch <grahamt@ActiveState.com> Murray Nesbitt <murrayn@ActiveState.com> Dick Hardt <dick_hardt@ActiveState.com> =head1 HISTORY v0.1 - Initial release =head1 SEE ALSO L<PPM::XML::ValidatingElement>, L<PPM::XML::Element>, L<XML::Parser>, OSD Specification (http://www.microsoft.com/standards/osd/) =cut
30.238325
119
0.581532
edc00fbc207a0e90f67bfe7396c1126304a2bb19
31,640
pm
Perl
lib/Quiq/FFmpeg.pm
s31tz/Quiq
6a65f1a00739d57275db6c11593722ebadd01036
[ "Artistic-1.0-Perl" ]
null
null
null
lib/Quiq/FFmpeg.pm
s31tz/Quiq
6a65f1a00739d57275db6c11593722ebadd01036
[ "Artistic-1.0-Perl" ]
2
2019-05-04T13:48:16.000Z
2019-08-27T21:39:45.000Z
lib/Quiq/FFmpeg.pm
s31tz/Quiq
6a65f1a00739d57275db6c11593722ebadd01036
[ "Artistic-1.0-Perl" ]
2
2019-02-02T12:04:19.000Z
2019-08-27T19:25:23.000Z
package Quiq::FFmpeg; use base qw/Quiq::Hash/; use v5.10; use strict; use warnings; our $VERSION = '1.196'; use Quiq::File::Video; use POSIX (); use Quiq::Option; use Quiq::Duration; use Quiq::FileHandle; # ----------------------------------------------------------------------------- =encoding utf8 =head1 NAME Quiq::FFmpeg - Konstruiere eine FFmpeg-Kommandozeile =head1 BASE CLASS L<Quiq::Hash> =head1 DESCRIPTION FFmpg Online-Dokumentation: L<https://www.ffmpeg.org/ffmpeg-all.html> Ein Objekt der Klasse repräsentiert eine ffmpeg-Kommandozeile. Die Klasse verfügt einerseits über I<elementare> (Objekt-)Methoden, um eine solche Kommandozeile sukzessive aus Eingabe- und Ausgabe-Dateien, Optionen, Filtern usw. zu konstruieren und andererseits I<höhere> (Klassen-)Methoden, die eine vollständige Kommandozeile zur Erfüllung eines bestimmten Zwecks unter Rückgriff auf die elementaren Methoden erstellen. Die höheren Methoden Methoden befinden sich im Abschnitt L<Klassenmethoden (vollständige Kommandozeilen)|"Klassenmethoden (vollständige Kommandozeilen)">. =head1 METHODS =head2 Konstruktor =head3 new() - Konstruktor =head4 Synopsis $cmd = $class->new; $cmd = $class->new($str); =head4 Description Instantiiere ein FFmpeg-Kommando-Objekt und liefere eine Referenz auf dieses Objekt zurück. =cut # ----------------------------------------------------------------------------- sub new { my ($class,$str) = @_; return $class->SUPER::new( cmd => $str // '', inputA => [], inputObjectA => [], outputA => [], outName => undef, outWidth => undef, outHeight => undef, outStart => undef, outStop => undef, ); } # ----------------------------------------------------------------------------- =head2 Objektmethoden =head3 command() - Kommandozeile als Zeichenkette =head4 Synopsis $str = $cmd->command; =head4 Description Liefere das Kommando als Zeichenkette. =cut # ----------------------------------------------------------------------------- sub command { return shift->{'cmd'}; } # ----------------------------------------------------------------------------- =head3 input() - Eingabe-Datei als Objekt =head4 Synopsis $fil = $cmd->input($i); =head4 Description Instantiiere Eingabe-Datei $i als Quiq::File-Objekt und liefere dieses zurück. Das Objekt wird gecached. =cut # ----------------------------------------------------------------------------- sub input { my ($self,$i) = @_; my $fil = $self->inputObjectA->[$i]; if (!$fil) { if (my $input = $self->inputA->[$i]) { $fil = Quiq::File::Video->new($input); $self->inputObjectA->[$i] = $fil; # cachen } } return $fil; } # ----------------------------------------------------------------------------- =head3 suffix() - Suffix Ausgabe-Datei =head4 Synopsis $str = $cmd->suffix; =head4 Description Liefere den Suffix für eine Ausgabedatei. Der Suffix ist eine Zeichenkette der Form NAME-WIDTH-HEIGHT-START-STOP wobei Komponenten fehlen können, die nicht definiert sind. =cut # ----------------------------------------------------------------------------- sub suffix { my $self = shift; my @suffix; my ($outName,$outWidth,$outHeight,$outStart,$outStop) = $self->get(qw/outName outWidth outHeight outStart outStop/); # name if ($outName) { push @suffix,$outName; } # size if ($outWidth && $outHeight) { push @suffix,sprintf('%04dx%04d',$outWidth,$outHeight); } # start, stop if (defined($outStart) && $outStop) { push @suffix,sprintf '%03d-%03d',POSIX::floor($outStart), POSIX::ceil($outStop); } return join '-',@suffix; } # ----------------------------------------------------------------------------- =head2 Kommandozeile konstruieren =head3 addOption() - Füge Option hinzu =head4 Synopsis $cmd->addOption($opt); $cmd->addOption($opt=>$val); =head4 Description Ergänze die Kommandozeile um die Option $opt und (optional) den Wert $val. Die Methode liefert keinen Wert zurück. =head4 Examples Option ohne Wert: $cmd->addOption('-y'); => -y Option mit Wert: $cmd->addOption(-i=>'video/GOPR1409.mp4'); => -i 'video/GOPR1409.mp4' =cut # ----------------------------------------------------------------------------- sub addOption { my $self = shift; my $opt = shift; # @_: $val my $ref = $self->getRef('cmd'); my $val; if (@_) { $val = shift; if (!defined($val) || $val eq '') { # Keine Option hinzufügen, wenn Wert-Argument, # angegeben, dieses aber undef oder '' ist return; } } if ($$ref) { $$ref .= ' '; } $$ref .= $opt; if (defined $val) { $$ref .= ' '; if ($val =~ /^([0-9.]+|[A-Za-z0-9:]+)$/) { $$ref .= $val; } else { $$ref .= "'$val'"; } } return; } # ----------------------------------------------------------------------------- =head3 addInput() - Füge Input-Option hinzu =head4 Synopsis $cmd->addInput($input); =head4 Description Ergänze das Kommando um Input $input, sofern $input einen Wert hat. Die Methode liefert keinen Wert zurück. =head4 Examples Dateiname: $cmd->addInput('video/GOPR1409.mp4'); => -i 'video/GOPR1409.mp4' Muster: $cmd->addInput('img/*.jpg'); => -i 'img/*.jpg' Undefiniert: $cmd->addInput(undef); => =cut # ----------------------------------------------------------------------------- sub addInput { my ($self,$input) = @_; if ($input) { $self->addOption(-i=>$input); $self->push(inputA=>$input); } return; } # ----------------------------------------------------------------------------- =head3 addFilter() - Füge Filter-Option hinzu =head4 Synopsis $cmd->addFilter($opt,\@filter,$sep); =head4 Description Ergänze das Kommando um Filter-Option $opt mit den Filtern @filter und dem Trenner $sep (Komma oder Semikolon). =head4 Examples Video Filter-Chain: $cmd->addFilter(-vf=>['crop=1440:1080','scale=720*a:720']); => -vf 'crop=1440:1080,scale=720*a:720' =cut # ----------------------------------------------------------------------------- sub addFilter { my ($self,$opt,$filterA,$sep) = @_; if (my $val = join($sep,@$filterA)) { $self->addOption($opt=>$val); } return; } # ----------------------------------------------------------------------------- =head3 addStartStop() - Füge Optionen für Zeitbereich hinzu =head4 Synopsis $cmd->addStartStop($start,$stop); =head4 Description Ergänze das Kommando um Optionen, die den Zeitbereich auf den Bereich $start und $stop eingrenzen. =head4 Examples Nur Start-Zeitpunkt: $cmd->addStartStop(5.5); => -ss 5.5 Nur Ende-Zeitpunkt: $cmd->addStartStop(undef,20.5); => -t 20.5 Start- und Ende-Zeitpunkt: $cmd->addStartStop(5.5,20.5); => -ss 5.5 -t 20.5 =cut # ----------------------------------------------------------------------------- sub addStartStop { my ($self,$start,$stop) = @_; if ($start) { $self->addOption(-ss=>$start); } $start ||= 0; if ($stop && $stop > $start) { $self->addOption(-t=>$stop-$start); } return; } # ----------------------------------------------------------------------------- =head3 addBitrate() - Füge Bitrate-Option hinzu =head4 Synopsis $cmd->addBitrate($bitrate); =head4 Description Ergänze das Kommando um eine allgemeine Bitrate-Option mit Suffix 'k' (= kb/s). Ist die Bitrate 0, '' oder undef, wird die Option nicht hinzugefügt. =head4 Examples Bitrate von 10000k: $cmd->addBitrate(10000); => -b 10000k =cut # ----------------------------------------------------------------------------- sub addBitrate { my ($self,$bitrate) = @_; if ($bitrate) { $self->addOption(-b=>$bitrate.'k'); } return; } # ----------------------------------------------------------------------------- =head3 addOutput() - Füge Output-Argument hinzu =head4 Synopsis $cmd->addOutput($output); =head4 Description Ergänze das Kommando um Output $output. Die Methode liefert keinen Wert zurück. =head4 Examples Dateiname: $cmd->addOutput('video/GOPR1409.mp4'); => 'video/GOPR1409.mp4' Muster: $cmd->addOutput('img/%06d.jpg'); => 'img/%06d.jpg' =cut # ----------------------------------------------------------------------------- sub addOutput { my ($self,$out) = @_; if (!defined $out || $out eq '') { # Dateiname generieren my $inputA = $self->get('inputA'); my ($path,$ext) = $inputA->[0] =~ /(.+?)\.([^.]+)$/; $out = sprintf '%s-%s.%s',$path,$self->suffix,$ext; } else { # Suffix einsetzen $out =~ s/%S/$self->suffix/e; } my $ref = $self->getRef('cmd'); if ($$ref) { $$ref .= ' '; } $$ref .= qq|'$out'|; $self->push(outputA=>$out); return; } # ----------------------------------------------------------------------------- =head3 addString() - Füge Zeichenkette am Ende hinzu =head4 Synopsis $cmd->addString($str); =head4 Description Füge Zeichenkette $str am Ende der Kommandozeile hinzu, mit einem Leerzeichen als Trenner. =head4 Example Kommando nach Objekt-Instantiierung: $cmd->addString('ffprobe'); => ffprobe =cut # ----------------------------------------------------------------------------- sub addString { my ($self,$str) = @_; my $ref = $self->getRef('cmd'); if ($$ref) { $$ref .= ' '; } $$ref .= $str; return; } # ----------------------------------------------------------------------------- =head3 prependString() - Füge Zeichenkette am Anfang hinzu =head4 Synopsis $cmd->prependString($str); =head4 Description Füge Zeichenkette $str am Beginn der Kommandozeile hinzu. Ein Leerzeichen wird automatisch hinzugefügt. =head4 Example Kommando voranstellen: $cmd->prependString('ffplay -autoexit'); => ffplay -autoexit ... =cut # ----------------------------------------------------------------------------- sub prependString { my ($self,$str) = @_; my $ref = $self->getRef('cmd'); if ($$ref) { $$ref = ' '.$$ref; } $$ref = $str.$$ref; return; } # ----------------------------------------------------------------------------- =head2 Filter =head3 cropFilter() - Liefere Crop-Filter =head4 Synopsis $str = $cmd->cropFilter($width,$height); $str = $cmd->cropFilter($width,$height,$xOffset,$yOffset); =head4 Description Erzeuge eine Crop-Filter-Spezifikation für die angegebenen Argumente und liefere diese zurück. =head4 Examples Nur Breite und Höhe: $cmd->cropFilter(1280,720); => 'crop=1280:720' Breite, Höhe, X-Offset, Y-Offset: $cmd->cropFilter(1280,720,240,0); => 'crop=1280:720:240:0' =cut # ----------------------------------------------------------------------------- sub cropFilter { my $self = shift; my $width = shift; my $height = shift; # @_: $xOffset,$yOffset my $str = "crop=$width:$height"; if (@_) { my $xOffset = shift || 0; my $yOffset = shift || 0; $str .= ":$xOffset:$yOffset"; } return $str; } # ----------------------------------------------------------------------------- =head3 scaleFilter() - Liefere Scale-Filter =head4 Synopsis $str = $cmd->scaleFilter($width,$height); $str = $cmd->scaleFilter("$width:$height"); =head4 Description Erzeuge eine Crop-Filter-Spezifikation für die angegebenen Argumente und liefere diese zurück. Sind die Argumente undefiniert, wird eine leere Liste geliefert. =head4 Examples Breite und Höhe als getrennte Argumente: $cmd->scaleFilter(1280,720); => 'scale=1280:720' Breite und Höhe in einem Argument: $cmd->scaleFilter('1280:720'); => 'scale=1280:720' Undefiniertes Argument: @filter = $cmd->scaleFilter(undef); => () =cut # ----------------------------------------------------------------------------- sub scaleFilter { my $self = shift; # @_: $width,$height -or- "$width,$height" my $size; if (@_ == 1) { $size = shift; } else { if (defined(my $width = shift) && defined(my $height = shift)) { $size = "$width:$height"; } } if (!defined($size)) { return (); } return "scale=$size"; } # ----------------------------------------------------------------------------- =head3 fpsFilter() - Liefere Fps-Filter =head4 Synopsis $str = $cmd->fpsFilter($fps); =head4 Description Erzeuge eine Fps-Filter-Spezifikation und liefere diese zurück. Ist das Argument undef, liefere eine leere Liste. =head4 Examples Argument: $cmd->fpsFilter(24); => 'fps=24' Undefiniertes Argument: @filter = $cmd->fpsFilter(undef); => () =cut # ----------------------------------------------------------------------------- sub fpsFilter { my ($self,$fps) = @_; return !defined $fps? (): "fps=$fps"; } # ----------------------------------------------------------------------------- =head3 framestepFilter() - Liefere Framestep-Filter =head4 Synopsis $str = $cmd->framestepFilter($fps); =head4 Description Erzeuge eine Framestep-Filter-Spezifikation und liefere diese zurück. Ist das Argument undef, liefere eine leere Liste. =head4 Examples Argument: $cmd->framestepFilter(4); => 'framestep=4' Undefiniertes Argument: @filter = $cmd->framestepFilter(undef); => () =cut # ----------------------------------------------------------------------------- sub framestepFilter { my ($self,$framestep) = @_; if (!defined($framestep) || $framestep == 1) { return (); } return "framestep=$framestep"; } # ----------------------------------------------------------------------------- =head2 Ausgabe-Datei-Eigenschaften (Getter/Setter) =head3 outName() - Setze/Liefere Bezeichnung Ausgabe-Datei =head4 Synopsis $cmd->outName($name); $name = $cmd->outName; =head4 Description Setze oder liefere die Bezeichnung für die Ausgabe-Datei. Die Angabe wird für den Suffix der Ausgabe-Datei genutzt. =head3 outSize() - Setze/Liefere Breite und Höhe Video-Ausgabe =head4 Synopsis $cmd->outSize($width,$height); ($width,$height) = $cmd->outSize; =head4 Description Setze oder liefere die Höhe und Breite der Video-Ausgabe. Die Angabe wird für den Suffix der Video-Ausgabe-Datei genutzt. =cut # ----------------------------------------------------------------------------- sub outSize { my $self = shift; # @_: $width,$height if (@_) { $self->{'outWidth'} = shift; $self->{'outHeight'} = shift; } return ($self->{'outWidth'},$self->{'outHeight'}); } # ----------------------------------------------------------------------------- =head3 outStart() - Setze/Liefere Start-Zeitpunkt =head4 Synopsis $cmd->outStart($s); $s = $cmd->outStart; =head4 Description Setze oder liefere den Start-Zeitpunkt der Ausgabe. Die Angabe wird für den Suffix der Ausgabe-Datei genutzt. =head3 outStop() - Setze/Liefere Stop-Zeitpunkt =head4 Synopsis $cmd->outStop($s); $s = $cmd->outStop; =head4 Description Setze oder liefere den Stop-Zeitpunkt der Ausgabe. Die Angabe wird für den Suffix der Ausgabe-Datei genutzt. =head2 Klassenmethoden (vollständige Kommandozeilen) =head3 imagesToVideo() - Füge Bild-Sequenz zu einem Video zusammen =head4 Synopsis $cmd = $class->imagesToVideo($pattern,$output,@opt); =head4 Arguments =over 4 =item $pattern Pfad-Muster der Bilder. Enthält das Pfad-Muster einen Stern (*), wird C<-pattern_type glob> gewählt. Beispiele: 'img/%06d.jpg' => -i 'img/%06d.jpg' 'img/*.jpg' => -pattern_type glob -i 'img/*.jpg' =item $output Name der generierten Video-Datei. =back =head4 Options =over 4 =item -audio => $file (Default: undef) Erzeuge einen Audio-Stream aus Audio-Datei $file. =item -duration => $duration (Default: undef) Beende die Ausgabe, wenn die Dauer $duration erreicht ist. =item -framerate => $n (Default: 8) Anzahl Bilder pro Sekunde. =item -loop => $bool (Default: 0) Wiederhole die Bildserie zyklisch. =item -play => 0|1|2 (Default: 0) Zeige das generierte Video im Player an, statt es in einer Datei zu speichern. Bei -play=>2 bleibt das Fenster des Players offen, bis es per Hand geschlossen wird. =item -preset => $preset (Default: undef) Satz an vorgewählten Optionen, für Encoding-Zeit vs. Kompressionsrate. Mögliche Werte: ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow. Siehe L<https://trac.ffmpeg.org/wiki/Encode/H.264>. =item -size => "$width:$height" (Default: undef) Breite und Höhe des generierten Video. Ohne Angabe nimmt ffmpeg die Größe der Bilder. =item -videoBitrate => $bitrate (Default: 60_000) Video-Bitrate in kbit/s. =item -videoFilter => $filter Optionale Filterangabe. Z.B. -videoFilter => 'lutyuv=y=val*1.4,hue=s=10' =item -videoFramerate => $n (Default: 24) Framerate des Video. =back =head4 Description Generiere ein ffmpeg-Kommando zum Zusammenfügen der Bilder $pattern zu Video $output und liefere dieses Kommando zurück. =cut # ----------------------------------------------------------------------------- sub imagesToVideo { my $class = shift; # @_: $pattern,$output,@opt # Optionen und Argumente my $audio = undef; my $duration = undef, my $framerate = 8; my $loop = 0; my $play = 0; my $preset = undef; my $size = undef; my $videoBitrate = 60_000; my $videoFilter = undef; my $videoFramerate = 24; Quiq::Option->extract(\@_, -audio => \$audio, -duration => \$duration, -framerate => \$framerate, -loop => \$loop, -play => \$play, -preset => \$preset, -size => \$size, -videoBitrate => \$videoBitrate, -videoFilter => \$videoFilter, -videoFramerate => \$videoFramerate, ); if (@_ == 0 || @_ > 2) { $class->throw('Usage: $ffm->imagesToVideo($input,$output,@opt)'); } my $pattern = shift; my $output = shift; # Operation ausführen # * Command-Objekt instantiieren my $self = $class->new('ffmpeg -y'); # * Input if ($loop) { $self->addOption(-loop=>$loop); } $self->addOption(-framerate=>$framerate); $self->addOption(-f=>'image2'); if ($pattern =~ /\*/) { $self->addOption(-pattern_type=>'glob'); } $self->addInput($pattern); if ($audio) { $self->addInput($audio); } # * Filter my @filter; # ** fps push @filter,$self->fpsFilter($videoFramerate); # ** scale push @filter,$self->scaleFilter($size); if ($play && !$size) { push @filter,$self->scaleFilter('720*a',720); } # ** YUV color space (laut ffmpeg-Doku aus Kompatibilitätsgründen nötig) push @filter,'format=yuv420p'; # ** Optionale Video-Filter if ($videoFilter) { push @filter,$videoFilter; } $self->addFilter(-vf=>\@filter,','); # * Output-Options if (defined $duration) { $self->addOption(-t=>$duration); } elsif ($audio) { $self->addOption('-shortest'); } if (defined $videoBitrate) { $self->addOption('-b:v'=>$videoBitrate.'k'); } if (defined $preset) { $self->addOption(-preset=>$preset); } # * Output if ($play) { $self->addOption(-f=>'avi'); if ($play == 1) { $self->addString('- 2>/dev/null | ffplay -autoexit - 2>/dev/null'); } else { $self->addString('- 2>/dev/null | ffplay - 2>/dev/null'); } } else { $self->addOutput($output); } return $self; } # ----------------------------------------------------------------------------- =head3 videoToImages() - Extrahiere Bild-Sequenz (Frames) aus Video =head4 Synopsis $cmd = $ffm->videoToImages($input,$dir,@opt); =head4 Options =over 4 =item -aspectRatio => '16:9'|'4:3' (Default: undef) Gewünschtes Seitenverhältnis der Bilder. Hat das Video ein abweichendes Seitenverhältnis, wird ein entsprechender Crop-Filter aufgesetzt. =item -framestep => $n (Default: 1) Extrahiere jeden $n-ten Frame. =item -pixelFormat=FMT (Default: 'yuvj422p') Pixel-Format des erzeugten Bildes. Laut Aussage im Netz ist yuvj422p das Standard-Pixel-Format für jpeg-Dateien. Wird das Pixel-Format hier nicht geändert, erzeugt ffmpeg die Bilder in Pixelformat yuvj420p, was Probleme beim Zusammenfügen mit Bildern einer Kamera zu einem Film macht. =item -quality => $n (Default: 2) Qualität der generierten jpg-Bilddateien. Wertebereich: 2-31, mit 2 als bester und 31 als schlechtester Qualität. =item -start => $s (Default: 0) Zeitpunkt in Sekunden (ggf. mit Nachkommastellen) vom Beginn des Video, an dem das Extrahieren der Frames beginnt. =item -stop => $s (Default: undef) Zeitpunkt in Sekunden (ggf. mit Nachkommastellen) vom Beginn des Video, an dem das Extrahieren der Frames endet. =back =head4 Description Generiere ein ffmpeg-Kommando, das die Frames aus dem Video $input extrahiert und im Verzeichnis $dir speichert. Die Bilder haben das Format 'jpg'. Der Name der Dateien ist NNNNNN.jpg, von 1 an lückenlos aufsteigend. =head4 Examples Ohne Optionen: $ffm->videoToImages('video.mp4','img'); => ffmpeg -y -loglevel error -stats -i 'video.mp4' -qscale:v 2 'img/%06d.jpg' Video-Seitenverhältnis 16:9 zu Bild-Seitenverhältnis 4:3 wandeln: $ffm->videoToImages('video.mp4','img', -aspectRatio => '4:3', ); => ffmpeg -y -loglevel error -stats -i 'video.mp4' -vf 'crop=ih/3*4:ih' -qscale:v 2 'img/%06d.jpg' Alle Optionen: $ffm->videoToImages('video.mp4','img', -aspectRatio => '4:3', -framestep => 6, -start => 3, -stop => 10, ); => ffmpeg -y -loglevel error -stats -i 'video.mp4' -vf 'framestep=6,crop=ih/3*4:ih' -ss 3 -t 7 -qscale:v 2 'img/%06d.jpg' =cut # ----------------------------------------------------------------------------- sub videoToImages { my $class = shift; # @_: $input,$dir,@opt # Optionen und Argumente my $aspectRatio = undef; my $framestep = 1; my $pixelFormat = 'yuvj422p'; my $quality = 2; my $start = 0; my $stop = undef; Quiq::Option->extract(\@_, -aspectRatio => \$aspectRatio, -framestep => \$framestep, -pixelFormat => \$pixelFormat, -quality => \$quality, -start => \$start, -stop => \$stop, ); if (@_ == 0 || @_ > 2) { $class->throw('Usage: $ffm->videoToImages($input,$dir,@opt)'); } my $input = shift; my $dir = shift; # Operation ausführen # * Command-Objekt instantiieren my $self = $class->new; # * Input $self->addInput($input); # * Filter my @filter; # ** framestep push @filter,$self->framestepFilter($framestep); if ($aspectRatio) { if ($aspectRatio eq '4:3') { push @filter,$self->cropFilter('ih/3*4','ih'); } elsif ($aspectRatio eq '16:9') { push @filter,$self->cropFilter('iw','iw/16*9'); } else { $self->throw; } } $self->addFilter(-vf=>\@filter,','); # Output-Optionen $self->addStartStop($start,$stop); $self->addOption('-qscale:v'=>$quality); $self->addOption(-pix_fmt=>$pixelFormat); # * Output $self->prependString('ffmpeg -y'); $self->addOutput("$dir/%06d.jpg"); return $self; } # ----------------------------------------------------------------------------- =head3 extract() - Extrahiere Abschnitt aus Audio- oder Video-Datei =head4 Synopsis $cmd = $class->extract($input,$output,@opt); =head4 Arguments =over 4 =item $input Eingabe-Datei. =item $output Ausgabe-Datei. =back =head4 Options =over 4 =item -name => $str (Default: undef) Füge dem Dateinamen die Bezeichnung $str hinzu. =item -play => 0|1|2 (Default: 0) Extrahiere den Ausschnitt nicht, sondern zeige ihn an. 1=Exit am Ende, 2=Fenster offen lassen (zu erneuten Positionen). =item -start => $s (Default: 0) Start-Position in einem Format, das die Klasse Quiq::Duration akzeptiert. =item -stop => $s (Default: undef) Ende-Position in einem Format, das die Klasse Quiq::Duration akzeptiert. =back =head4 Description Extrahiere von Position $start bis Position $stop einen Teil aus der Audio- oder Video-Datei $input und schreibe ihn auf Datei $output. Die Extraktion erfolgt ohne Transcoding, also ohne Qualitätsverlust. =cut # ----------------------------------------------------------------------------- sub extract { my $class = shift; # @_: $input,$output,@opt # Optionen und Argumente my $name = undef; my $play = 0; my $start = undef; my $stop = undef; Quiq::Option->extract(\@_, -name => \$name, -play => \$play, -start => \$start, -stop => \$stop, ); if (@_ == 0 || @_ > 2) { $class->throw('Usage: $ffm->extract($input,$output,@opt)'); } my $input = shift; my $output = shift; my $self = $class->new; $self->addInput($input); if (defined $start) { $start = Quiq::Duration->stringToSeconds($start); } if (defined $stop) { $stop = Quiq::Duration->stringToSeconds($stop); } $self->addStartStop($start,$stop); if ($play) { $self->prependString($play == 1? 'ffplay -autoexit': 'ffplay'); $self->addOption(-vf=>'scale=720*a:720'); } else { my $inp = $self->input(0); $self->outName($name); # Rausgenommen, da Fehler bei Extraktion aus Audio-Datei. # Bei Video nötig? # $self->outSize($inp->size); $self->outStart($start || 0); $self->outStop($stop || $inp->duration); $self->prependString('ffmpeg -y'); $self->addOption(-codec=>'copy'); $self->addOutput($output); } return $self; } # ----------------------------------------------------------------------------- =head3 extract169To43() - Extrahiere/Croppe 16:9-Video zu 4:3-Video =head4 Synopsis $cmd = $class->extract169To43($input,$output,@opt); =head4 Arguments =over 4 =item $input Eingabe-Datei. =item $output Ausgabe-Datei. Wenn undef, wird der Name der Ausgabedatei generiert. =back =head4 Options =over 4 =item -bitrate => $x (Default: undef) Die Bitrate des generierten Video in kb/s. =item -name => $str (Default: undef) Füge dem Dateinamen die Bezeichnung $str hinzu. =item -play => 0|1|2 (Default: 0) Zeige das generierte Video im Player an, statt es in einer Datei zu speichern. Bei -play=>2 bleibt das Fenster des Players offen, bis es per Hand geschlossen wird. =item -start => $s (Default: 0) Start-Position in Sekunden (mit Millisekunden als Nachkommastellen). =item -stop => $s (Default: undef) Ende-Position in Sekunden (mit Millisekunden als Nachkommastellen). =item -xOffset => $n (Default: undef) Crop-Offset in x-Richtung. Per Default croppt der crop-Filter mittig. =back =head4 Description Croppe 16:9-Video $input zum 4:3-Video $output. Die Crop-Operation schneidet links und rechts einen Teil des Video ab. =cut # ----------------------------------------------------------------------------- sub extract169To43 { my $class = shift; # @_: $input,$output,@opt # Optionen und Argumente my $bitrate = undef; my $name = undef; my $play = 0; my $start = undef; my $stop = undef; my $xOffset = undef; Quiq::Option->extract(\@_, -bitrate => \$bitrate, -name => \$name, -play => \$play, -start => \$start, -stop => \$stop, -xOffset => \$xOffset, ); if (@_ == 0 || @_ > 2) { $class->throw('Usage: $ffm->extract169To43($input,$output,@opt)'); } my $input = shift; my $output = shift; # Operation ausführen # * Command-Objekt instantiieren my $self = $class->new; # * Input $self->addInput($input); # * Filter my @filter; # ** crop my ($width,$height) = $self->input(0)->size; my $newWidth = $height/3*4; if (!defined $xOffset) { $xOffset = ($width-$newWidth)/2; } push @filter,$self->cropFilter($newWidth,$height,$xOffset,0); # ** scale (im Falle von play) if ($play) { push @filter,$self->scaleFilter('720*a',720); } $self->addFilter('-vf',\@filter,','); # * Output-Optionen $self->addStartStop($start,$stop); $self->addBitrate($bitrate || $self->input(0)->bitrate); # * Output if ($play) { $self->prependString($play == 1? 'ffplay -autoexit': 'ffplay'); } else { $self->outName($name); $self->outSize($newWidth,$height); $self->outStart($start || 0); $self->outStop($stop || $self->input(0)->duration); $self->prependString('ffmpeg -y'); $self->addOutput($output); } return $self; } # ----------------------------------------------------------------------------- =head3 videoInfo() - Schreibe Video-Stream-Information in XML =head4 Synopsis $cmd = $class->videoInfo($input); $cmd = $class->videoInfo($input,$streamIndex); =head4 Arguments =over 4 =item $input Eingabe-Datei. =item $streamIndex (Default: 0) Index des Video-Stream. =back =head4 Description Erzeuge eine ffprobe-Kommandozeile, die Information über den Video-Stream $streamIndex in Datei $input liefert. Ist kein Stream-Index angegeben, wird der erste Stream (Index 0) genommen. =cut # ----------------------------------------------------------------------------- sub videoInfo { my $class = shift; my $input = shift; my $streamIndex = shift || 0; my $self = $class->new; $self->addString('ffprobe'); $self->addOption(-loglevel=>'error'); $self->addOption(-print_format=>'xml'); $self->addOption('-show_streams'); $self->addOption(-select_streams=>"v:$streamIndex"); $self->addInput($input); return $self; } # ----------------------------------------------------------------------------- =head2 Kommando-Ausführung =head3 execute() - Führe FFmpeg-Kommandozeile aus =head4 Synopsis $cmd->execute; =head4 Description Führe FFmpeg-Kommando $cmd aus. Als Ausgabe erscheint lediglich die Fortschrittsanzeige. =cut # ----------------------------------------------------------------------------- sub execute { my $self = shift; my $cmd = $self->command; my $fh = Quiq::FileHandle->open('-|',"($cmd 2>&1)"); local $/ = "\r"; $| = 1; while (<$fh>) { if (/^(ffmpeg|ffplay|ffprobe|Input|Output)/) { next; } s/\n+$/\n/; print; } $fh->close; return; } # ----------------------------------------------------------------------------- =head1 VERSION 1.196 =head1 AUTHOR Frank Seitz, L<http://fseitz.de/> =head1 COPYRIGHT Copyright (C) 2021 Frank Seitz =head1 LICENSE This code is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut # ----------------------------------------------------------------------------- 1; # eof
20.308087
142
0.53859
ed6c1268dc34aef02435ad4741a5afd4b8589435
139
t
Perl
_templates/container/new/index.ejs.t
Dewyer/arpad2020BGrad
f002bb2b8869a2953a561fd23d1bfba309036228
[ "Apache-2.0" ]
1
2020-04-06T16:47:46.000Z
2020-04-06T16:47:46.000Z
pandamic-web/_templates/container/new/index.ejs.t
Pandamic-App/pandamic
a0250fc9066471bdd39b84c84a51c9ee9d6b5760
[ "MIT" ]
6
2020-07-12T08:31:20.000Z
2022-02-27T02:41:45.000Z
_templates/container/new/index.ejs.t
Dewyer/arpad2020BGrad
f002bb2b8869a2953a561fd23d1bfba309036228
[ "Apache-2.0" ]
null
null
null
--- to: src/components/<%= name %>/index.tsx --- import <%= name %>Container from "./<%= name %>-container"; export <%= name %>Container;
19.857143
59
0.589928
ed17a0dbdf719a194f32f6916b9c86231bbfe75f
6,982
pl
Perl
scripts/generate_errors.pl
paul-elliott-arm/mbedtls
17605f072b6bc85e1a9cf6a81bd6b5d5eb65440a
[ "Apache-2.0" ]
3,553
2015-01-29T21:43:36.000Z
2022-03-31T08:41:59.000Z
scripts/generate_errors.pl
paul-elliott-arm/mbedtls
17605f072b6bc85e1a9cf6a81bd6b5d5eb65440a
[ "Apache-2.0" ]
5,899
2016-05-11T19:21:49.000Z
2022-03-31T18:17:20.000Z
scripts/generate_errors.pl
paul-elliott-arm/mbedtls
17605f072b6bc85e1a9cf6a81bd6b5d5eb65440a
[ "Apache-2.0" ]
1,176
2015-05-20T08:31:11.000Z
2022-03-31T22:40:08.000Z
#!/usr/bin/env perl # Generate error.c # # Usage: ./generate_errors.pl or scripts/generate_errors.pl without arguments, # or generate_errors.pl include_dir data_dir error_file # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. use strict; my ($include_dir, $data_dir, $error_file); if( @ARGV ) { die "Invalid number of arguments" if scalar @ARGV != 3; ($include_dir, $data_dir, $error_file) = @ARGV; -d $include_dir or die "No such directory: $include_dir\n"; -d $data_dir or die "No such directory: $data_dir\n"; } else { $include_dir = 'include/mbedtls'; $data_dir = 'scripts/data_files'; $error_file = 'library/error.c'; unless( -d $include_dir && -d $data_dir ) { chdir '..' or die; -d $include_dir && -d $data_dir or die "Without arguments, must be run from root or scripts\n" } } my $error_format_file = $data_dir.'/error.fmt'; my @low_level_modules = qw( AES ARC4 ARIA ASN1 BASE64 BIGNUM BLOWFISH CAMELLIA CCM CHACHA20 CHACHAPOLY CMAC CTR_DRBG DES ENTROPY ERROR GCM HKDF HMAC_DRBG MD2 MD4 MD5 NET OID PADLOCK PBKDF2 PLATFORM POLY1305 RIPEMD160 SHA1 SHA256 SHA512 THREADING XTEA ); my @high_level_modules = qw( CIPHER DHM ECP MD PEM PK PKCS12 PKCS5 RSA SSL X509 ); my $line_separator = $/; undef $/; open(FORMAT_FILE, "$error_format_file") or die "Opening error format file '$error_format_file': $!"; my $error_format = <FORMAT_FILE>; close(FORMAT_FILE); $/ = $line_separator; my @files = <$include_dir/*.h>; my @necessary_include_files; my @matches; foreach my $file (@files) { open(FILE, "$file"); my @grep_res = grep(/^\s*#define\s+MBEDTLS_ERR_\w+\s+\-0x[0-9A-Fa-f]+/, <FILE>); push(@matches, @grep_res); close FILE; my $include_name = $file; $include_name =~ s!.*/!!; push @necessary_include_files, $include_name if @grep_res; } my $ll_old_define = ""; my $hl_old_define = ""; my $ll_code_check = ""; my $hl_code_check = ""; my $headers = ""; my %included_headers; my %error_codes_seen; foreach my $line (@matches) { next if ($line =~ /compat-1.2.h/); my ($error_name, $error_code) = $line =~ /(MBEDTLS_ERR_\w+)\s+\-(0x\w+)/; my ($description) = $line =~ /\/\*\*< (.*?)\.? \*\//; die "Duplicated error code: $error_code ($error_name)\n" if( $error_codes_seen{$error_code}++ ); $description =~ s/\\/\\\\/g; if ($description eq "") { $description = "DESCRIPTION MISSING"; warn "Missing description for $error_name\n"; } my ($module_name) = $error_name =~ /^MBEDTLS_ERR_([^_]+)/; # Fix faulty ones $module_name = "BIGNUM" if ($module_name eq "MPI"); $module_name = "CTR_DRBG" if ($module_name eq "CTR"); $module_name = "HMAC_DRBG" if ($module_name eq "HMAC"); my $define_name = $module_name; $define_name = "X509_USE,X509_CREATE" if ($define_name eq "X509"); $define_name = "ASN1_PARSE" if ($define_name eq "ASN1"); $define_name = "SSL_TLS" if ($define_name eq "SSL"); $define_name = "PEM_PARSE,PEM_WRITE" if ($define_name eq "PEM"); my $include_name = $module_name; $include_name =~ tr/A-Z/a-z/; # Fix faulty ones $include_name = "net_sockets" if ($module_name eq "NET"); $included_headers{"${include_name}.h"} = $module_name; my $found_ll = grep $_ eq $module_name, @low_level_modules; my $found_hl = grep $_ eq $module_name, @high_level_modules; if (!$found_ll && !$found_hl) { printf("Error: Do not know how to handle: $module_name\n"); exit 1; } my $code_check; my $old_define; my $white_space; my $first; if ($found_ll) { $code_check = \$ll_code_check; $old_define = \$ll_old_define; $white_space = ' '; } else { $code_check = \$hl_code_check; $old_define = \$hl_old_define; $white_space = ' '; } if ($define_name ne ${$old_define}) { if (${$old_define} ne "") { ${$code_check} .= "#endif /* "; $first = 0; foreach my $dep (split(/,/, ${$old_define})) { ${$code_check} .= " || " if ($first++); ${$code_check} .= "MBEDTLS_${dep}_C"; } ${$code_check} .= " */\n\n"; } ${$code_check} .= "#if "; $headers .= "#if " if ($include_name ne ""); $first = 0; foreach my $dep (split(/,/, ${define_name})) { ${$code_check} .= " || " if ($first); $headers .= " || " if ($first++); ${$code_check} .= "defined(MBEDTLS_${dep}_C)"; $headers .= "defined(MBEDTLS_${dep}_C)" if ($include_name ne ""); } ${$code_check} .= "\n"; $headers .= "\n#include \"mbedtls/${include_name}.h\"\n". "#endif\n\n" if ($include_name ne ""); ${$old_define} = $define_name; } ${$code_check} .= "${white_space}case -($error_name):\n". "${white_space} return( \"$module_name - $description\" );\n" }; if ($ll_old_define ne "") { $ll_code_check .= "#endif /* "; my $first = 0; foreach my $dep (split(/,/, $ll_old_define)) { $ll_code_check .= " || " if ($first++); $ll_code_check .= "MBEDTLS_${dep}_C"; } $ll_code_check .= " */\n"; } if ($hl_old_define ne "") { $hl_code_check .= "#endif /* "; my $first = 0; foreach my $dep (split(/,/, $hl_old_define)) { $hl_code_check .= " || " if ($first++); $hl_code_check .= "MBEDTLS_${dep}_C"; } $hl_code_check .= " */\n"; } $error_format =~ s/HEADER_INCLUDED\n/$headers/g; $error_format =~ s/LOW_LEVEL_CODE_CHECKS\n/$ll_code_check/g; $error_format =~ s/HIGH_LEVEL_CODE_CHECKS\n/$hl_code_check/g; open(ERROR_FILE, ">$error_file") or die "Opening destination file '$error_file': $!"; print ERROR_FILE $error_format; close(ERROR_FILE); my $errors = 0; for my $include_name (@necessary_include_files) { if (not $included_headers{$include_name}) { print STDERR "The header file \"$include_name\" defines error codes but has not been included!\n"; ++$errors; } } exit !!$errors;
30.489083
106
0.57949
edab98fc5df762af91235392dc368aaf35b9b9ff
6,118
t
Perl
t/core/config_etcd.t
philzhangrui/apisix
7abd9585cfab2bc69dfd2ccfd26bbac1b75ddbfc
[ "Apache-2.0" ]
1
2021-03-12T17:07:30.000Z
2021-03-12T17:07:30.000Z
t/core/config_etcd.t
philzhangrui/apisix
7abd9585cfab2bc69dfd2ccfd26bbac1b75ddbfc
[ "Apache-2.0" ]
null
null
null
t/core/config_etcd.t
philzhangrui/apisix
7abd9585cfab2bc69dfd2ccfd26bbac1b75ddbfc
[ "Apache-2.0" ]
null
null
null
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # use t::APISIX 'no_plan'; repeat_each(1); no_long_string(); no_root_location(); log_level("info"); run_tests; __DATA__ === TEST 1: wrong etcd port --- yaml_config apisix: node_listen: 1984 etcd: host: - "http://127.0.0.1:7777" -- wrong etcd port timeout: 1 --- config location /t { content_by_lua_block { ngx.sleep(8) ngx.say(body) } } --- timeout: 12 --- request GET /t --- grep_error_log eval qr{connection refused} --- grep_error_log_out eval qr/(connection refused){1,}/ === TEST 2: originate TLS connection to etcd cluster without TLS configuration --- yaml_config apisix: node_listen: 1984 etcd: host: - "https://127.0.0.1:2379" --- config location /t { content_by_lua_block { ngx.sleep(4) ngx.say("ok") } } --- timeout: 5 --- request GET /t --- grep_error_log chop handshake failed --- grep_error_log_out eval qr/(handshake failed){1,}/ === TEST 3: originate plain connection to etcd cluster which enables TLS --- yaml_config apisix: node_listen: 1984 etcd: host: - "http://127.0.0.1:12379" --- config location /t { content_by_lua_block { ngx.sleep(4) ngx.say("ok") } } --- timeout: 5 --- request GET /t --- grep_error_log chop closed --- grep_error_log_out eval qr/(closed){1,}/ === TEST 4: originate TLS connection to etcd cluster and verify TLS certificate (default behavior) --- yaml_config apisix: node_listen: 1984 etcd: host: - "https://127.0.0.1:12379" --- config location /t { content_by_lua_block { ngx.sleep(4) ngx.say("ok") } } --- timeout: 5 --- request GET /t --- grep_error_log chop 18: self signed certificate --- grep_error_log_out eval qr/(18: self signed certificate){1,}/ === TEST 5: set route(id: 1) to etcd cluster with TLS --- yaml_config apisix: node_listen: 1984 admin_key: null etcd: host: - "https://127.0.0.1:12379" tls: verify: false --- config location /t { content_by_lua_block { local t = require("lib.test_admin").test local code, body = t('/apisix/admin/routes/1', ngx.HTTP_PUT, [[{ "methods": ["GET"], "upstream": { "nodes": { "127.0.0.1:8080": 1 }, "type": "roundrobin" }, "desc": "new route", "uri": "/index.html" }]], [[{ "node": { "value": { "methods": [ "GET" ], "uri": "/index.html", "desc": "new route", "upstream": { "nodes": { "127.0.0.1:8080": 1 }, "type": "roundrobin" } }, "key": "/apisix/routes/1" }, "action": "set" }]] ) ngx.status = code ngx.say(body) } } --- request GET /t --- response_body passed --- no_error_log [error] === TEST 6: get route(id: 1) from etcd cluster with TLS --- yaml_config apisix: node_listen: 1984 admin_key: null etcd: host: - "https://127.0.0.1:12379" tls: verify: false --- config location /t { content_by_lua_block { local t = require("lib.test_admin").test local code, body = t('/apisix/admin/routes/1', ngx.HTTP_GET, nil, [[{ "node": { "value": { "methods": [ "GET" ], "uri": "/index.html", "desc": "new route", "upstream": { "nodes": { "127.0.0.1:8080": 1 }, "type": "roundrobin" } }, "key": "/apisix/routes/1" }, "action": "get" }]] ) ngx.status = code ngx.say(body) } } --- request GET /t --- response_body passed --- no_error_log [error] === TEST 7: ensure only one auth request per subsystem for all the etcd sync --- yaml_config apisix: node_listen: 1984 etcd: host: - "http://127.0.0.1:1980" -- fake server port timeout: 1 user: root # root username for etcd password: 5tHkHhYkjr6cQY # root password for etcd --- config location /t { content_by_lua_block { ngx.sleep(0.5) } } --- request GET /t --- grep_error_log eval qr/etcd auth failed/ --- grep_error_log_out etcd auth failed etcd auth failed etcd auth failed etcd auth failed
23.351145
98
0.487905