code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
#!/pkg/gnu/bin//perl5 # # write new values from form to $wd/conf/testbed, and run WebStone # push(@INC, "$wd/bin"); require('WebStone-common.pl'); html_begin("Current Configuration"); &show_model(); &write_data(); print CLIENT <<EOF <HR> <FORM METHOD="POST" ACTION="$wd/bin/runbench.pl"> <P><INPUT TYPE="SUBMIT" VALUE="Run WebStone"> </FORM> </DL> EOF ; html_end(); # end main sub write_data { rename("$wd/conf/testbed", "$wd/conf/testbed.bak") || die "rename testbed: $!\n"; open(TESTBED, ">>$wd/conf/testbed") || die "open testbed: $!\n"; print CLIENT "<PRE>"; foreach $key (@keylist) { $$key =~ s/\+/ /g; $newvalue = "$key=\"$$key\"\n"; print CLIENT $newvalue; print TESTBED $newvalue; } print CLIENT "</PRE>"; close(TESTBED); } # end
wfnex/openbras
src/ace/ACE_wrappers/apps/JAWS/clients/WebSTONE/bin/write-testbed.pl
Perl
bsd-3-clause
788
#!/usr/bin/perl use strict; use warnings 'all'; use YAML qw(); use lib '/sysbuilder/lib'; use Yahoo::SysBuilder::Utils qw(run_local notify_boothost); my $cfg = YAML::LoadFile( '/sysbuilder/etc/config.yaml' ); my $dhclient = YAML::LoadFile( '/sysbuilder/etc/dhclient.yaml' ); my $ybiipinfo = { installdate => scalar localtime, hostname => $cfg->{hostname}, boothost_ip => $cfg->{boothost_ip}, profile => $cfg->{profile}, image => $cfg->{image}, installer => $cfg->{installer}, kernel_cmdline => $cfg->{kernel_cmdline}, yinst_ybiip_profiles => $cfg->{yinst_ybiip_profiles}, yinst_ybootserver => $cfg->{yinst_ybootserver}, }; $|++; print "INFO: Notifying boothost we're done\n"; # notify boothost we're done (unless we're running under yvm) notify_boothost( nextboot => 'done', broadcast => 'no' ) unless exists $cfg->{yvm_user}; open my $ok_file, ">", "/tmp/ysysbuilder-installer-ok"; close $ok_file; print "IMAGING COMPLETED\n\n"; sleep 1; exit 0;
eam/ysysbuilder
steps/std-esxi/900_finish.pl
Perl
bsd-3-clause
1,081
#!/usr/bin/env perl use strict; use warnings; use File::Slurp qw/read_file/; use Data::Dumper; my @lines = read_file('input'); my $res; my $i = 0; my @one = (); my @two = (); my @three = (); foreach my $line (@lines){ chomp $line; my ($a, $b, $c) = $line =~ m/(\d+)\s+(\d+)\s+(\d+)/; push @one, $a; push @two, $b; push @three, $c; next unless checkTriangle($a, $b, $c); $res++; } print "Result: $res\n"; $res = checkList(@one) + checkList(@two) + checkList(@three); print "Result two: $res\n"; sub checkTriangle { my ($a, $b, $c) = @_; return 0 unless $a + $b > $c; return 0 unless $a + $c > $b; return 0 unless $b + $c > $a; return 1; } sub checkList { my @list = @_; my $res = 0; for ($i = 0; $i < scalar @list; $i+=3) { next unless checkTriangle($list[$i], $list[$i+1], $list[$i+2]); $res++; } return $res; }
Aneurysm9/advent
2016/day3/day3.pl
Perl
bsd-3-clause
842
package LWP::UserAgent; use unmocked 'Moose'; use unmocked 'HTTP::Response'; use unmocked 'HTTP::Request'; our $AGENT_STRING; sub agent { my ($self, $string) = @_; $AGENT_STRING = $string; } our $TIMEOUT; sub timeout { my ($self, $timeout) = @_; $TIMEOUT = $timeout; } our $RESPONSE; our $REQUEST; sub request { my ($self, $req) = @_; $REQUEST = $req; my $res = HTTP::Response->new(@$RESPONSE); return $res; } 1;
sanyaade-mobiledev/smart-platform
t/Mock/LWP/UserAgent.pm
Perl
mit
450
require 5; package Pod::Simple::Progress; $VERSION = '3.32'; use strict; # Objects of this class are used for noting progress of an # operation every so often. Messages delivered more often than that # are suppressed. # # There's actually nothing in here that's specific to Pod processing; # but it's ad-hoc enough that I'm not willing to give it a name that # implies that it's generally useful, like "IO::Progress" or something. # # -- sburke # #-------------------------------------------------------------------------- sub new { my($class,$delay) = @_; my $self = bless {'quiet_until' => 1}, ref($class) || $class; $self->to(*STDOUT{IO}); $self->delay(defined($delay) ? $delay : 5); return $self; } sub copy { my $orig = shift; bless {%$orig, 'quiet_until' => 1}, ref($orig); } #-------------------------------------------------------------------------- sub reach { my($self, $point, $note) = @_; if( (my $now = time) >= $self->{'quiet_until'}) { my $goal; my $to = $self->{'to'}; print $to join('', ($self->{'quiet_until'} == 1) ? () : '... ', (defined $point) ? ( '#', ($goal = $self->{'goal'}) ? ( ' ' x (length($goal) - length($point)), $point, '/', $goal, ) : $point, $note ? ': ' : (), ) : (), $note || '', "\n" ); $self->{'quiet_until'} = $now + $self->{'delay'}; } return $self; } #-------------------------------------------------------------------------- sub done { my($self, $note) = @_; $self->{'quiet_until'} = 1; return $self->reach( undef, $note ); } #-------------------------------------------------------------------------- # Simple accessors: sub delay { return $_[0]{'delay'} if @_ == 1; $_[0]{'delay'} = $_[1]; return $_[0] } sub goal { return $_[0]{'goal' } if @_ == 1; $_[0]{'goal' } = $_[1]; return $_[0] } sub to { return $_[0]{'to' } if @_ == 1; $_[0]{'to' } = $_[1]; return $_[0] } #-------------------------------------------------------------------------- unless(caller) { # Simple self-test: my $p = __PACKAGE__->new->goal(5); $p->reach(1, "Primus!"); sleep 1; $p->reach(2, "Secundus!"); sleep 3; $p->reach(3, "Tertius!"); sleep 5; $p->reach(4); $p->reach(5, "Quintus!"); sleep 1; $p->done("All done"); } #-------------------------------------------------------------------------- 1; __END__
operepo/ope
bin/usr/share/perl5/core_perl/Pod/Simple/Progress.pm
Perl
mit
2,412
package YAML::Dumper; use YAML::Mo; extends 'YAML::Dumper::Base'; our $VERSION = '0.81'; use YAML::Dumper::Base; use YAML::Node; use YAML::Types; # Context constants use constant KEY => 3; use constant BLESSED => 4; use constant FROMARRAY => 5; use constant VALUE => "\x07YAML\x07VALUE\x07"; # Common YAML character sets my $ESCAPE_CHAR = '[\\x00-\\x08\\x0b-\\x0d\\x0e-\\x1f]'; my $LIT_CHAR = '|'; #============================================================================== # OO version of Dump. YAML->new->dump($foo); sub dump { my $self = shift; $self->stream(''); $self->document(0); for my $document (@_) { $self->{document}++; $self->transferred({}); $self->id_refcnt({}); $self->id_anchor({}); $self->anchor(1); $self->level(0); $self->offset->[0] = 0 - $self->indent_width; $self->_prewalk($document); $self->_emit_header($document); $self->_emit_node($document); } return $self->stream; } # Every YAML document in the stream must begin with a YAML header, unless # there is only a single document and the user requests "no header". sub _emit_header { my $self = shift; my ($node) = @_; if (not $self->use_header and $self->document == 1 ) { $self->die('YAML_DUMP_ERR_NO_HEADER') unless ref($node) =~ /^(HASH|ARRAY)$/; $self->die('YAML_DUMP_ERR_NO_HEADER') if ref($node) eq 'HASH' and keys(%$node) == 0; $self->die('YAML_DUMP_ERR_NO_HEADER') if ref($node) eq 'ARRAY' and @$node == 0; # XXX Also croak if aliased, blessed, or ynode $self->headless(1); return; } $self->{stream} .= '---'; # XXX Consider switching to 1.1 style if ($self->use_version) { # $self->{stream} .= " #YAML:1.0"; } } # Walk the tree to be dumped and keep track of its reference counts. # This function is where the Dumper does all its work. All type # transfers happen here. sub _prewalk { my $self = shift; my $stringify = $self->stringify; my ($class, $type, $node_id) = $self->node_info(\$_[0], $stringify); # Handle typeglobs if ($type eq 'GLOB') { $self->transferred->{$node_id} = YAML::Type::glob->yaml_dump($_[0]); $self->_prewalk($self->transferred->{$node_id}); return; } # Handle regexps if (ref($_[0]) eq 'Regexp') { return; } # Handle Purity for scalars. # XXX can't find a use case yet. Might be YAGNI. if (not ref $_[0]) { $self->{id_refcnt}{$node_id}++ if $self->purity; return; } # Make a copy of original my $value = $_[0]; ($class, $type, $node_id) = $self->node_info($value, $stringify); # Must be a stringified object. return if (ref($value) and not $type); # Look for things already transferred. if ($self->transferred->{$node_id}) { (undef, undef, $node_id) = (ref $self->transferred->{$node_id}) ? $self->node_info($self->transferred->{$node_id}, $stringify) : $self->node_info(\ $self->transferred->{$node_id}, $stringify); $self->{id_refcnt}{$node_id}++; return; } # Handle code refs if ($type eq 'CODE') { $self->transferred->{$node_id} = 'placeholder'; YAML::Type::code->yaml_dump( $self->dump_code, $_[0], $self->transferred->{$node_id} ); ($class, $type, $node_id) = $self->node_info(\ $self->transferred->{$node_id}, $stringify); $self->{id_refcnt}{$node_id}++; return; } # Handle blessed things if (defined $class) { if ($value->can('yaml_dump')) { $value = $value->yaml_dump; } elsif ($type eq 'SCALAR') { $self->transferred->{$node_id} = 'placeholder'; YAML::Type::blessed->yaml_dump ($_[0], $self->transferred->{$node_id}); ($class, $type, $node_id) = $self->node_info(\ $self->transferred->{$node_id}, $stringify); $self->{id_refcnt}{$node_id}++; return; } else { $value = YAML::Type::blessed->yaml_dump($value); } $self->transferred->{$node_id} = $value; (undef, $type, $node_id) = $self->node_info($value, $stringify); } # Handle YAML Blessed things if (defined YAML->global_object()->{blessed_map}{$node_id}) { $value = YAML->global_object()->{blessed_map}{$node_id}; $self->transferred->{$node_id} = $value; ($class, $type, $node_id) = $self->node_info($value, $stringify); $self->_prewalk($value); return; } # Handle hard refs if ($type eq 'REF' or $type eq 'SCALAR') { $value = YAML::Type::ref->yaml_dump($value); $self->transferred->{$node_id} = $value; (undef, $type, $node_id) = $self->node_info($value, $stringify); } # Handle ref-to-glob's elsif ($type eq 'GLOB') { my $ref_ynode = $self->transferred->{$node_id} = YAML::Type::ref->yaml_dump($value); my $glob_ynode = $ref_ynode->{&VALUE} = YAML::Type::glob->yaml_dump($$value); (undef, undef, $node_id) = $self->node_info($glob_ynode, $stringify); $self->transferred->{$node_id} = $glob_ynode; $self->_prewalk($glob_ynode); return; } # Increment ref count for node return if ++($self->{id_refcnt}{$node_id}) > 1; # Keep on walking if ($type eq 'HASH') { $self->_prewalk($value->{$_}) for keys %{$value}; return; } elsif ($type eq 'ARRAY') { $self->_prewalk($_) for @{$value}; return; } # Unknown type. Need to know about it. $self->warn(<<"..."); YAML::Dumper can't handle dumping this type of data. Please report this to the author. id: $node_id type: $type class: $class value: $value ... return; } # Every data element and sub data element is a node. # Everything emitted goes through this function. sub _emit_node { my $self = shift; my ($type, $node_id); my $ref = ref($_[0]); if ($ref) { if ($ref eq 'Regexp') { $self->_emit(' !!perl/regexp'); $self->_emit_str("$_[0]"); return; } (undef, $type, $node_id) = $self->node_info($_[0], $self->stringify); } else { $type = $ref || 'SCALAR'; (undef, undef, $node_id) = $self->node_info(\$_[0], $self->stringify); } my ($ynode, $tag) = ('') x 2; my ($value, $context) = (@_, 0); if (defined $self->transferred->{$node_id}) { $value = $self->transferred->{$node_id}; $ynode = ynode($value); if (ref $value) { $tag = defined $ynode ? $ynode->tag->short : ''; (undef, $type, $node_id) = $self->node_info($value, $self->stringify); } else { $ynode = ynode($self->transferred->{$node_id}); $tag = defined $ynode ? $ynode->tag->short : ''; $type = 'SCALAR'; (undef, undef, $node_id) = $self->node_info( \ $self->transferred->{$node_id}, $self->stringify ); } } elsif ($ynode = ynode($value)) { $tag = $ynode->tag->short; } if ($self->use_aliases) { $self->{id_refcnt}{$node_id} ||= 0; if ($self->{id_refcnt}{$node_id} > 1) { if (defined $self->{id_anchor}{$node_id}) { $self->{stream} .= ' *' . $self->{id_anchor}{$node_id} . "\n"; return; } my $anchor = $self->anchor_prefix . $self->{anchor}++; $self->{stream} .= ' &' . $anchor; $self->{id_anchor}{$node_id} = $anchor; } } return $self->_emit_str("$value") # Stringified object if ref($value) and not $type; return $self->_emit_scalar($value, $tag) if $type eq 'SCALAR' and $tag; return $self->_emit_str($value) if $type eq 'SCALAR'; return $self->_emit_mapping($value, $tag, $node_id, $context) if $type eq 'HASH'; return $self->_emit_sequence($value, $tag) if $type eq 'ARRAY'; $self->warn('YAML_DUMP_WARN_BAD_NODE_TYPE', $type); return $self->_emit_str("$value"); } # A YAML mapping is akin to a Perl hash. sub _emit_mapping { my $self = shift; my ($value, $tag, $node_id, $context) = @_; $self->{stream} .= " !$tag" if $tag; # Sometimes 'keys' fails. Like on a bad tie implementation. my $empty_hash = not(eval {keys %$value}); $self->warn('YAML_EMIT_WARN_KEYS', $@) if $@; return ($self->{stream} .= " {}\n") if $empty_hash; # If CompressSeries is on (default) and legal is this context, then # use it and make the indent level be 2 for this node. if ($context == FROMARRAY and $self->compress_series and not (defined $self->{id_anchor}{$node_id} or $tag or $empty_hash) ) { $self->{stream} .= ' '; $self->offset->[$self->level+1] = $self->offset->[$self->level] + 2; } else { $context = 0; $self->{stream} .= "\n" unless $self->headless && not($self->headless(0)); $self->offset->[$self->level+1] = $self->offset->[$self->level] + $self->indent_width; } $self->{level}++; my @keys; if ($self->sort_keys == 1) { if (ynode($value)) { @keys = keys %$value; } else { @keys = sort keys %$value; } } elsif ($self->sort_keys == 2) { @keys = sort keys %$value; } # XXX This is hackish but sometimes handy. Not sure whether to leave it in. elsif (ref($self->sort_keys) eq 'ARRAY') { my $i = 1; my %order = map { ($_, $i++) } @{$self->sort_keys}; @keys = sort { (defined $order{$a} and defined $order{$b}) ? ($order{$a} <=> $order{$b}) : ($a cmp $b); } keys %$value; } else { @keys = keys %$value; } # Force the YAML::VALUE ('=') key to sort last. if (exists $value->{&VALUE}) { for (my $i = 0; $i < @keys; $i++) { if ($keys[$i] eq &VALUE) { splice(@keys, $i, 1); push @keys, &VALUE; last; } } } for my $key (@keys) { $self->_emit_key($key, $context); $context = 0; $self->{stream} .= ':'; $self->_emit_node($value->{$key}); } $self->{level}--; } # A YAML series is akin to a Perl array. sub _emit_sequence { my $self = shift; my ($value, $tag) = @_; $self->{stream} .= " !$tag" if $tag; return ($self->{stream} .= " []\n") if @$value == 0; $self->{stream} .= "\n" unless $self->headless && not($self->headless(0)); # XXX Really crufty feature. Better implemented by ynodes. if ($self->inline_series and @$value <= $self->inline_series and not (scalar grep {ref or /\n/} @$value) ) { $self->{stream} =~ s/\n\Z/ /; $self->{stream} .= '['; for (my $i = 0; $i < @$value; $i++) { $self->_emit_str($value->[$i], KEY); last if $i == $#{$value}; $self->{stream} .= ', '; } $self->{stream} .= "]\n"; return; } $self->offset->[$self->level + 1] = $self->offset->[$self->level] + $self->indent_width; $self->{level}++; for my $val (@$value) { $self->{stream} .= ' ' x $self->offset->[$self->level]; $self->{stream} .= '-'; $self->_emit_node($val, FROMARRAY); } $self->{level}--; } # Emit a mapping key sub _emit_key { my $self = shift; my ($value, $context) = @_; $self->{stream} .= ' ' x $self->offset->[$self->level] unless $context == FROMARRAY; $self->_emit_str($value, KEY); } # Emit a blessed SCALAR sub _emit_scalar { my $self = shift; my ($value, $tag) = @_; $self->{stream} .= " !$tag"; $self->_emit_str($value, BLESSED); } sub _emit { my $self = shift; $self->{stream} .= join '', @_; } # Emit a string value. YAML has many scalar styles. This routine attempts to # guess the best style for the text. sub _emit_str { my $self = shift; my $type = $_[1] || 0; # Use heuristics to find the best scalar emission style. $self->offset->[$self->level + 1] = $self->offset->[$self->level] + $self->indent_width; $self->{level}++; my $sf = $type == KEY ? '' : ' '; my $sb = $type == KEY ? '? ' : ' '; my $ef = $type == KEY ? '' : "\n"; my $eb = "\n"; while (1) { $self->_emit($sf), $self->_emit_plain($_[0]), $self->_emit($ef), last if not defined $_[0]; $self->_emit($sf, '=', $ef), last if $_[0] eq VALUE; $self->_emit($sf), $self->_emit_double($_[0]), $self->_emit($ef), last if $_[0] =~ /$ESCAPE_CHAR/; if ($_[0] =~ /\n/) { $self->_emit($sb), $self->_emit_block($LIT_CHAR, $_[0]), $self->_emit($eb), last if $self->use_block; Carp::cluck "[YAML] \$UseFold is no longer supported" if $self->use_fold; $self->_emit($sf), $self->_emit_double($_[0]), $self->_emit($ef), last if length $_[0] <= 30; $self->_emit($sf), $self->_emit_double($_[0]), $self->_emit($ef), last if $_[0] !~ /\n\s*\S/; $self->_emit($sb), $self->_emit_block($LIT_CHAR, $_[0]), $self->_emit($eb), last; } $self->_emit($sf), $self->_emit_plain($_[0]), $self->_emit($ef), last if $self->is_valid_plain($_[0]); $self->_emit($sf), $self->_emit_double($_[0]), $self->_emit($ef), last if $_[0] =~ /'/; $self->_emit($sf), $self->_emit_single($_[0]), $self->_emit($ef); last; } $self->{level}--; return; } # Check whether or not a scalar should be emitted as an plain scalar. sub is_valid_plain { my $self = shift; return 0 unless length $_[0]; # refer to YAML::Loader::parse_inline_simple() return 0 if $_[0] =~ /^[\s\{\[\~\`\'\"\!\@\#\>\|\%\&\?\*\^]/; return 0 if $_[0] =~ /[\{\[\]\},]/; return 0 if $_[0] =~ /[:\-\?]\s/; return 0 if $_[0] =~ /\s#/; return 0 if $_[0] =~ /\:(\s|$)/; return 0 if $_[0] =~ /[\s\|\>]$/; return 1; } sub _emit_block { my $self = shift; my ($indicator, $value) = @_; $self->{stream} .= $indicator; $value =~ /(\n*)\Z/; my $chomp = length $1 ? (length $1 > 1) ? '+' : '' : '-'; $value = '~' if not defined $value; $self->{stream} .= $chomp; $self->{stream} .= $self->indent_width if $value =~ /^\s/; $self->{stream} .= $self->indent($value); } # Plain means that the scalar is unquoted. sub _emit_plain { my $self = shift; $self->{stream} .= defined $_[0] ? $_[0] : '~'; } # Double quoting is for single lined escaped strings. sub _emit_double { my $self = shift; (my $escaped = $self->escape($_[0])) =~ s/"/\\"/g; $self->{stream} .= qq{"$escaped"}; } # Single quoting is for single lined unescaped strings. sub _emit_single { my $self = shift; my $item = shift; $item =~ s{'}{''}g; $self->{stream} .= "'$item'"; } #============================================================================== # Utility subroutines. #============================================================================== # Indent a scalar to the current indentation level. sub indent { my $self = shift; my ($text) = @_; return $text unless length $text; $text =~ s/\n\Z//; my $indent = ' ' x $self->offset->[$self->level]; $text =~ s/^/$indent/gm; $text = "\n$text"; return $text; } # Escapes for unprintable characters my @escapes = qw(\0 \x01 \x02 \x03 \x04 \x05 \x06 \a \x08 \t \n \v \f \r \x0e \x0f \x10 \x11 \x12 \x13 \x14 \x15 \x16 \x17 \x18 \x19 \x1a \e \x1c \x1d \x1e \x1f ); # Escape the unprintable characters sub escape { my $self = shift; my ($text) = @_; $text =~ s/\\/\\\\/g; $text =~ s/([\x00-\x1f])/$escapes[ord($1)]/ge; return $text; } 1; __END__ =head1 NAME YAML::Dumper - YAML class for dumping Perl objects to YAML =head1 SYNOPSIS use YAML::Dumper; my $dumper = YAML::Dumper->new; $dumper->indent_width(4); print $dumper->dump({foo => 'bar'}); =head1 DESCRIPTION YAML::Dumper is the module that YAML.pm used to serialize Perl objects to YAML. It is fully object oriented and usable on its own. =head1 AUTHOR Ingy döt Net <ingy@cpan.org> =head1 COPYRIGHT Copyright (c) 2006, 2011-2012. Ingy döt Net. All rights reserved. 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> =cut
leighpauls/k2cro4
third_party/perl/perl/vendor/lib/YAML/Dumper.pm
Perl
bsd-3-clause
17,194
# install_check.pl do 'mon-lib.pl'; # is_installed(mode) # For mode 1, returns 2 if the server is installed and configured for use by # Webmin, 1 if installed but not configured, or 0 otherwise. # For mode 0, returns 1 if installed, 0 if not sub is_installed { if (-r $mon_config_file) { return $_[0] ? 2 : 1; } return 0; }
rcuvgd/Webmin22.01.2016
mon/install_check.pl
Perl
bsd-3-clause
329
#!/usr/bin/env perl ############################################################################## # # # Copyright 2014 Intel Corporation # # # # 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. # # # ############################################################################## # # # Developers and authors: # # Shay Gueron (1, 2), and Vlad Krasnov (1) # # (1) Intel Corporation, Israel Development Center # # (2) University of Haifa # # Reference: # # S.Gueron and V.Krasnov, "Fast Prime Field Elliptic Curve Cryptography with# # 256 Bit Primes" # # # ############################################################################## # Further optimization by <appro@openssl.org>: # # this/original with/without -DECP_NISTZ256_ASM(*) # Opteron +12-49% +110-150% # Bulldozer +14-45% +175-210% # P4 +18-46% n/a :-( # Westmere +12-34% +80-87% # Sandy Bridge +9-35% +110-120% # Ivy Bridge +9-35% +110-125% # Haswell +8-37% +140-160% # Broadwell +18-58% +145-210% # Atom +15-50% +130-180% # VIA Nano +43-160% +300-480% # # (*) "without -DECP_NISTZ256_ASM" refers to build with # "enable-ec_nistp_64_gcc_128"; # # Ranges denote minimum and maximum improvement coefficients depending # on benchmark. Lower coefficients are for ECDSA sign, relatively fastest # server-side operation. Keep in mind that +100% means 2x improvement. $flavour = shift; $output = shift; if ($flavour =~ /\./) { $output = $flavour; undef $flavour; } $win64=0; $win64=1 if ($flavour =~ /[nm]asm|mingw64/ || $output =~ /\.asm$/); $0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; ( $xlate="${dir}x86_64-xlate.pl" and -f $xlate ) or ( $xlate="${dir}../../perlasm/x86_64-xlate.pl" and -f $xlate) or die "can't locate x86_64-xlate.pl"; open OUT,"| \"$^X\" $xlate $flavour $output"; *STDOUT=*OUT; if (`$ENV{CC} -Wa,-v -c -o /dev/null -x assembler /dev/null 2>&1` =~ /GNU assembler version ([2-9]\.[0-9]+)/) { $avx = ($1>=2.19) + ($1>=2.22); $addx = ($1>=2.23); } if (!$addx && $win64 && ($flavour =~ /nasm/ || $ENV{ASM} =~ /nasm/) && `nasm -v 2>&1` =~ /NASM version ([2-9]\.[0-9]+)/) { $avx = ($1>=2.09) + ($1>=2.10); $addx = ($1>=2.10); } if (!$addx && $win64 && ($flavour =~ /masm/ || $ENV{ASM} =~ /ml64/) && `ml64 2>&1` =~ /Version ([0-9]+)\./) { $avx = ($1>=10) + ($1>=11); $addx = ($1>=12); } if (!$addx && `$ENV{CC} -v 2>&1` =~ /((?:^clang|LLVM) version|based on LLVM) ([3-9])\.([0-9]+)/) { my $ver = $2 + $3/100.0; # 3.1->3.01, 3.10->3.10 $avx = ($ver>=3.0) + ($ver>=3.01); $addx = ($ver>=3.03); } $code.=<<___; .text .extern OPENSSL_ia32cap_P # The polynomial .align 64 .Lpoly: .quad 0xffffffffffffffff, 0x00000000ffffffff, 0x0000000000000000, 0xffffffff00000001 # 2^512 mod P precomputed for NIST P256 polynomial .LRR: .quad 0x0000000000000003, 0xfffffffbffffffff, 0xfffffffffffffffe, 0x00000004fffffffd .LOne: .long 1,1,1,1,1,1,1,1 .LTwo: .long 2,2,2,2,2,2,2,2 .LThree: .long 3,3,3,3,3,3,3,3 .LONE_mont: .quad 0x0000000000000001, 0xffffffff00000000, 0xffffffffffffffff, 0x00000000fffffffe ___ { ################################################################################ # void ecp_nistz256_mul_by_2(uint64_t res[4], uint64_t a[4]); my ($a0,$a1,$a2,$a3)=map("%r$_",(8..11)); my ($t0,$t1,$t2,$t3,$t4)=("%rax","%rdx","%rcx","%r12","%r13"); my ($r_ptr,$a_ptr,$b_ptr)=("%rdi","%rsi","%rdx"); $code.=<<___; .globl ecp_nistz256_mul_by_2 .type ecp_nistz256_mul_by_2,\@function,2 .align 64 ecp_nistz256_mul_by_2: push %r12 push %r13 mov 8*0($a_ptr), $a0 mov 8*1($a_ptr), $a1 add $a0, $a0 # a0:a3+a0:a3 mov 8*2($a_ptr), $a2 adc $a1, $a1 mov 8*3($a_ptr), $a3 lea .Lpoly(%rip), $a_ptr mov $a0, $t0 adc $a2, $a2 adc $a3, $a3 mov $a1, $t1 sbb $t4, $t4 sub 8*0($a_ptr), $a0 mov $a2, $t2 sbb 8*1($a_ptr), $a1 sbb 8*2($a_ptr), $a2 mov $a3, $t3 sbb 8*3($a_ptr), $a3 test $t4, $t4 cmovz $t0, $a0 cmovz $t1, $a1 mov $a0, 8*0($r_ptr) cmovz $t2, $a2 mov $a1, 8*1($r_ptr) cmovz $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) pop %r13 pop %r12 ret .size ecp_nistz256_mul_by_2,.-ecp_nistz256_mul_by_2 ################################################################################ # void ecp_nistz256_div_by_2(uint64_t res[4], uint64_t a[4]); .globl ecp_nistz256_div_by_2 .type ecp_nistz256_div_by_2,\@function,2 .align 32 ecp_nistz256_div_by_2: push %r12 push %r13 mov 8*0($a_ptr), $a0 mov 8*1($a_ptr), $a1 mov 8*2($a_ptr), $a2 mov $a0, $t0 mov 8*3($a_ptr), $a3 lea .Lpoly(%rip), $a_ptr mov $a1, $t1 xor $t4, $t4 add 8*0($a_ptr), $a0 mov $a2, $t2 adc 8*1($a_ptr), $a1 adc 8*2($a_ptr), $a2 mov $a3, $t3 adc 8*3($a_ptr), $a3 adc \$0, $t4 xor $a_ptr, $a_ptr # borrow $a_ptr test \$1, $t0 cmovz $t0, $a0 cmovz $t1, $a1 cmovz $t2, $a2 cmovz $t3, $a3 cmovz $a_ptr, $t4 mov $a1, $t0 # a0:a3>>1 shr \$1, $a0 shl \$63, $t0 mov $a2, $t1 shr \$1, $a1 or $t0, $a0 shl \$63, $t1 mov $a3, $t2 shr \$1, $a2 or $t1, $a1 shl \$63, $t2 shr \$1, $a3 shl \$63, $t4 or $t2, $a2 or $t4, $a3 mov $a0, 8*0($r_ptr) mov $a1, 8*1($r_ptr) mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) pop %r13 pop %r12 ret .size ecp_nistz256_div_by_2,.-ecp_nistz256_div_by_2 ################################################################################ # void ecp_nistz256_mul_by_3(uint64_t res[4], uint64_t a[4]); .globl ecp_nistz256_mul_by_3 .type ecp_nistz256_mul_by_3,\@function,2 .align 32 ecp_nistz256_mul_by_3: push %r12 push %r13 mov 8*0($a_ptr), $a0 xor $t4, $t4 mov 8*1($a_ptr), $a1 add $a0, $a0 # a0:a3+a0:a3 mov 8*2($a_ptr), $a2 adc $a1, $a1 mov 8*3($a_ptr), $a3 mov $a0, $t0 adc $a2, $a2 adc $a3, $a3 mov $a1, $t1 adc \$0, $t4 sub \$-1, $a0 mov $a2, $t2 sbb .Lpoly+8*1(%rip), $a1 sbb \$0, $a2 mov $a3, $t3 sbb .Lpoly+8*3(%rip), $a3 test $t4, $t4 cmovz $t0, $a0 cmovz $t1, $a1 cmovz $t2, $a2 cmovz $t3, $a3 xor $t4, $t4 add 8*0($a_ptr), $a0 # a0:a3+=a_ptr[0:3] adc 8*1($a_ptr), $a1 mov $a0, $t0 adc 8*2($a_ptr), $a2 adc 8*3($a_ptr), $a3 mov $a1, $t1 adc \$0, $t4 sub \$-1, $a0 mov $a2, $t2 sbb .Lpoly+8*1(%rip), $a1 sbb \$0, $a2 mov $a3, $t3 sbb .Lpoly+8*3(%rip), $a3 test $t4, $t4 cmovz $t0, $a0 cmovz $t1, $a1 mov $a0, 8*0($r_ptr) cmovz $t2, $a2 mov $a1, 8*1($r_ptr) cmovz $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) pop %r13 pop %r12 ret .size ecp_nistz256_mul_by_3,.-ecp_nistz256_mul_by_3 ################################################################################ # void ecp_nistz256_add(uint64_t res[4], uint64_t a[4], uint64_t b[4]); .globl ecp_nistz256_add .type ecp_nistz256_add,\@function,3 .align 32 ecp_nistz256_add: push %r12 push %r13 mov 8*0($a_ptr), $a0 xor $t4, $t4 mov 8*1($a_ptr), $a1 mov 8*2($a_ptr), $a2 mov 8*3($a_ptr), $a3 lea .Lpoly(%rip), $a_ptr add 8*0($b_ptr), $a0 adc 8*1($b_ptr), $a1 mov $a0, $t0 adc 8*2($b_ptr), $a2 adc 8*3($b_ptr), $a3 mov $a1, $t1 adc \$0, $t4 sub 8*0($a_ptr), $a0 mov $a2, $t2 sbb 8*1($a_ptr), $a1 sbb 8*2($a_ptr), $a2 mov $a3, $t3 sbb 8*3($a_ptr), $a3 test $t4, $t4 cmovz $t0, $a0 cmovz $t1, $a1 mov $a0, 8*0($r_ptr) cmovz $t2, $a2 mov $a1, 8*1($r_ptr) cmovz $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) pop %r13 pop %r12 ret .size ecp_nistz256_add,.-ecp_nistz256_add ################################################################################ # void ecp_nistz256_sub(uint64_t res[4], uint64_t a[4], uint64_t b[4]); .globl ecp_nistz256_sub .type ecp_nistz256_sub,\@function,3 .align 32 ecp_nistz256_sub: push %r12 push %r13 mov 8*0($a_ptr), $a0 xor $t4, $t4 mov 8*1($a_ptr), $a1 mov 8*2($a_ptr), $a2 mov 8*3($a_ptr), $a3 lea .Lpoly(%rip), $a_ptr sub 8*0($b_ptr), $a0 sbb 8*1($b_ptr), $a1 mov $a0, $t0 sbb 8*2($b_ptr), $a2 sbb 8*3($b_ptr), $a3 mov $a1, $t1 sbb \$0, $t4 add 8*0($a_ptr), $a0 mov $a2, $t2 adc 8*1($a_ptr), $a1 adc 8*2($a_ptr), $a2 mov $a3, $t3 adc 8*3($a_ptr), $a3 test $t4, $t4 cmovz $t0, $a0 cmovz $t1, $a1 mov $a0, 8*0($r_ptr) cmovz $t2, $a2 mov $a1, 8*1($r_ptr) cmovz $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) pop %r13 pop %r12 ret .size ecp_nistz256_sub,.-ecp_nistz256_sub ################################################################################ # void ecp_nistz256_neg(uint64_t res[4], uint64_t a[4]); .globl ecp_nistz256_neg .type ecp_nistz256_neg,\@function,2 .align 32 ecp_nistz256_neg: push %r12 push %r13 xor $a0, $a0 xor $a1, $a1 xor $a2, $a2 xor $a3, $a3 xor $t4, $t4 sub 8*0($a_ptr), $a0 sbb 8*1($a_ptr), $a1 sbb 8*2($a_ptr), $a2 mov $a0, $t0 sbb 8*3($a_ptr), $a3 lea .Lpoly(%rip), $a_ptr mov $a1, $t1 sbb \$0, $t4 add 8*0($a_ptr), $a0 mov $a2, $t2 adc 8*1($a_ptr), $a1 adc 8*2($a_ptr), $a2 mov $a3, $t3 adc 8*3($a_ptr), $a3 test $t4, $t4 cmovz $t0, $a0 cmovz $t1, $a1 mov $a0, 8*0($r_ptr) cmovz $t2, $a2 mov $a1, 8*1($r_ptr) cmovz $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) pop %r13 pop %r12 ret .size ecp_nistz256_neg,.-ecp_nistz256_neg ___ } { my ($r_ptr,$a_ptr,$b_org,$b_ptr)=("%rdi","%rsi","%rdx","%rbx"); my ($acc0,$acc1,$acc2,$acc3,$acc4,$acc5,$acc6,$acc7)=map("%r$_",(8..15)); my ($t0,$t1,$t2,$t3,$t4)=("%rcx","%rbp","%rbx","%rdx","%rax"); my ($poly1,$poly3)=($acc6,$acc7); $code.=<<___; ################################################################################ # void ecp_nistz256_to_mont( # uint64_t res[4], # uint64_t in[4]); .globl ecp_nistz256_to_mont .type ecp_nistz256_to_mont,\@function,2 .align 32 ecp_nistz256_to_mont: ___ $code.=<<___ if ($addx); mov \$0x80100, %ecx and OPENSSL_ia32cap_P+8(%rip), %ecx ___ $code.=<<___; lea .LRR(%rip), $b_org jmp .Lmul_mont .size ecp_nistz256_to_mont,.-ecp_nistz256_to_mont ################################################################################ # void ecp_nistz256_mul_mont( # uint64_t res[4], # uint64_t a[4], # uint64_t b[4]); .globl ecp_nistz256_mul_mont .type ecp_nistz256_mul_mont,\@function,3 .align 32 ecp_nistz256_mul_mont: ___ $code.=<<___ if ($addx); mov \$0x80100, %ecx and OPENSSL_ia32cap_P+8(%rip), %ecx ___ $code.=<<___; .Lmul_mont: push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 ___ $code.=<<___ if ($addx); cmp \$0x80100, %ecx je .Lmul_montx ___ $code.=<<___; mov $b_org, $b_ptr mov 8*0($b_org), %rax mov 8*0($a_ptr), $acc1 mov 8*1($a_ptr), $acc2 mov 8*2($a_ptr), $acc3 mov 8*3($a_ptr), $acc4 call __ecp_nistz256_mul_montq ___ $code.=<<___ if ($addx); jmp .Lmul_mont_done .align 32 .Lmul_montx: mov $b_org, $b_ptr mov 8*0($b_org), %rdx mov 8*0($a_ptr), $acc1 mov 8*1($a_ptr), $acc2 mov 8*2($a_ptr), $acc3 mov 8*3($a_ptr), $acc4 lea -128($a_ptr), $a_ptr # control u-op density call __ecp_nistz256_mul_montx ___ $code.=<<___; .Lmul_mont_done: pop %r15 pop %r14 pop %r13 pop %r12 pop %rbx pop %rbp ret .size ecp_nistz256_mul_mont,.-ecp_nistz256_mul_mont .type __ecp_nistz256_mul_montq,\@abi-omnipotent .align 32 __ecp_nistz256_mul_montq: ######################################################################## # Multiply a by b[0] mov %rax, $t1 mulq $acc1 mov .Lpoly+8*1(%rip),$poly1 mov %rax, $acc0 mov $t1, %rax mov %rdx, $acc1 mulq $acc2 mov .Lpoly+8*3(%rip),$poly3 add %rax, $acc1 mov $t1, %rax adc \$0, %rdx mov %rdx, $acc2 mulq $acc3 add %rax, $acc2 mov $t1, %rax adc \$0, %rdx mov %rdx, $acc3 mulq $acc4 add %rax, $acc3 mov $acc0, %rax adc \$0, %rdx xor $acc5, $acc5 mov %rdx, $acc4 ######################################################################## # First reduction step # Basically now we want to multiply acc[0] by p256, # and add the result to the acc. # Due to the special form of p256 we do some optimizations # # acc[0] x p256[0..1] = acc[0] x 2^96 - acc[0] # then we add acc[0] and get acc[0] x 2^96 mov $acc0, $t1 shl \$32, $acc0 mulq $poly3 shr \$32, $t1 add $acc0, $acc1 # +=acc[0]<<96 adc $t1, $acc2 adc %rax, $acc3 mov 8*1($b_ptr), %rax adc %rdx, $acc4 adc \$0, $acc5 xor $acc0, $acc0 ######################################################################## # Multiply by b[1] mov %rax, $t1 mulq 8*0($a_ptr) add %rax, $acc1 mov $t1, %rax adc \$0, %rdx mov %rdx, $t0 mulq 8*1($a_ptr) add $t0, $acc2 adc \$0, %rdx add %rax, $acc2 mov $t1, %rax adc \$0, %rdx mov %rdx, $t0 mulq 8*2($a_ptr) add $t0, $acc3 adc \$0, %rdx add %rax, $acc3 mov $t1, %rax adc \$0, %rdx mov %rdx, $t0 mulq 8*3($a_ptr) add $t0, $acc4 adc \$0, %rdx add %rax, $acc4 mov $acc1, %rax adc %rdx, $acc5 adc \$0, $acc0 ######################################################################## # Second reduction step mov $acc1, $t1 shl \$32, $acc1 mulq $poly3 shr \$32, $t1 add $acc1, $acc2 adc $t1, $acc3 adc %rax, $acc4 mov 8*2($b_ptr), %rax adc %rdx, $acc5 adc \$0, $acc0 xor $acc1, $acc1 ######################################################################## # Multiply by b[2] mov %rax, $t1 mulq 8*0($a_ptr) add %rax, $acc2 mov $t1, %rax adc \$0, %rdx mov %rdx, $t0 mulq 8*1($a_ptr) add $t0, $acc3 adc \$0, %rdx add %rax, $acc3 mov $t1, %rax adc \$0, %rdx mov %rdx, $t0 mulq 8*2($a_ptr) add $t0, $acc4 adc \$0, %rdx add %rax, $acc4 mov $t1, %rax adc \$0, %rdx mov %rdx, $t0 mulq 8*3($a_ptr) add $t0, $acc5 adc \$0, %rdx add %rax, $acc5 mov $acc2, %rax adc %rdx, $acc0 adc \$0, $acc1 ######################################################################## # Third reduction step mov $acc2, $t1 shl \$32, $acc2 mulq $poly3 shr \$32, $t1 add $acc2, $acc3 adc $t1, $acc4 adc %rax, $acc5 mov 8*3($b_ptr), %rax adc %rdx, $acc0 adc \$0, $acc1 xor $acc2, $acc2 ######################################################################## # Multiply by b[3] mov %rax, $t1 mulq 8*0($a_ptr) add %rax, $acc3 mov $t1, %rax adc \$0, %rdx mov %rdx, $t0 mulq 8*1($a_ptr) add $t0, $acc4 adc \$0, %rdx add %rax, $acc4 mov $t1, %rax adc \$0, %rdx mov %rdx, $t0 mulq 8*2($a_ptr) add $t0, $acc5 adc \$0, %rdx add %rax, $acc5 mov $t1, %rax adc \$0, %rdx mov %rdx, $t0 mulq 8*3($a_ptr) add $t0, $acc0 adc \$0, %rdx add %rax, $acc0 mov $acc3, %rax adc %rdx, $acc1 adc \$0, $acc2 ######################################################################## # Final reduction step mov $acc3, $t1 shl \$32, $acc3 mulq $poly3 shr \$32, $t1 add $acc3, $acc4 adc $t1, $acc5 mov $acc4, $t0 adc %rax, $acc0 adc %rdx, $acc1 mov $acc5, $t1 adc \$0, $acc2 ######################################################################## # Branch-less conditional subtraction of P sub \$-1, $acc4 # .Lpoly[0] mov $acc0, $t2 sbb $poly1, $acc5 # .Lpoly[1] sbb \$0, $acc0 # .Lpoly[2] mov $acc1, $t3 sbb $poly3, $acc1 # .Lpoly[3] sbb \$0, $acc2 cmovc $t0, $acc4 cmovc $t1, $acc5 mov $acc4, 8*0($r_ptr) cmovc $t2, $acc0 mov $acc5, 8*1($r_ptr) cmovc $t3, $acc1 mov $acc0, 8*2($r_ptr) mov $acc1, 8*3($r_ptr) ret .size __ecp_nistz256_mul_montq,.-__ecp_nistz256_mul_montq ################################################################################ # void ecp_nistz256_sqr_mont( # uint64_t res[4], # uint64_t a[4]); # we optimize the square according to S.Gueron and V.Krasnov, # "Speeding up Big-Number Squaring" .globl ecp_nistz256_sqr_mont .type ecp_nistz256_sqr_mont,\@function,2 .align 32 ecp_nistz256_sqr_mont: ___ $code.=<<___ if ($addx); mov \$0x80100, %ecx and OPENSSL_ia32cap_P+8(%rip), %ecx ___ $code.=<<___; push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 ___ $code.=<<___ if ($addx); cmp \$0x80100, %ecx je .Lsqr_montx ___ $code.=<<___; mov 8*0($a_ptr), %rax mov 8*1($a_ptr), $acc6 mov 8*2($a_ptr), $acc7 mov 8*3($a_ptr), $acc0 call __ecp_nistz256_sqr_montq ___ $code.=<<___ if ($addx); jmp .Lsqr_mont_done .align 32 .Lsqr_montx: mov 8*0($a_ptr), %rdx mov 8*1($a_ptr), $acc6 mov 8*2($a_ptr), $acc7 mov 8*3($a_ptr), $acc0 lea -128($a_ptr), $a_ptr # control u-op density call __ecp_nistz256_sqr_montx ___ $code.=<<___; .Lsqr_mont_done: pop %r15 pop %r14 pop %r13 pop %r12 pop %rbx pop %rbp ret .size ecp_nistz256_sqr_mont,.-ecp_nistz256_sqr_mont .type __ecp_nistz256_sqr_montq,\@abi-omnipotent .align 32 __ecp_nistz256_sqr_montq: mov %rax, $acc5 mulq $acc6 # a[1]*a[0] mov %rax, $acc1 mov $acc7, %rax mov %rdx, $acc2 mulq $acc5 # a[0]*a[2] add %rax, $acc2 mov $acc0, %rax adc \$0, %rdx mov %rdx, $acc3 mulq $acc5 # a[0]*a[3] add %rax, $acc3 mov $acc7, %rax adc \$0, %rdx mov %rdx, $acc4 ################################# mulq $acc6 # a[1]*a[2] add %rax, $acc3 mov $acc0, %rax adc \$0, %rdx mov %rdx, $t1 mulq $acc6 # a[1]*a[3] add %rax, $acc4 mov $acc0, %rax adc \$0, %rdx add $t1, $acc4 mov %rdx, $acc5 adc \$0, $acc5 ################################# mulq $acc7 # a[2]*a[3] xor $acc7, $acc7 add %rax, $acc5 mov 8*0($a_ptr), %rax mov %rdx, $acc6 adc \$0, $acc6 add $acc1, $acc1 # acc1:6<<1 adc $acc2, $acc2 adc $acc3, $acc3 adc $acc4, $acc4 adc $acc5, $acc5 adc $acc6, $acc6 adc \$0, $acc7 mulq %rax mov %rax, $acc0 mov 8*1($a_ptr), %rax mov %rdx, $t0 mulq %rax add $t0, $acc1 adc %rax, $acc2 mov 8*2($a_ptr), %rax adc \$0, %rdx mov %rdx, $t0 mulq %rax add $t0, $acc3 adc %rax, $acc4 mov 8*3($a_ptr), %rax adc \$0, %rdx mov %rdx, $t0 mulq %rax add $t0, $acc5 adc %rax, $acc6 mov $acc0, %rax adc %rdx, $acc7 mov .Lpoly+8*1(%rip), $a_ptr mov .Lpoly+8*3(%rip), $t1 ########################################## # Now the reduction # First iteration mov $acc0, $t0 shl \$32, $acc0 mulq $t1 shr \$32, $t0 add $acc0, $acc1 # +=acc[0]<<96 adc $t0, $acc2 adc %rax, $acc3 mov $acc1, %rax adc \$0, %rdx ########################################## # Second iteration mov $acc1, $t0 shl \$32, $acc1 mov %rdx, $acc0 mulq $t1 shr \$32, $t0 add $acc1, $acc2 adc $t0, $acc3 adc %rax, $acc0 mov $acc2, %rax adc \$0, %rdx ########################################## # Third iteration mov $acc2, $t0 shl \$32, $acc2 mov %rdx, $acc1 mulq $t1 shr \$32, $t0 add $acc2, $acc3 adc $t0, $acc0 adc %rax, $acc1 mov $acc3, %rax adc \$0, %rdx ########################################### # Last iteration mov $acc3, $t0 shl \$32, $acc3 mov %rdx, $acc2 mulq $t1 shr \$32, $t0 add $acc3, $acc0 adc $t0, $acc1 adc %rax, $acc2 adc \$0, %rdx xor $acc3, $acc3 ############################################ # Add the rest of the acc add $acc0, $acc4 adc $acc1, $acc5 mov $acc4, $acc0 adc $acc2, $acc6 adc %rdx, $acc7 mov $acc5, $acc1 adc \$0, $acc3 sub \$-1, $acc4 # .Lpoly[0] mov $acc6, $acc2 sbb $a_ptr, $acc5 # .Lpoly[1] sbb \$0, $acc6 # .Lpoly[2] mov $acc7, $t0 sbb $t1, $acc7 # .Lpoly[3] sbb \$0, $acc3 cmovc $acc0, $acc4 cmovc $acc1, $acc5 mov $acc4, 8*0($r_ptr) cmovc $acc2, $acc6 mov $acc5, 8*1($r_ptr) cmovc $t0, $acc7 mov $acc6, 8*2($r_ptr) mov $acc7, 8*3($r_ptr) ret .size __ecp_nistz256_sqr_montq,.-__ecp_nistz256_sqr_montq ___ if ($addx) { $code.=<<___; .type __ecp_nistz256_mul_montx,\@abi-omnipotent .align 32 __ecp_nistz256_mul_montx: ######################################################################## # Multiply by b[0] mulx $acc1, $acc0, $acc1 mulx $acc2, $t0, $acc2 mov \$32, $poly1 xor $acc5, $acc5 # cf=0 mulx $acc3, $t1, $acc3 mov .Lpoly+8*3(%rip), $poly3 adc $t0, $acc1 mulx $acc4, $t0, $acc4 mov $acc0, %rdx adc $t1, $acc2 shlx $poly1,$acc0,$t1 adc $t0, $acc3 shrx $poly1,$acc0,$t0 adc \$0, $acc4 ######################################################################## # First reduction step add $t1, $acc1 adc $t0, $acc2 mulx $poly3, $t0, $t1 mov 8*1($b_ptr), %rdx adc $t0, $acc3 adc $t1, $acc4 adc \$0, $acc5 xor $acc0, $acc0 # $acc0=0,cf=0,of=0 ######################################################################## # Multiply by b[1] mulx 8*0+128($a_ptr), $t0, $t1 adcx $t0, $acc1 adox $t1, $acc2 mulx 8*1+128($a_ptr), $t0, $t1 adcx $t0, $acc2 adox $t1, $acc3 mulx 8*2+128($a_ptr), $t0, $t1 adcx $t0, $acc3 adox $t1, $acc4 mulx 8*3+128($a_ptr), $t0, $t1 mov $acc1, %rdx adcx $t0, $acc4 shlx $poly1, $acc1, $t0 adox $t1, $acc5 shrx $poly1, $acc1, $t1 adcx $acc0, $acc5 adox $acc0, $acc0 adc \$0, $acc0 ######################################################################## # Second reduction step add $t0, $acc2 adc $t1, $acc3 mulx $poly3, $t0, $t1 mov 8*2($b_ptr), %rdx adc $t0, $acc4 adc $t1, $acc5 adc \$0, $acc0 xor $acc1 ,$acc1 # $acc1=0,cf=0,of=0 ######################################################################## # Multiply by b[2] mulx 8*0+128($a_ptr), $t0, $t1 adcx $t0, $acc2 adox $t1, $acc3 mulx 8*1+128($a_ptr), $t0, $t1 adcx $t0, $acc3 adox $t1, $acc4 mulx 8*2+128($a_ptr), $t0, $t1 adcx $t0, $acc4 adox $t1, $acc5 mulx 8*3+128($a_ptr), $t0, $t1 mov $acc2, %rdx adcx $t0, $acc5 shlx $poly1, $acc2, $t0 adox $t1, $acc0 shrx $poly1, $acc2, $t1 adcx $acc1, $acc0 adox $acc1, $acc1 adc \$0, $acc1 ######################################################################## # Third reduction step add $t0, $acc3 adc $t1, $acc4 mulx $poly3, $t0, $t1 mov 8*3($b_ptr), %rdx adc $t0, $acc5 adc $t1, $acc0 adc \$0, $acc1 xor $acc2, $acc2 # $acc2=0,cf=0,of=0 ######################################################################## # Multiply by b[3] mulx 8*0+128($a_ptr), $t0, $t1 adcx $t0, $acc3 adox $t1, $acc4 mulx 8*1+128($a_ptr), $t0, $t1 adcx $t0, $acc4 adox $t1, $acc5 mulx 8*2+128($a_ptr), $t0, $t1 adcx $t0, $acc5 adox $t1, $acc0 mulx 8*3+128($a_ptr), $t0, $t1 mov $acc3, %rdx adcx $t0, $acc0 shlx $poly1, $acc3, $t0 adox $t1, $acc1 shrx $poly1, $acc3, $t1 adcx $acc2, $acc1 adox $acc2, $acc2 adc \$0, $acc2 ######################################################################## # Fourth reduction step add $t0, $acc4 adc $t1, $acc5 mulx $poly3, $t0, $t1 mov $acc4, $t2 mov .Lpoly+8*1(%rip), $poly1 adc $t0, $acc0 mov $acc5, $t3 adc $t1, $acc1 adc \$0, $acc2 ######################################################################## # Branch-less conditional subtraction of P xor %eax, %eax mov $acc0, $t0 sbb \$-1, $acc4 # .Lpoly[0] sbb $poly1, $acc5 # .Lpoly[1] sbb \$0, $acc0 # .Lpoly[2] mov $acc1, $t1 sbb $poly3, $acc1 # .Lpoly[3] sbb \$0, $acc2 cmovc $t2, $acc4 cmovc $t3, $acc5 mov $acc4, 8*0($r_ptr) cmovc $t0, $acc0 mov $acc5, 8*1($r_ptr) cmovc $t1, $acc1 mov $acc0, 8*2($r_ptr) mov $acc1, 8*3($r_ptr) ret .size __ecp_nistz256_mul_montx,.-__ecp_nistz256_mul_montx .type __ecp_nistz256_sqr_montx,\@abi-omnipotent .align 32 __ecp_nistz256_sqr_montx: mulx $acc6, $acc1, $acc2 # a[0]*a[1] mulx $acc7, $t0, $acc3 # a[0]*a[2] xor %eax, %eax adc $t0, $acc2 mulx $acc0, $t1, $acc4 # a[0]*a[3] mov $acc6, %rdx adc $t1, $acc3 adc \$0, $acc4 xor $acc5, $acc5 # $acc5=0,cf=0,of=0 ################################# mulx $acc7, $t0, $t1 # a[1]*a[2] adcx $t0, $acc3 adox $t1, $acc4 mulx $acc0, $t0, $t1 # a[1]*a[3] mov $acc7, %rdx adcx $t0, $acc4 adox $t1, $acc5 adc \$0, $acc5 ################################# mulx $acc0, $t0, $acc6 # a[2]*a[3] mov 8*0+128($a_ptr), %rdx xor $acc7, $acc7 # $acc7=0,cf=0,of=0 adcx $acc1, $acc1 # acc1:6<<1 adox $t0, $acc5 adcx $acc2, $acc2 adox $acc7, $acc6 # of=0 mulx %rdx, $acc0, $t1 mov 8*1+128($a_ptr), %rdx adcx $acc3, $acc3 adox $t1, $acc1 adcx $acc4, $acc4 mulx %rdx, $t0, $t4 mov 8*2+128($a_ptr), %rdx adcx $acc5, $acc5 adox $t0, $acc2 adcx $acc6, $acc6 .byte 0x67 mulx %rdx, $t0, $t1 mov 8*3+128($a_ptr), %rdx adox $t4, $acc3 adcx $acc7, $acc7 adox $t0, $acc4 mov \$32, $a_ptr adox $t1, $acc5 .byte 0x67,0x67 mulx %rdx, $t0, $t4 mov $acc0, %rdx adox $t0, $acc6 shlx $a_ptr, $acc0, $t0 adox $t4, $acc7 shrx $a_ptr, $acc0, $t4 mov .Lpoly+8*3(%rip), $t1 # reduction step 1 add $t0, $acc1 adc $t4, $acc2 mulx $t1, $t0, $acc0 mov $acc1, %rdx adc $t0, $acc3 shlx $a_ptr, $acc1, $t0 adc \$0, $acc0 shrx $a_ptr, $acc1, $t4 # reduction step 2 add $t0, $acc2 adc $t4, $acc3 mulx $t1, $t0, $acc1 mov $acc2, %rdx adc $t0, $acc0 shlx $a_ptr, $acc2, $t0 adc \$0, $acc1 shrx $a_ptr, $acc2, $t4 # reduction step 3 add $t0, $acc3 adc $t4, $acc0 mulx $t1, $t0, $acc2 mov $acc3, %rdx adc $t0, $acc1 shlx $a_ptr, $acc3, $t0 adc \$0, $acc2 shrx $a_ptr, $acc3, $t4 # reduction step 4 add $t0, $acc0 adc $t4, $acc1 mulx $t1, $t0, $acc3 adc $t0, $acc2 adc \$0, $acc3 xor $t3, $t3 # cf=0 adc $acc0, $acc4 # accumulate upper half mov .Lpoly+8*1(%rip), $a_ptr adc $acc1, $acc5 mov $acc4, $acc0 adc $acc2, $acc6 adc $acc3, $acc7 mov $acc5, $acc1 adc \$0, $t3 xor %eax, %eax # cf=0 sbb \$-1, $acc4 # .Lpoly[0] mov $acc6, $acc2 sbb $a_ptr, $acc5 # .Lpoly[1] sbb \$0, $acc6 # .Lpoly[2] mov $acc7, $acc3 sbb $t1, $acc7 # .Lpoly[3] sbb \$0, $t3 cmovc $acc0, $acc4 cmovc $acc1, $acc5 mov $acc4, 8*0($r_ptr) cmovc $acc2, $acc6 mov $acc5, 8*1($r_ptr) cmovc $acc3, $acc7 mov $acc6, 8*2($r_ptr) mov $acc7, 8*3($r_ptr) ret .size __ecp_nistz256_sqr_montx,.-__ecp_nistz256_sqr_montx ___ } } { my ($r_ptr,$in_ptr)=("%rdi","%rsi"); my ($acc0,$acc1,$acc2,$acc3)=map("%r$_",(8..11)); my ($t0,$t1,$t2)=("%rcx","%r12","%r13"); $code.=<<___; ################################################################################ # void ecp_nistz256_from_mont( # uint64_t res[4], # uint64_t in[4]); # This one performs Montgomery multiplication by 1, so we only need the reduction .globl ecp_nistz256_from_mont .type ecp_nistz256_from_mont,\@function,2 .align 32 ecp_nistz256_from_mont: push %r12 push %r13 mov 8*0($in_ptr), %rax mov .Lpoly+8*3(%rip), $t2 mov 8*1($in_ptr), $acc1 mov 8*2($in_ptr), $acc2 mov 8*3($in_ptr), $acc3 mov %rax, $acc0 mov .Lpoly+8*1(%rip), $t1 ######################################### # First iteration mov %rax, $t0 shl \$32, $acc0 mulq $t2 shr \$32, $t0 add $acc0, $acc1 adc $t0, $acc2 adc %rax, $acc3 mov $acc1, %rax adc \$0, %rdx ######################################### # Second iteration mov $acc1, $t0 shl \$32, $acc1 mov %rdx, $acc0 mulq $t2 shr \$32, $t0 add $acc1, $acc2 adc $t0, $acc3 adc %rax, $acc0 mov $acc2, %rax adc \$0, %rdx ########################################## # Third iteration mov $acc2, $t0 shl \$32, $acc2 mov %rdx, $acc1 mulq $t2 shr \$32, $t0 add $acc2, $acc3 adc $t0, $acc0 adc %rax, $acc1 mov $acc3, %rax adc \$0, %rdx ########################################### # Last iteration mov $acc3, $t0 shl \$32, $acc3 mov %rdx, $acc2 mulq $t2 shr \$32, $t0 add $acc3, $acc0 adc $t0, $acc1 mov $acc0, $t0 adc %rax, $acc2 mov $acc1, $in_ptr adc \$0, %rdx ########################################### # Branch-less conditional subtraction sub \$-1, $acc0 mov $acc2, %rax sbb $t1, $acc1 sbb \$0, $acc2 mov %rdx, $acc3 sbb $t2, %rdx sbb $t2, $t2 cmovnz $t0, $acc0 cmovnz $in_ptr, $acc1 mov $acc0, 8*0($r_ptr) cmovnz %rax, $acc2 mov $acc1, 8*1($r_ptr) cmovz %rdx, $acc3 mov $acc2, 8*2($r_ptr) mov $acc3, 8*3($r_ptr) pop %r13 pop %r12 ret .size ecp_nistz256_from_mont,.-ecp_nistz256_from_mont ___ } { my ($val,$in_t,$index)=$win64?("%rcx","%rdx","%r8d"):("%rdi","%rsi","%edx"); my ($ONE,$INDEX,$Ra,$Rb,$Rc,$Rd,$Re,$Rf)=map("%xmm$_",(0..7)); my ($M0,$T0a,$T0b,$T0c,$T0d,$T0e,$T0f,$TMP0)=map("%xmm$_",(8..15)); my ($M1,$T2a,$T2b,$TMP2,$M2,$T2a,$T2b,$TMP2)=map("%xmm$_",(8..15)); $code.=<<___; ################################################################################ # void ecp_nistz256_select_w5(uint64_t *val, uint64_t *in_t, int index); .globl ecp_nistz256_select_w5 .type ecp_nistz256_select_w5,\@abi-omnipotent .align 32 ecp_nistz256_select_w5: ___ $code.=<<___ if ($avx>1); mov OPENSSL_ia32cap_P+8(%rip), %eax test \$`1<<5`, %eax jnz .Lavx2_select_w5 ___ $code.=<<___ if ($win64); lea -0x88(%rsp), %rax .LSEH_begin_ecp_nistz256_select_w5: .byte 0x48,0x8d,0x60,0xe0 #lea -0x20(%rax), %rsp .byte 0x0f,0x29,0x70,0xe0 #movaps %xmm6, -0x20(%rax) .byte 0x0f,0x29,0x78,0xf0 #movaps %xmm7, -0x10(%rax) .byte 0x44,0x0f,0x29,0x00 #movaps %xmm8, 0(%rax) .byte 0x44,0x0f,0x29,0x48,0x10 #movaps %xmm9, 0x10(%rax) .byte 0x44,0x0f,0x29,0x50,0x20 #movaps %xmm10, 0x20(%rax) .byte 0x44,0x0f,0x29,0x58,0x30 #movaps %xmm11, 0x30(%rax) .byte 0x44,0x0f,0x29,0x60,0x40 #movaps %xmm12, 0x40(%rax) .byte 0x44,0x0f,0x29,0x68,0x50 #movaps %xmm13, 0x50(%rax) .byte 0x44,0x0f,0x29,0x70,0x60 #movaps %xmm14, 0x60(%rax) .byte 0x44,0x0f,0x29,0x78,0x70 #movaps %xmm15, 0x70(%rax) ___ $code.=<<___; movdqa .LOne(%rip), $ONE movd $index, $INDEX pxor $Ra, $Ra pxor $Rb, $Rb pxor $Rc, $Rc pxor $Rd, $Rd pxor $Re, $Re pxor $Rf, $Rf movdqa $ONE, $M0 pshufd \$0, $INDEX, $INDEX mov \$16, %rax .Lselect_loop_sse_w5: movdqa $M0, $TMP0 paddd $ONE, $M0 pcmpeqd $INDEX, $TMP0 movdqa 16*0($in_t), $T0a movdqa 16*1($in_t), $T0b movdqa 16*2($in_t), $T0c movdqa 16*3($in_t), $T0d movdqa 16*4($in_t), $T0e movdqa 16*5($in_t), $T0f lea 16*6($in_t), $in_t pand $TMP0, $T0a pand $TMP0, $T0b por $T0a, $Ra pand $TMP0, $T0c por $T0b, $Rb pand $TMP0, $T0d por $T0c, $Rc pand $TMP0, $T0e por $T0d, $Rd pand $TMP0, $T0f por $T0e, $Re por $T0f, $Rf dec %rax jnz .Lselect_loop_sse_w5 movdqu $Ra, 16*0($val) movdqu $Rb, 16*1($val) movdqu $Rc, 16*2($val) movdqu $Rd, 16*3($val) movdqu $Re, 16*4($val) movdqu $Rf, 16*5($val) ___ $code.=<<___ if ($win64); movaps (%rsp), %xmm6 movaps 0x10(%rsp), %xmm7 movaps 0x20(%rsp), %xmm8 movaps 0x30(%rsp), %xmm9 movaps 0x40(%rsp), %xmm10 movaps 0x50(%rsp), %xmm11 movaps 0x60(%rsp), %xmm12 movaps 0x70(%rsp), %xmm13 movaps 0x80(%rsp), %xmm14 movaps 0x90(%rsp), %xmm15 lea 0xa8(%rsp), %rsp .LSEH_end_ecp_nistz256_select_w5: ___ $code.=<<___; ret .size ecp_nistz256_select_w5,.-ecp_nistz256_select_w5 ################################################################################ # void ecp_nistz256_select_w7(uint64_t *val, uint64_t *in_t, int index); .globl ecp_nistz256_select_w7 .type ecp_nistz256_select_w7,\@abi-omnipotent .align 32 ecp_nistz256_select_w7: ___ $code.=<<___ if ($avx>1); mov OPENSSL_ia32cap_P+8(%rip), %eax test \$`1<<5`, %eax jnz .Lavx2_select_w7 ___ $code.=<<___ if ($win64); lea -0x88(%rsp), %rax .LSEH_begin_ecp_nistz256_select_w7: .byte 0x48,0x8d,0x60,0xe0 #lea -0x20(%rax), %rsp .byte 0x0f,0x29,0x70,0xe0 #movaps %xmm6, -0x20(%rax) .byte 0x0f,0x29,0x78,0xf0 #movaps %xmm7, -0x10(%rax) .byte 0x44,0x0f,0x29,0x00 #movaps %xmm8, 0(%rax) .byte 0x44,0x0f,0x29,0x48,0x10 #movaps %xmm9, 0x10(%rax) .byte 0x44,0x0f,0x29,0x50,0x20 #movaps %xmm10, 0x20(%rax) .byte 0x44,0x0f,0x29,0x58,0x30 #movaps %xmm11, 0x30(%rax) .byte 0x44,0x0f,0x29,0x60,0x40 #movaps %xmm12, 0x40(%rax) .byte 0x44,0x0f,0x29,0x68,0x50 #movaps %xmm13, 0x50(%rax) .byte 0x44,0x0f,0x29,0x70,0x60 #movaps %xmm14, 0x60(%rax) .byte 0x44,0x0f,0x29,0x78,0x70 #movaps %xmm15, 0x70(%rax) ___ $code.=<<___; movdqa .LOne(%rip), $M0 movd $index, $INDEX pxor $Ra, $Ra pxor $Rb, $Rb pxor $Rc, $Rc pxor $Rd, $Rd movdqa $M0, $ONE pshufd \$0, $INDEX, $INDEX mov \$64, %rax .Lselect_loop_sse_w7: movdqa $M0, $TMP0 paddd $ONE, $M0 movdqa 16*0($in_t), $T0a movdqa 16*1($in_t), $T0b pcmpeqd $INDEX, $TMP0 movdqa 16*2($in_t), $T0c movdqa 16*3($in_t), $T0d lea 16*4($in_t), $in_t pand $TMP0, $T0a pand $TMP0, $T0b por $T0a, $Ra pand $TMP0, $T0c por $T0b, $Rb pand $TMP0, $T0d por $T0c, $Rc prefetcht0 255($in_t) por $T0d, $Rd dec %rax jnz .Lselect_loop_sse_w7 movdqu $Ra, 16*0($val) movdqu $Rb, 16*1($val) movdqu $Rc, 16*2($val) movdqu $Rd, 16*3($val) ___ $code.=<<___ if ($win64); movaps (%rsp), %xmm6 movaps 0x10(%rsp), %xmm7 movaps 0x20(%rsp), %xmm8 movaps 0x30(%rsp), %xmm9 movaps 0x40(%rsp), %xmm10 movaps 0x50(%rsp), %xmm11 movaps 0x60(%rsp), %xmm12 movaps 0x70(%rsp), %xmm13 movaps 0x80(%rsp), %xmm14 movaps 0x90(%rsp), %xmm15 lea 0xa8(%rsp), %rsp .LSEH_end_ecp_nistz256_select_w7: ___ $code.=<<___; ret .size ecp_nistz256_select_w7,.-ecp_nistz256_select_w7 ___ } if ($avx>1) { my ($val,$in_t,$index)=$win64?("%rcx","%rdx","%r8d"):("%rdi","%rsi","%edx"); my ($TWO,$INDEX,$Ra,$Rb,$Rc)=map("%ymm$_",(0..4)); my ($M0,$T0a,$T0b,$T0c,$TMP0)=map("%ymm$_",(5..9)); my ($M1,$T1a,$T1b,$T1c,$TMP1)=map("%ymm$_",(10..14)); $code.=<<___; ################################################################################ # void ecp_nistz256_avx2_select_w5(uint64_t *val, uint64_t *in_t, int index); .type ecp_nistz256_avx2_select_w5,\@abi-omnipotent .align 32 ecp_nistz256_avx2_select_w5: .Lavx2_select_w5: vzeroupper ___ $code.=<<___ if ($win64); lea -0x88(%rsp), %rax .LSEH_begin_ecp_nistz256_avx2_select_w5: .byte 0x48,0x8d,0x60,0xe0 #lea -0x20(%rax), %rsp .byte 0xc5,0xf8,0x29,0x70,0xe0 #vmovaps %xmm6, -0x20(%rax) .byte 0xc5,0xf8,0x29,0x78,0xf0 #vmovaps %xmm7, -0x10(%rax) .byte 0xc5,0x78,0x29,0x40,0x00 #vmovaps %xmm8, 8(%rax) .byte 0xc5,0x78,0x29,0x48,0x10 #vmovaps %xmm9, 0x10(%rax) .byte 0xc5,0x78,0x29,0x50,0x20 #vmovaps %xmm10, 0x20(%rax) .byte 0xc5,0x78,0x29,0x58,0x30 #vmovaps %xmm11, 0x30(%rax) .byte 0xc5,0x78,0x29,0x60,0x40 #vmovaps %xmm12, 0x40(%rax) .byte 0xc5,0x78,0x29,0x68,0x50 #vmovaps %xmm13, 0x50(%rax) .byte 0xc5,0x78,0x29,0x70,0x60 #vmovaps %xmm14, 0x60(%rax) .byte 0xc5,0x78,0x29,0x78,0x70 #vmovaps %xmm15, 0x70(%rax) ___ $code.=<<___; vmovdqa .LTwo(%rip), $TWO vpxor $Ra, $Ra, $Ra vpxor $Rb, $Rb, $Rb vpxor $Rc, $Rc, $Rc vmovdqa .LOne(%rip), $M0 vmovdqa .LTwo(%rip), $M1 vmovd $index, %xmm1 vpermd $INDEX, $Ra, $INDEX mov \$8, %rax .Lselect_loop_avx2_w5: vmovdqa 32*0($in_t), $T0a vmovdqa 32*1($in_t), $T0b vmovdqa 32*2($in_t), $T0c vmovdqa 32*3($in_t), $T1a vmovdqa 32*4($in_t), $T1b vmovdqa 32*5($in_t), $T1c vpcmpeqd $INDEX, $M0, $TMP0 vpcmpeqd $INDEX, $M1, $TMP1 vpaddd $TWO, $M0, $M0 vpaddd $TWO, $M1, $M1 lea 32*6($in_t), $in_t vpand $TMP0, $T0a, $T0a vpand $TMP0, $T0b, $T0b vpand $TMP0, $T0c, $T0c vpand $TMP1, $T1a, $T1a vpand $TMP1, $T1b, $T1b vpand $TMP1, $T1c, $T1c vpxor $T0a, $Ra, $Ra vpxor $T0b, $Rb, $Rb vpxor $T0c, $Rc, $Rc vpxor $T1a, $Ra, $Ra vpxor $T1b, $Rb, $Rb vpxor $T1c, $Rc, $Rc dec %rax jnz .Lselect_loop_avx2_w5 vmovdqu $Ra, 32*0($val) vmovdqu $Rb, 32*1($val) vmovdqu $Rc, 32*2($val) vzeroupper ___ $code.=<<___ if ($win64); movaps (%rsp), %xmm6 movaps 0x10(%rsp), %xmm7 movaps 0x20(%rsp), %xmm8 movaps 0x30(%rsp), %xmm9 movaps 0x40(%rsp), %xmm10 movaps 0x50(%rsp), %xmm11 movaps 0x60(%rsp), %xmm12 movaps 0x70(%rsp), %xmm13 movaps 0x80(%rsp), %xmm14 movaps 0x90(%rsp), %xmm15 lea 0xa8(%rsp), %rsp .LSEH_end_ecp_nistz256_avx2_select_w5: ___ $code.=<<___; ret .size ecp_nistz256_avx2_select_w5,.-ecp_nistz256_avx2_select_w5 ___ } if ($avx>1) { my ($val,$in_t,$index)=$win64?("%rcx","%rdx","%r8d"):("%rdi","%rsi","%edx"); my ($THREE,$INDEX,$Ra,$Rb)=map("%ymm$_",(0..3)); my ($M0,$T0a,$T0b,$TMP0)=map("%ymm$_",(4..7)); my ($M1,$T1a,$T1b,$TMP1)=map("%ymm$_",(8..11)); my ($M2,$T2a,$T2b,$TMP2)=map("%ymm$_",(12..15)); $code.=<<___; ################################################################################ # void ecp_nistz256_avx2_select_w7(uint64_t *val, uint64_t *in_t, int index); .globl ecp_nistz256_avx2_select_w7 .type ecp_nistz256_avx2_select_w7,\@abi-omnipotent .align 32 ecp_nistz256_avx2_select_w7: .Lavx2_select_w7: vzeroupper ___ $code.=<<___ if ($win64); lea -0x88(%rsp), %rax .LSEH_begin_ecp_nistz256_avx2_select_w7: .byte 0x48,0x8d,0x60,0xe0 #lea -0x20(%rax), %rsp .byte 0xc5,0xf8,0x29,0x70,0xe0 #vmovaps %xmm6, -0x20(%rax) .byte 0xc5,0xf8,0x29,0x78,0xf0 #vmovaps %xmm7, -0x10(%rax) .byte 0xc5,0x78,0x29,0x40,0x00 #vmovaps %xmm8, 8(%rax) .byte 0xc5,0x78,0x29,0x48,0x10 #vmovaps %xmm9, 0x10(%rax) .byte 0xc5,0x78,0x29,0x50,0x20 #vmovaps %xmm10, 0x20(%rax) .byte 0xc5,0x78,0x29,0x58,0x30 #vmovaps %xmm11, 0x30(%rax) .byte 0xc5,0x78,0x29,0x60,0x40 #vmovaps %xmm12, 0x40(%rax) .byte 0xc5,0x78,0x29,0x68,0x50 #vmovaps %xmm13, 0x50(%rax) .byte 0xc5,0x78,0x29,0x70,0x60 #vmovaps %xmm14, 0x60(%rax) .byte 0xc5,0x78,0x29,0x78,0x70 #vmovaps %xmm15, 0x70(%rax) ___ $code.=<<___; vmovdqa .LThree(%rip), $THREE vpxor $Ra, $Ra, $Ra vpxor $Rb, $Rb, $Rb vmovdqa .LOne(%rip), $M0 vmovdqa .LTwo(%rip), $M1 vmovdqa .LThree(%rip), $M2 vmovd $index, %xmm1 vpermd $INDEX, $Ra, $INDEX # Skip index = 0, because it is implicitly the point at infinity mov \$21, %rax .Lselect_loop_avx2_w7: vmovdqa 32*0($in_t), $T0a vmovdqa 32*1($in_t), $T0b vmovdqa 32*2($in_t), $T1a vmovdqa 32*3($in_t), $T1b vmovdqa 32*4($in_t), $T2a vmovdqa 32*5($in_t), $T2b vpcmpeqd $INDEX, $M0, $TMP0 vpcmpeqd $INDEX, $M1, $TMP1 vpcmpeqd $INDEX, $M2, $TMP2 vpaddd $THREE, $M0, $M0 vpaddd $THREE, $M1, $M1 vpaddd $THREE, $M2, $M2 lea 32*6($in_t), $in_t vpand $TMP0, $T0a, $T0a vpand $TMP0, $T0b, $T0b vpand $TMP1, $T1a, $T1a vpand $TMP1, $T1b, $T1b vpand $TMP2, $T2a, $T2a vpand $TMP2, $T2b, $T2b vpxor $T0a, $Ra, $Ra vpxor $T0b, $Rb, $Rb vpxor $T1a, $Ra, $Ra vpxor $T1b, $Rb, $Rb vpxor $T2a, $Ra, $Ra vpxor $T2b, $Rb, $Rb dec %rax jnz .Lselect_loop_avx2_w7 vmovdqa 32*0($in_t), $T0a vmovdqa 32*1($in_t), $T0b vpcmpeqd $INDEX, $M0, $TMP0 vpand $TMP0, $T0a, $T0a vpand $TMP0, $T0b, $T0b vpxor $T0a, $Ra, $Ra vpxor $T0b, $Rb, $Rb vmovdqu $Ra, 32*0($val) vmovdqu $Rb, 32*1($val) vzeroupper ___ $code.=<<___ if ($win64); movaps (%rsp), %xmm6 movaps 0x10(%rsp), %xmm7 movaps 0x20(%rsp), %xmm8 movaps 0x30(%rsp), %xmm9 movaps 0x40(%rsp), %xmm10 movaps 0x50(%rsp), %xmm11 movaps 0x60(%rsp), %xmm12 movaps 0x70(%rsp), %xmm13 movaps 0x80(%rsp), %xmm14 movaps 0x90(%rsp), %xmm15 lea 0xa8(%rsp), %rsp .LSEH_end_ecp_nistz256_avx2_select_w7: ___ $code.=<<___; ret .size ecp_nistz256_avx2_select_w7,.-ecp_nistz256_avx2_select_w7 ___ } else { $code.=<<___; .globl ecp_nistz256_avx2_select_w7 .type ecp_nistz256_avx2_select_w7,\@function,3 .align 32 ecp_nistz256_avx2_select_w7: .byte 0x0f,0x0b # ud2 ret .size ecp_nistz256_avx2_select_w7,.-ecp_nistz256_avx2_select_w7 ___ } {{{ ######################################################################## # This block implements higher level point_double, point_add and # point_add_affine. The key to performance in this case is to allow # out-of-order execution logic to overlap computations from next step # with tail processing from current step. By using tailored calling # sequence we minimize inter-step overhead to give processor better # shot at overlapping operations... # # You will notice that input data is copied to stack. Trouble is that # there are no registers to spare for holding original pointers and # reloading them, pointers, would create undesired dependencies on # effective addresses calculation paths. In other words it's too done # to favour out-of-order execution logic. # <appro@openssl.org> my ($r_ptr,$a_ptr,$b_org,$b_ptr)=("%rdi","%rsi","%rdx","%rbx"); my ($acc0,$acc1,$acc2,$acc3,$acc4,$acc5,$acc6,$acc7)=map("%r$_",(8..15)); my ($t0,$t1,$t2,$t3,$t4)=("%rax","%rbp","%rcx",$acc4,$acc4); my ($poly1,$poly3)=($acc6,$acc7); sub load_for_mul () { my ($a,$b,$src0) = @_; my $bias = $src0 eq "%rax" ? 0 : -128; " mov $b, $src0 lea $b, $b_ptr mov 8*0+$a, $acc1 mov 8*1+$a, $acc2 lea $bias+$a, $a_ptr mov 8*2+$a, $acc3 mov 8*3+$a, $acc4" } sub load_for_sqr () { my ($a,$src0) = @_; my $bias = $src0 eq "%rax" ? 0 : -128; " mov 8*0+$a, $src0 mov 8*1+$a, $acc6 lea $bias+$a, $a_ptr mov 8*2+$a, $acc7 mov 8*3+$a, $acc0" } { ######################################################################## # operate in 4-5-0-1 "name space" that matches multiplication output # my ($a0,$a1,$a2,$a3,$t3,$t4)=($acc4,$acc5,$acc0,$acc1,$acc2,$acc3); $code.=<<___; .type __ecp_nistz256_add_toq,\@abi-omnipotent .align 32 __ecp_nistz256_add_toq: add 8*0($b_ptr), $a0 adc 8*1($b_ptr), $a1 mov $a0, $t0 adc 8*2($b_ptr), $a2 adc 8*3($b_ptr), $a3 mov $a1, $t1 sbb $t4, $t4 sub \$-1, $a0 mov $a2, $t2 sbb $poly1, $a1 sbb \$0, $a2 mov $a3, $t3 sbb $poly3, $a3 test $t4, $t4 cmovz $t0, $a0 cmovz $t1, $a1 mov $a0, 8*0($r_ptr) cmovz $t2, $a2 mov $a1, 8*1($r_ptr) cmovz $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) ret .size __ecp_nistz256_add_toq,.-__ecp_nistz256_add_toq .type __ecp_nistz256_sub_fromq,\@abi-omnipotent .align 32 __ecp_nistz256_sub_fromq: sub 8*0($b_ptr), $a0 sbb 8*1($b_ptr), $a1 mov $a0, $t0 sbb 8*2($b_ptr), $a2 sbb 8*3($b_ptr), $a3 mov $a1, $t1 sbb $t4, $t4 add \$-1, $a0 mov $a2, $t2 adc $poly1, $a1 adc \$0, $a2 mov $a3, $t3 adc $poly3, $a3 test $t4, $t4 cmovz $t0, $a0 cmovz $t1, $a1 mov $a0, 8*0($r_ptr) cmovz $t2, $a2 mov $a1, 8*1($r_ptr) cmovz $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) ret .size __ecp_nistz256_sub_fromq,.-__ecp_nistz256_sub_fromq .type __ecp_nistz256_subq,\@abi-omnipotent .align 32 __ecp_nistz256_subq: sub $a0, $t0 sbb $a1, $t1 mov $t0, $a0 sbb $a2, $t2 sbb $a3, $t3 mov $t1, $a1 sbb $t4, $t4 add \$-1, $t0 mov $t2, $a2 adc $poly1, $t1 adc \$0, $t2 mov $t3, $a3 adc $poly3, $t3 test $t4, $t4 cmovnz $t0, $a0 cmovnz $t1, $a1 cmovnz $t2, $a2 cmovnz $t3, $a3 ret .size __ecp_nistz256_subq,.-__ecp_nistz256_subq .type __ecp_nistz256_mul_by_2q,\@abi-omnipotent .align 32 __ecp_nistz256_mul_by_2q: add $a0, $a0 # a0:a3+a0:a3 adc $a1, $a1 mov $a0, $t0 adc $a2, $a2 adc $a3, $a3 mov $a1, $t1 sbb $t4, $t4 sub \$-1, $a0 mov $a2, $t2 sbb $poly1, $a1 sbb \$0, $a2 mov $a3, $t3 sbb $poly3, $a3 test $t4, $t4 cmovz $t0, $a0 cmovz $t1, $a1 mov $a0, 8*0($r_ptr) cmovz $t2, $a2 mov $a1, 8*1($r_ptr) cmovz $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) ret .size __ecp_nistz256_mul_by_2q,.-__ecp_nistz256_mul_by_2q ___ } sub gen_double () { my $x = shift; my ($src0,$sfx,$bias); my ($S,$M,$Zsqr,$in_x,$tmp0)=map(32*$_,(0..4)); if ($x ne "x") { $src0 = "%rax"; $sfx = ""; $bias = 0; $code.=<<___; .globl ecp_nistz256_point_double .type ecp_nistz256_point_double,\@function,2 .align 32 ecp_nistz256_point_double: ___ $code.=<<___ if ($addx); mov \$0x80100, %ecx and OPENSSL_ia32cap_P+8(%rip), %ecx cmp \$0x80100, %ecx je .Lpoint_doublex ___ } else { $src0 = "%rdx"; $sfx = "x"; $bias = 128; $code.=<<___; .type ecp_nistz256_point_doublex,\@function,2 .align 32 ecp_nistz256_point_doublex: .Lpoint_doublex: ___ } $code.=<<___; push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 sub \$32*5+8, %rsp movdqu 0x00($a_ptr), %xmm0 # copy *(P256_POINT *)$a_ptr.x mov $a_ptr, $b_ptr # backup copy movdqu 0x10($a_ptr), %xmm1 mov 0x20+8*0($a_ptr), $acc4 # load in_y in "5-4-0-1" order mov 0x20+8*1($a_ptr), $acc5 mov 0x20+8*2($a_ptr), $acc0 mov 0x20+8*3($a_ptr), $acc1 mov .Lpoly+8*1(%rip), $poly1 mov .Lpoly+8*3(%rip), $poly3 movdqa %xmm0, $in_x(%rsp) movdqa %xmm1, $in_x+0x10(%rsp) lea 0x20($r_ptr), $acc2 lea 0x40($r_ptr), $acc3 movq $r_ptr, %xmm0 movq $acc2, %xmm1 movq $acc3, %xmm2 lea $S(%rsp), $r_ptr call __ecp_nistz256_mul_by_2$x # p256_mul_by_2(S, in_y); mov 0x40+8*0($a_ptr), $src0 mov 0x40+8*1($a_ptr), $acc6 mov 0x40+8*2($a_ptr), $acc7 mov 0x40+8*3($a_ptr), $acc0 lea 0x40-$bias($a_ptr), $a_ptr lea $Zsqr(%rsp), $r_ptr call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(Zsqr, in_z); `&load_for_sqr("$S(%rsp)", "$src0")` lea $S(%rsp), $r_ptr call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(S, S); mov 0x20($b_ptr), $src0 # $b_ptr is still valid mov 0x40+8*0($b_ptr), $acc1 mov 0x40+8*1($b_ptr), $acc2 mov 0x40+8*2($b_ptr), $acc3 mov 0x40+8*3($b_ptr), $acc4 lea 0x40-$bias($b_ptr), $a_ptr lea 0x20($b_ptr), $b_ptr movq %xmm2, $r_ptr call __ecp_nistz256_mul_mont$x # p256_mul_mont(res_z, in_z, in_y); call __ecp_nistz256_mul_by_2$x # p256_mul_by_2(res_z, res_z); mov $in_x+8*0(%rsp), $acc4 # "5-4-0-1" order mov $in_x+8*1(%rsp), $acc5 lea $Zsqr(%rsp), $b_ptr mov $in_x+8*2(%rsp), $acc0 mov $in_x+8*3(%rsp), $acc1 lea $M(%rsp), $r_ptr call __ecp_nistz256_add_to$x # p256_add(M, in_x, Zsqr); mov $in_x+8*0(%rsp), $acc4 # "5-4-0-1" order mov $in_x+8*1(%rsp), $acc5 lea $Zsqr(%rsp), $b_ptr mov $in_x+8*2(%rsp), $acc0 mov $in_x+8*3(%rsp), $acc1 lea $Zsqr(%rsp), $r_ptr call __ecp_nistz256_sub_from$x # p256_sub(Zsqr, in_x, Zsqr); `&load_for_sqr("$S(%rsp)", "$src0")` movq %xmm1, $r_ptr call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(res_y, S); ___ { ######## ecp_nistz256_div_by_2(res_y, res_y); ########################## # operate in 4-5-6-7 "name space" that matches squaring output # my ($poly1,$poly3)=($a_ptr,$t1); my ($a0,$a1,$a2,$a3,$t3,$t4,$t1)=($acc4,$acc5,$acc6,$acc7,$acc0,$acc1,$acc2); $code.=<<___; xor $t4, $t4 mov $a0, $t0 add \$-1, $a0 mov $a1, $t1 adc $poly1, $a1 mov $a2, $t2 adc \$0, $a2 mov $a3, $t3 adc $poly3, $a3 adc \$0, $t4 xor $a_ptr, $a_ptr # borrow $a_ptr test \$1, $t0 cmovz $t0, $a0 cmovz $t1, $a1 cmovz $t2, $a2 cmovz $t3, $a3 cmovz $a_ptr, $t4 mov $a1, $t0 # a0:a3>>1 shr \$1, $a0 shl \$63, $t0 mov $a2, $t1 shr \$1, $a1 or $t0, $a0 shl \$63, $t1 mov $a3, $t2 shr \$1, $a2 or $t1, $a1 shl \$63, $t2 mov $a0, 8*0($r_ptr) shr \$1, $a3 mov $a1, 8*1($r_ptr) shl \$63, $t4 or $t2, $a2 or $t4, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) ___ } $code.=<<___; `&load_for_mul("$M(%rsp)", "$Zsqr(%rsp)", "$src0")` lea $M(%rsp), $r_ptr call __ecp_nistz256_mul_mont$x # p256_mul_mont(M, M, Zsqr); lea $tmp0(%rsp), $r_ptr call __ecp_nistz256_mul_by_2$x lea $M(%rsp), $b_ptr lea $M(%rsp), $r_ptr call __ecp_nistz256_add_to$x # p256_mul_by_3(M, M); `&load_for_mul("$S(%rsp)", "$in_x(%rsp)", "$src0")` lea $S(%rsp), $r_ptr call __ecp_nistz256_mul_mont$x # p256_mul_mont(S, S, in_x); lea $tmp0(%rsp), $r_ptr call __ecp_nistz256_mul_by_2$x # p256_mul_by_2(tmp0, S); `&load_for_sqr("$M(%rsp)", "$src0")` movq %xmm0, $r_ptr call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(res_x, M); lea $tmp0(%rsp), $b_ptr mov $acc6, $acc0 # harmonize sqr output and sub input mov $acc7, $acc1 mov $a_ptr, $poly1 mov $t1, $poly3 call __ecp_nistz256_sub_from$x # p256_sub(res_x, res_x, tmp0); mov $S+8*0(%rsp), $t0 mov $S+8*1(%rsp), $t1 mov $S+8*2(%rsp), $t2 mov $S+8*3(%rsp), $acc2 # "4-5-0-1" order lea $S(%rsp), $r_ptr call __ecp_nistz256_sub$x # p256_sub(S, S, res_x); mov $M(%rsp), $src0 lea $M(%rsp), $b_ptr mov $acc4, $acc6 # harmonize sub output and mul input xor %ecx, %ecx mov $acc4, $S+8*0(%rsp) # have to save:-( mov $acc5, $acc2 mov $acc5, $S+8*1(%rsp) cmovz $acc0, $acc3 mov $acc0, $S+8*2(%rsp) lea $S-$bias(%rsp), $a_ptr cmovz $acc1, $acc4 mov $acc1, $S+8*3(%rsp) mov $acc6, $acc1 lea $S(%rsp), $r_ptr call __ecp_nistz256_mul_mont$x # p256_mul_mont(S, S, M); movq %xmm1, $b_ptr movq %xmm1, $r_ptr call __ecp_nistz256_sub_from$x # p256_sub(res_y, S, res_y); add \$32*5+8, %rsp pop %r15 pop %r14 pop %r13 pop %r12 pop %rbx pop %rbp ret .size ecp_nistz256_point_double$sfx,.-ecp_nistz256_point_double$sfx ___ } &gen_double("q"); sub gen_add () { my $x = shift; my ($src0,$sfx,$bias); my ($H,$Hsqr,$R,$Rsqr,$Hcub, $U1,$U2,$S1,$S2, $res_x,$res_y,$res_z, $in1_x,$in1_y,$in1_z, $in2_x,$in2_y,$in2_z)=map(32*$_,(0..17)); my ($Z1sqr, $Z2sqr) = ($Hsqr, $Rsqr); if ($x ne "x") { $src0 = "%rax"; $sfx = ""; $bias = 0; $code.=<<___; .globl ecp_nistz256_point_add .type ecp_nistz256_point_add,\@function,3 .align 32 ecp_nistz256_point_add: ___ $code.=<<___ if ($addx); mov \$0x80100, %ecx and OPENSSL_ia32cap_P+8(%rip), %ecx cmp \$0x80100, %ecx je .Lpoint_addx ___ } else { $src0 = "%rdx"; $sfx = "x"; $bias = 128; $code.=<<___; .type ecp_nistz256_point_addx,\@function,3 .align 32 ecp_nistz256_point_addx: .Lpoint_addx: ___ } $code.=<<___; push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 sub \$32*18+8, %rsp movdqu 0x00($a_ptr), %xmm0 # copy *(P256_POINT *)$a_ptr movdqu 0x10($a_ptr), %xmm1 movdqu 0x20($a_ptr), %xmm2 movdqu 0x30($a_ptr), %xmm3 movdqu 0x40($a_ptr), %xmm4 movdqu 0x50($a_ptr), %xmm5 mov $a_ptr, $b_ptr # reassign mov $b_org, $a_ptr # reassign movdqa %xmm0, $in1_x(%rsp) movdqa %xmm1, $in1_x+0x10(%rsp) por %xmm0, %xmm1 movdqa %xmm2, $in1_y(%rsp) movdqa %xmm3, $in1_y+0x10(%rsp) por %xmm2, %xmm3 movdqa %xmm4, $in1_z(%rsp) movdqa %xmm5, $in1_z+0x10(%rsp) por %xmm1, %xmm3 movdqu 0x00($a_ptr), %xmm0 # copy *(P256_POINT *)$b_ptr pshufd \$0xb1, %xmm3, %xmm5 movdqu 0x10($a_ptr), %xmm1 movdqu 0x20($a_ptr), %xmm2 por %xmm3, %xmm5 movdqu 0x30($a_ptr), %xmm3 mov 0x40+8*0($a_ptr), $src0 # load original in2_z mov 0x40+8*1($a_ptr), $acc6 mov 0x40+8*2($a_ptr), $acc7 mov 0x40+8*3($a_ptr), $acc0 movdqa %xmm0, $in2_x(%rsp) pshufd \$0x1e, %xmm5, %xmm4 movdqa %xmm1, $in2_x+0x10(%rsp) por %xmm0, %xmm1 movq $r_ptr, %xmm0 # save $r_ptr movdqa %xmm2, $in2_y(%rsp) movdqa %xmm3, $in2_y+0x10(%rsp) por %xmm2, %xmm3 por %xmm4, %xmm5 pxor %xmm4, %xmm4 por %xmm1, %xmm3 lea 0x40-$bias($a_ptr), $a_ptr # $a_ptr is still valid mov $src0, $in2_z+8*0(%rsp) # make in2_z copy mov $acc6, $in2_z+8*1(%rsp) mov $acc7, $in2_z+8*2(%rsp) mov $acc0, $in2_z+8*3(%rsp) lea $Z2sqr(%rsp), $r_ptr # Z2^2 call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(Z2sqr, in2_z); pcmpeqd %xmm4, %xmm5 pshufd \$0xb1, %xmm3, %xmm4 por %xmm3, %xmm4 pshufd \$0, %xmm5, %xmm5 # in1infty pshufd \$0x1e, %xmm4, %xmm3 por %xmm3, %xmm4 pxor %xmm3, %xmm3 pcmpeqd %xmm3, %xmm4 pshufd \$0, %xmm4, %xmm4 # in2infty mov 0x40+8*0($b_ptr), $src0 # load original in1_z mov 0x40+8*1($b_ptr), $acc6 mov 0x40+8*2($b_ptr), $acc7 mov 0x40+8*3($b_ptr), $acc0 lea 0x40-$bias($b_ptr), $a_ptr lea $Z1sqr(%rsp), $r_ptr # Z1^2 call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(Z1sqr, in1_z); `&load_for_mul("$Z2sqr(%rsp)", "$in2_z(%rsp)", "$src0")` lea $S1(%rsp), $r_ptr # S1 = Z2^3 call __ecp_nistz256_mul_mont$x # p256_mul_mont(S1, Z2sqr, in2_z); `&load_for_mul("$Z1sqr(%rsp)", "$in1_z(%rsp)", "$src0")` lea $S2(%rsp), $r_ptr # S2 = Z1^3 call __ecp_nistz256_mul_mont$x # p256_mul_mont(S2, Z1sqr, in1_z); `&load_for_mul("$S1(%rsp)", "$in1_y(%rsp)", "$src0")` lea $S1(%rsp), $r_ptr # S1 = Y1*Z2^3 call __ecp_nistz256_mul_mont$x # p256_mul_mont(S1, S1, in1_y); `&load_for_mul("$S2(%rsp)", "$in2_y(%rsp)", "$src0")` lea $S2(%rsp), $r_ptr # S2 = Y2*Z1^3 call __ecp_nistz256_mul_mont$x # p256_mul_mont(S2, S2, in2_y); lea $S1(%rsp), $b_ptr lea $R(%rsp), $r_ptr # R = S2 - S1 call __ecp_nistz256_sub_from$x # p256_sub(R, S2, S1); or $acc5, $acc4 # see if result is zero movdqa %xmm4, %xmm2 or $acc0, $acc4 or $acc1, $acc4 por %xmm5, %xmm2 # in1infty || in2infty movq $acc4, %xmm3 `&load_for_mul("$Z2sqr(%rsp)", "$in1_x(%rsp)", "$src0")` lea $U1(%rsp), $r_ptr # U1 = X1*Z2^2 call __ecp_nistz256_mul_mont$x # p256_mul_mont(U1, in1_x, Z2sqr); `&load_for_mul("$Z1sqr(%rsp)", "$in2_x(%rsp)", "$src0")` lea $U2(%rsp), $r_ptr # U2 = X2*Z1^2 call __ecp_nistz256_mul_mont$x # p256_mul_mont(U2, in2_x, Z1sqr); lea $U1(%rsp), $b_ptr lea $H(%rsp), $r_ptr # H = U2 - U1 call __ecp_nistz256_sub_from$x # p256_sub(H, U2, U1); or $acc5, $acc4 # see if result is zero or $acc0, $acc4 or $acc1, $acc4 .byte 0x3e # predict taken jnz .Ladd_proceed$x # is_equal(U1,U2)? movq %xmm2, $acc0 movq %xmm3, $acc1 test $acc0, $acc0 jnz .Ladd_proceed$x # (in1infty || in2infty)? test $acc1, $acc1 jz .Ladd_proceed$x # is_equal(S1,S2)? movq %xmm0, $r_ptr # restore $r_ptr pxor %xmm0, %xmm0 movdqu %xmm0, 0x00($r_ptr) movdqu %xmm0, 0x10($r_ptr) movdqu %xmm0, 0x20($r_ptr) movdqu %xmm0, 0x30($r_ptr) movdqu %xmm0, 0x40($r_ptr) movdqu %xmm0, 0x50($r_ptr) jmp .Ladd_done$x .align 32 .Ladd_proceed$x: `&load_for_sqr("$R(%rsp)", "$src0")` lea $Rsqr(%rsp), $r_ptr # R^2 call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(Rsqr, R); `&load_for_mul("$H(%rsp)", "$in1_z(%rsp)", "$src0")` lea $res_z(%rsp), $r_ptr # Z3 = H*Z1*Z2 call __ecp_nistz256_mul_mont$x # p256_mul_mont(res_z, H, in1_z); `&load_for_sqr("$H(%rsp)", "$src0")` lea $Hsqr(%rsp), $r_ptr # H^2 call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(Hsqr, H); `&load_for_mul("$res_z(%rsp)", "$in2_z(%rsp)", "$src0")` lea $res_z(%rsp), $r_ptr # Z3 = H*Z1*Z2 call __ecp_nistz256_mul_mont$x # p256_mul_mont(res_z, res_z, in2_z); `&load_for_mul("$Hsqr(%rsp)", "$H(%rsp)", "$src0")` lea $Hcub(%rsp), $r_ptr # H^3 call __ecp_nistz256_mul_mont$x # p256_mul_mont(Hcub, Hsqr, H); `&load_for_mul("$Hsqr(%rsp)", "$U1(%rsp)", "$src0")` lea $U2(%rsp), $r_ptr # U1*H^2 call __ecp_nistz256_mul_mont$x # p256_mul_mont(U2, U1, Hsqr); ___ { ####################################################################### # operate in 4-5-0-1 "name space" that matches multiplication output # my ($acc0,$acc1,$acc2,$acc3,$t3,$t4)=($acc4,$acc5,$acc0,$acc1,$acc2,$acc3); my ($poly1, $poly3)=($acc6,$acc7); $code.=<<___; #lea $U2(%rsp), $a_ptr #lea $Hsqr(%rsp), $r_ptr # 2*U1*H^2 #call __ecp_nistz256_mul_by_2 # ecp_nistz256_mul_by_2(Hsqr, U2); add $acc0, $acc0 # a0:a3+a0:a3 lea $Rsqr(%rsp), $a_ptr adc $acc1, $acc1 mov $acc0, $t0 adc $acc2, $acc2 adc $acc3, $acc3 mov $acc1, $t1 sbb $t4, $t4 sub \$-1, $acc0 mov $acc2, $t2 sbb $poly1, $acc1 sbb \$0, $acc2 mov $acc3, $t3 sbb $poly3, $acc3 test $t4, $t4 cmovz $t0, $acc0 mov 8*0($a_ptr), $t0 cmovz $t1, $acc1 mov 8*1($a_ptr), $t1 cmovz $t2, $acc2 mov 8*2($a_ptr), $t2 cmovz $t3, $acc3 mov 8*3($a_ptr), $t3 call __ecp_nistz256_sub$x # p256_sub(res_x, Rsqr, Hsqr); lea $Hcub(%rsp), $b_ptr lea $res_x(%rsp), $r_ptr call __ecp_nistz256_sub_from$x # p256_sub(res_x, res_x, Hcub); mov $U2+8*0(%rsp), $t0 mov $U2+8*1(%rsp), $t1 mov $U2+8*2(%rsp), $t2 mov $U2+8*3(%rsp), $t3 lea $res_y(%rsp), $r_ptr call __ecp_nistz256_sub$x # p256_sub(res_y, U2, res_x); mov $acc0, 8*0($r_ptr) # save the result, as mov $acc1, 8*1($r_ptr) # __ecp_nistz256_sub doesn't mov $acc2, 8*2($r_ptr) mov $acc3, 8*3($r_ptr) ___ } $code.=<<___; `&load_for_mul("$S1(%rsp)", "$Hcub(%rsp)", "$src0")` lea $S2(%rsp), $r_ptr call __ecp_nistz256_mul_mont$x # p256_mul_mont(S2, S1, Hcub); `&load_for_mul("$R(%rsp)", "$res_y(%rsp)", "$src0")` lea $res_y(%rsp), $r_ptr call __ecp_nistz256_mul_mont$x # p256_mul_mont(res_y, R, res_y); lea $S2(%rsp), $b_ptr lea $res_y(%rsp), $r_ptr call __ecp_nistz256_sub_from$x # p256_sub(res_y, res_y, S2); movq %xmm0, $r_ptr # restore $r_ptr movdqa %xmm5, %xmm0 # copy_conditional(res_z, in2_z, in1infty); movdqa %xmm5, %xmm1 pandn $res_z(%rsp), %xmm0 movdqa %xmm5, %xmm2 pandn $res_z+0x10(%rsp), %xmm1 movdqa %xmm5, %xmm3 pand $in2_z(%rsp), %xmm2 pand $in2_z+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqa %xmm4, %xmm0 # copy_conditional(res_z, in1_z, in2infty); movdqa %xmm4, %xmm1 pandn %xmm2, %xmm0 movdqa %xmm4, %xmm2 pandn %xmm3, %xmm1 movdqa %xmm4, %xmm3 pand $in1_z(%rsp), %xmm2 pand $in1_z+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqu %xmm2, 0x40($r_ptr) movdqu %xmm3, 0x50($r_ptr) movdqa %xmm5, %xmm0 # copy_conditional(res_x, in2_x, in1infty); movdqa %xmm5, %xmm1 pandn $res_x(%rsp), %xmm0 movdqa %xmm5, %xmm2 pandn $res_x+0x10(%rsp), %xmm1 movdqa %xmm5, %xmm3 pand $in2_x(%rsp), %xmm2 pand $in2_x+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqa %xmm4, %xmm0 # copy_conditional(res_x, in1_x, in2infty); movdqa %xmm4, %xmm1 pandn %xmm2, %xmm0 movdqa %xmm4, %xmm2 pandn %xmm3, %xmm1 movdqa %xmm4, %xmm3 pand $in1_x(%rsp), %xmm2 pand $in1_x+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqu %xmm2, 0x00($r_ptr) movdqu %xmm3, 0x10($r_ptr) movdqa %xmm5, %xmm0 # copy_conditional(res_y, in2_y, in1infty); movdqa %xmm5, %xmm1 pandn $res_y(%rsp), %xmm0 movdqa %xmm5, %xmm2 pandn $res_y+0x10(%rsp), %xmm1 movdqa %xmm5, %xmm3 pand $in2_y(%rsp), %xmm2 pand $in2_y+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqa %xmm4, %xmm0 # copy_conditional(res_y, in1_y, in2infty); movdqa %xmm4, %xmm1 pandn %xmm2, %xmm0 movdqa %xmm4, %xmm2 pandn %xmm3, %xmm1 movdqa %xmm4, %xmm3 pand $in1_y(%rsp), %xmm2 pand $in1_y+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqu %xmm2, 0x20($r_ptr) movdqu %xmm3, 0x30($r_ptr) .Ladd_done$x: add \$32*18+8, %rsp pop %r15 pop %r14 pop %r13 pop %r12 pop %rbx pop %rbp ret .size ecp_nistz256_point_add$sfx,.-ecp_nistz256_point_add$sfx ___ } &gen_add("q"); sub gen_add_affine () { my $x = shift; my ($src0,$sfx,$bias); my ($U2,$S2,$H,$R,$Hsqr,$Hcub,$Rsqr, $res_x,$res_y,$res_z, $in1_x,$in1_y,$in1_z, $in2_x,$in2_y)=map(32*$_,(0..14)); my $Z1sqr = $S2; if ($x ne "x") { $src0 = "%rax"; $sfx = ""; $bias = 0; $code.=<<___; .globl ecp_nistz256_point_add_affine .type ecp_nistz256_point_add_affine,\@function,3 .align 32 ecp_nistz256_point_add_affine: ___ $code.=<<___ if ($addx); mov \$0x80100, %ecx and OPENSSL_ia32cap_P+8(%rip), %ecx cmp \$0x80100, %ecx je .Lpoint_add_affinex ___ } else { $src0 = "%rdx"; $sfx = "x"; $bias = 128; $code.=<<___; .type ecp_nistz256_point_add_affinex,\@function,3 .align 32 ecp_nistz256_point_add_affinex: .Lpoint_add_affinex: ___ } $code.=<<___; push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 sub \$32*15+8, %rsp movdqu 0x00($a_ptr), %xmm0 # copy *(P256_POINT *)$a_ptr mov $b_org, $b_ptr # reassign movdqu 0x10($a_ptr), %xmm1 movdqu 0x20($a_ptr), %xmm2 movdqu 0x30($a_ptr), %xmm3 movdqu 0x40($a_ptr), %xmm4 movdqu 0x50($a_ptr), %xmm5 mov 0x40+8*0($a_ptr), $src0 # load original in1_z mov 0x40+8*1($a_ptr), $acc6 mov 0x40+8*2($a_ptr), $acc7 mov 0x40+8*3($a_ptr), $acc0 movdqa %xmm0, $in1_x(%rsp) movdqa %xmm1, $in1_x+0x10(%rsp) por %xmm0, %xmm1 movdqa %xmm2, $in1_y(%rsp) movdqa %xmm3, $in1_y+0x10(%rsp) por %xmm2, %xmm3 movdqa %xmm4, $in1_z(%rsp) movdqa %xmm5, $in1_z+0x10(%rsp) por %xmm1, %xmm3 movdqu 0x00($b_ptr), %xmm0 # copy *(P256_POINT_AFFINE *)$b_ptr pshufd \$0xb1, %xmm3, %xmm5 movdqu 0x10($b_ptr), %xmm1 movdqu 0x20($b_ptr), %xmm2 por %xmm3, %xmm5 movdqu 0x30($b_ptr), %xmm3 movdqa %xmm0, $in2_x(%rsp) pshufd \$0x1e, %xmm5, %xmm4 movdqa %xmm1, $in2_x+0x10(%rsp) por %xmm0, %xmm1 movq $r_ptr, %xmm0 # save $r_ptr movdqa %xmm2, $in2_y(%rsp) movdqa %xmm3, $in2_y+0x10(%rsp) por %xmm2, %xmm3 por %xmm4, %xmm5 pxor %xmm4, %xmm4 por %xmm1, %xmm3 lea 0x40-$bias($a_ptr), $a_ptr # $a_ptr is still valid lea $Z1sqr(%rsp), $r_ptr # Z1^2 call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(Z1sqr, in1_z); pcmpeqd %xmm4, %xmm5 pshufd \$0xb1, %xmm3, %xmm4 mov 0x00($b_ptr), $src0 # $b_ptr is still valid #lea 0x00($b_ptr), $b_ptr mov $acc4, $acc1 # harmonize sqr output and mul input por %xmm3, %xmm4 pshufd \$0, %xmm5, %xmm5 # in1infty pshufd \$0x1e, %xmm4, %xmm3 mov $acc5, $acc2 por %xmm3, %xmm4 pxor %xmm3, %xmm3 mov $acc6, $acc3 pcmpeqd %xmm3, %xmm4 pshufd \$0, %xmm4, %xmm4 # in2infty lea $Z1sqr-$bias(%rsp), $a_ptr mov $acc7, $acc4 lea $U2(%rsp), $r_ptr # U2 = X2*Z1^2 call __ecp_nistz256_mul_mont$x # p256_mul_mont(U2, Z1sqr, in2_x); lea $in1_x(%rsp), $b_ptr lea $H(%rsp), $r_ptr # H = U2 - U1 call __ecp_nistz256_sub_from$x # p256_sub(H, U2, in1_x); `&load_for_mul("$Z1sqr(%rsp)", "$in1_z(%rsp)", "$src0")` lea $S2(%rsp), $r_ptr # S2 = Z1^3 call __ecp_nistz256_mul_mont$x # p256_mul_mont(S2, Z1sqr, in1_z); `&load_for_mul("$H(%rsp)", "$in1_z(%rsp)", "$src0")` lea $res_z(%rsp), $r_ptr # Z3 = H*Z1*Z2 call __ecp_nistz256_mul_mont$x # p256_mul_mont(res_z, H, in1_z); `&load_for_mul("$S2(%rsp)", "$in2_y(%rsp)", "$src0")` lea $S2(%rsp), $r_ptr # S2 = Y2*Z1^3 call __ecp_nistz256_mul_mont$x # p256_mul_mont(S2, S2, in2_y); lea $in1_y(%rsp), $b_ptr lea $R(%rsp), $r_ptr # R = S2 - S1 call __ecp_nistz256_sub_from$x # p256_sub(R, S2, in1_y); `&load_for_sqr("$H(%rsp)", "$src0")` lea $Hsqr(%rsp), $r_ptr # H^2 call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(Hsqr, H); `&load_for_sqr("$R(%rsp)", "$src0")` lea $Rsqr(%rsp), $r_ptr # R^2 call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(Rsqr, R); `&load_for_mul("$H(%rsp)", "$Hsqr(%rsp)", "$src0")` lea $Hcub(%rsp), $r_ptr # H^3 call __ecp_nistz256_mul_mont$x # p256_mul_mont(Hcub, Hsqr, H); `&load_for_mul("$Hsqr(%rsp)", "$in1_x(%rsp)", "$src0")` lea $U2(%rsp), $r_ptr # U1*H^2 call __ecp_nistz256_mul_mont$x # p256_mul_mont(U2, in1_x, Hsqr); ___ { ####################################################################### # operate in 4-5-0-1 "name space" that matches multiplication output # my ($acc0,$acc1,$acc2,$acc3,$t3,$t4)=($acc4,$acc5,$acc0,$acc1,$acc2,$acc3); my ($poly1, $poly3)=($acc6,$acc7); $code.=<<___; #lea $U2(%rsp), $a_ptr #lea $Hsqr(%rsp), $r_ptr # 2*U1*H^2 #call __ecp_nistz256_mul_by_2 # ecp_nistz256_mul_by_2(Hsqr, U2); add $acc0, $acc0 # a0:a3+a0:a3 lea $Rsqr(%rsp), $a_ptr adc $acc1, $acc1 mov $acc0, $t0 adc $acc2, $acc2 adc $acc3, $acc3 mov $acc1, $t1 sbb $t4, $t4 sub \$-1, $acc0 mov $acc2, $t2 sbb $poly1, $acc1 sbb \$0, $acc2 mov $acc3, $t3 sbb $poly3, $acc3 test $t4, $t4 cmovz $t0, $acc0 mov 8*0($a_ptr), $t0 cmovz $t1, $acc1 mov 8*1($a_ptr), $t1 cmovz $t2, $acc2 mov 8*2($a_ptr), $t2 cmovz $t3, $acc3 mov 8*3($a_ptr), $t3 call __ecp_nistz256_sub$x # p256_sub(res_x, Rsqr, Hsqr); lea $Hcub(%rsp), $b_ptr lea $res_x(%rsp), $r_ptr call __ecp_nistz256_sub_from$x # p256_sub(res_x, res_x, Hcub); mov $U2+8*0(%rsp), $t0 mov $U2+8*1(%rsp), $t1 mov $U2+8*2(%rsp), $t2 mov $U2+8*3(%rsp), $t3 lea $H(%rsp), $r_ptr call __ecp_nistz256_sub$x # p256_sub(H, U2, res_x); mov $acc0, 8*0($r_ptr) # save the result, as mov $acc1, 8*1($r_ptr) # __ecp_nistz256_sub doesn't mov $acc2, 8*2($r_ptr) mov $acc3, 8*3($r_ptr) ___ } $code.=<<___; `&load_for_mul("$Hcub(%rsp)", "$in1_y(%rsp)", "$src0")` lea $S2(%rsp), $r_ptr call __ecp_nistz256_mul_mont$x # p256_mul_mont(S2, Hcub, in1_y); `&load_for_mul("$H(%rsp)", "$R(%rsp)", "$src0")` lea $H(%rsp), $r_ptr call __ecp_nistz256_mul_mont$x # p256_mul_mont(H, H, R); lea $S2(%rsp), $b_ptr lea $res_y(%rsp), $r_ptr call __ecp_nistz256_sub_from$x # p256_sub(res_y, H, S2); movq %xmm0, $r_ptr # restore $r_ptr movdqa %xmm5, %xmm0 # copy_conditional(res_z, ONE, in1infty); movdqa %xmm5, %xmm1 pandn $res_z(%rsp), %xmm0 movdqa %xmm5, %xmm2 pandn $res_z+0x10(%rsp), %xmm1 movdqa %xmm5, %xmm3 pand .LONE_mont(%rip), %xmm2 pand .LONE_mont+0x10(%rip), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqa %xmm4, %xmm0 # copy_conditional(res_z, in1_z, in2infty); movdqa %xmm4, %xmm1 pandn %xmm2, %xmm0 movdqa %xmm4, %xmm2 pandn %xmm3, %xmm1 movdqa %xmm4, %xmm3 pand $in1_z(%rsp), %xmm2 pand $in1_z+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqu %xmm2, 0x40($r_ptr) movdqu %xmm3, 0x50($r_ptr) movdqa %xmm5, %xmm0 # copy_conditional(res_x, in2_x, in1infty); movdqa %xmm5, %xmm1 pandn $res_x(%rsp), %xmm0 movdqa %xmm5, %xmm2 pandn $res_x+0x10(%rsp), %xmm1 movdqa %xmm5, %xmm3 pand $in2_x(%rsp), %xmm2 pand $in2_x+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqa %xmm4, %xmm0 # copy_conditional(res_x, in1_x, in2infty); movdqa %xmm4, %xmm1 pandn %xmm2, %xmm0 movdqa %xmm4, %xmm2 pandn %xmm3, %xmm1 movdqa %xmm4, %xmm3 pand $in1_x(%rsp), %xmm2 pand $in1_x+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqu %xmm2, 0x00($r_ptr) movdqu %xmm3, 0x10($r_ptr) movdqa %xmm5, %xmm0 # copy_conditional(res_y, in2_y, in1infty); movdqa %xmm5, %xmm1 pandn $res_y(%rsp), %xmm0 movdqa %xmm5, %xmm2 pandn $res_y+0x10(%rsp), %xmm1 movdqa %xmm5, %xmm3 pand $in2_y(%rsp), %xmm2 pand $in2_y+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqa %xmm4, %xmm0 # copy_conditional(res_y, in1_y, in2infty); movdqa %xmm4, %xmm1 pandn %xmm2, %xmm0 movdqa %xmm4, %xmm2 pandn %xmm3, %xmm1 movdqa %xmm4, %xmm3 pand $in1_y(%rsp), %xmm2 pand $in1_y+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqu %xmm2, 0x20($r_ptr) movdqu %xmm3, 0x30($r_ptr) add \$32*15+8, %rsp pop %r15 pop %r14 pop %r13 pop %r12 pop %rbx pop %rbp ret .size ecp_nistz256_point_add_affine$sfx,.-ecp_nistz256_point_add_affine$sfx ___ } &gen_add_affine("q"); ######################################################################## # AD*X magic # if ($addx) { { ######################################################################## # operate in 4-5-0-1 "name space" that matches multiplication output # my ($a0,$a1,$a2,$a3,$t3,$t4)=($acc4,$acc5,$acc0,$acc1,$acc2,$acc3); $code.=<<___; .type __ecp_nistz256_add_tox,\@abi-omnipotent .align 32 __ecp_nistz256_add_tox: xor $t4, $t4 adc 8*0($b_ptr), $a0 adc 8*1($b_ptr), $a1 mov $a0, $t0 adc 8*2($b_ptr), $a2 adc 8*3($b_ptr), $a3 mov $a1, $t1 adc \$0, $t4 xor $t3, $t3 sbb \$-1, $a0 mov $a2, $t2 sbb $poly1, $a1 sbb \$0, $a2 mov $a3, $t3 sbb $poly3, $a3 bt \$0, $t4 cmovnc $t0, $a0 cmovnc $t1, $a1 mov $a0, 8*0($r_ptr) cmovnc $t2, $a2 mov $a1, 8*1($r_ptr) cmovnc $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) ret .size __ecp_nistz256_add_tox,.-__ecp_nistz256_add_tox .type __ecp_nistz256_sub_fromx,\@abi-omnipotent .align 32 __ecp_nistz256_sub_fromx: xor $t4, $t4 sbb 8*0($b_ptr), $a0 sbb 8*1($b_ptr), $a1 mov $a0, $t0 sbb 8*2($b_ptr), $a2 sbb 8*3($b_ptr), $a3 mov $a1, $t1 sbb \$0, $t4 xor $t3, $t3 adc \$-1, $a0 mov $a2, $t2 adc $poly1, $a1 adc \$0, $a2 mov $a3, $t3 adc $poly3, $a3 bt \$0, $t4 cmovnc $t0, $a0 cmovnc $t1, $a1 mov $a0, 8*0($r_ptr) cmovnc $t2, $a2 mov $a1, 8*1($r_ptr) cmovnc $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) ret .size __ecp_nistz256_sub_fromx,.-__ecp_nistz256_sub_fromx .type __ecp_nistz256_subx,\@abi-omnipotent .align 32 __ecp_nistz256_subx: xor $t4, $t4 sbb $a0, $t0 sbb $a1, $t1 mov $t0, $a0 sbb $a2, $t2 sbb $a3, $t3 mov $t1, $a1 sbb \$0, $t4 xor $a3 ,$a3 adc \$-1, $t0 mov $t2, $a2 adc $poly1, $t1 adc \$0, $t2 mov $t3, $a3 adc $poly3, $t3 bt \$0, $t4 cmovc $t0, $a0 cmovc $t1, $a1 cmovc $t2, $a2 cmovc $t3, $a3 ret .size __ecp_nistz256_subx,.-__ecp_nistz256_subx .type __ecp_nistz256_mul_by_2x,\@abi-omnipotent .align 32 __ecp_nistz256_mul_by_2x: xor $t4, $t4 adc $a0, $a0 # a0:a3+a0:a3 adc $a1, $a1 mov $a0, $t0 adc $a2, $a2 adc $a3, $a3 mov $a1, $t1 adc \$0, $t4 xor $t3, $t3 sbb \$-1, $a0 mov $a2, $t2 sbb $poly1, $a1 sbb \$0, $a2 mov $a3, $t3 sbb $poly3, $a3 bt \$0, $t4 cmovnc $t0, $a0 cmovnc $t1, $a1 mov $a0, 8*0($r_ptr) cmovnc $t2, $a2 mov $a1, 8*1($r_ptr) cmovnc $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) ret .size __ecp_nistz256_mul_by_2x,.-__ecp_nistz256_mul_by_2x ___ } &gen_double("x"); &gen_add("x"); &gen_add_affine("x"); } }}} $code =~ s/\`([^\`]*)\`/eval $1/gem; print $code; close STDOUT;
jdgarcia/nodegit
vendor/openssl/openssl/crypto/ec/asm/ecp_nistz256-x86_64.pl
Perl
mit
68,125
% | ———————————————————————————————————————————————————————————————————————————— % | # 1 - xreverse % | % | ## References % | http://learnprolognow.org/lpnpage.php?pagetype=html&pageid=lpn-htmlse25 % | % | ## Notes % | Common pattern used in solution, detailed comments included to % | demonstrate thorough understanding as per academic integrity. % | ———————————————————————————————————————————————————————————————————————————— % Use accumulator pattern, acummulating the solution's elements into empty list. xreverse(L,R):- xreverseAcc(L,[],R). % Deconstruct the given list into head and tail, then recursively take the head % of each successive tail as the head of the provided accumulator list. xreverseAcc([H|T],A,R):- xreverseAcc(T,[H|A],R). % Base case is true if accumulated solution list (A) matches reversed list (R). % If R is not provided, this will set the value of R to A so as to return R = A. xreverseAcc([],A,A).
commande/cmput325
asn3/1255891.pl
Perl
mit
1,238
# $Id: Cipher.pm,v 1.12 2008/09/24 19:21:20 turnstep Exp $ package Net::SSH::Perl::Cipher; use strict; use Carp qw( croak ); use vars qw( %CIPHERS %CIPHERS_SSH2 %CIPH_REVERSE %SUPPORTED ); BEGIN { %CIPHERS = ( None => 0, IDEA => 1, DES => 2, DES3 => 3, RC4 => 5, Blowfish => 6, ); %CIPHERS_SSH2 = ( '3des-cbc' => 'DES3', 'blowfish-cbc' => 'Blowfish', 'arcfour' => 'RC4', ); %CIPH_REVERSE = reverse %CIPHERS; } sub _determine_supported { for my $ciph (keys %CIPHERS) { my $pack = sprintf "%s::%s", __PACKAGE__, $ciph; eval "use $pack"; $SUPPORTED{$CIPHERS{$ciph}}++ unless $@; } } sub new { my $class = shift; my $type = shift; my($ciph); unless ($type eq "None") { $type = $CIPHERS_SSH2{$type} || $type; my $ciph_class = join '::', __PACKAGE__, $type; (my $lib = $ciph_class . ".pm") =~ s!::!/!g; require $lib; $ciph = $ciph_class->new(@_); } else { $ciph = bless { }, __PACKAGE__; } $ciph; } sub new_from_key_str { my $class = shift; eval "use Digest::MD5 qw( md5 );"; defined $_[1] ? $class->new($_[0], md5($_[1])) : $class->new(@_); } sub enabled { $_[0]->{enabled} } sub enable { $_[0]->{enabled} = 1 } sub id { my $this = shift; my $type; if (my $class = ref $this) { my $pack = __PACKAGE__; ($type = $class) =~ s/^${pack}:://; } else { $type = $this; } $CIPHERS{$type}; } sub name { my $this = shift; my $name; if (my $class = ref $this) { my $pack = __PACKAGE__; ($name = $class) =~ s/^${pack}:://; } else { $name = $CIPH_REVERSE{$this}; } $name; } sub mask { my $mask = 0; $mask |= (1<<$_) for keys %SUPPORTED; $mask; } sub supported { unless (keys %SUPPORTED) { _determine_supported(); } my $protocol = 1; shift, $protocol = shift if not ref $_[0] and $_[0] and $_[0] eq 'protocol'; unless(@_) { return [ keys %SUPPORTED ] unless 2 == $protocol; return [ grep $SUPPORTED{$_}, map $CIPHERS{$_}, values %CIPHERS_SSH2 ]; } my $id = ref $_[0] ? shift->id : shift; return $id == 0 || exists $SUPPORTED{$id} unless @_; my $ssupp = shift; mask() & $ssupp & (1 << $id); } sub encrypt { $_[1] } sub decrypt { $_[1] } 1; __END__ =head1 NAME Net::SSH::Perl::Cipher - Base cipher class, plus utility methods =head1 SYNOPSIS use Net::SSH::Perl::Cipher; # Get list of supported cipher IDs. my $supported = Net::SSH::Perl::Cipher::supported(); # Translate a cipher name into an ID. my $id = Net::SSH::Perl::Cipher::id($name); # Translate a cipher ID into a name. my $name = Net::SSH::Perl::Cipher::name($id); =head1 DESCRIPTION I<Net::SSH::Perl::Cipher> provides a base class for each of the encryption cipher classes. In addition, it defines a set of utility methods that can be called either as functions or object methods. =head1 UTILITY METHODS =head2 supported( [ protocol => $protocol, ] [ $ciph_id [, $server_supports ] ]) Without arguments returns a reference to an array of ciphers supported by I<Net::SSH::Perl>. These are ciphers that have working Net::SSH::Perl::Cipher:: implementations, essentially. Pass 'protocol => 2' to get a list of SSH2 ciphers. With one argument I<$ciph_id>, returns a true value if that cipher is supported by I<Net::SSH::Perl>, and false otherwise. With two arguments, I<$ciph_id> and I<$server_supports>, returns true if the cipher represented by I<$ciph_id> is supported both by I<Net::SSH::Perl> and by the sshd server. The list of ciphers supported by the server should be in I<$server_supports>, a bit mask sent from the server during the session identification phase. Can be called either as a non-exported function, i.e. my $i_support = Net::SSH::Perl::Cipher::supported(); or as an object method of a I<Net::SSH::Perl::Cipher> object, or an object of a subclass: if ($ciph->supported($server_supports)) { print "Server supports cipher $ciph"; } =head2 id( [ $cipher_name ] ) Translates a cipher name into a cipher ID. If given I<$cipher_name> translates that name into the corresponding ID. If called as an object method, translates the object's cipher class name into the ID. =head2 name( [ $cipher_id ] ) Translates a cipher ID into a cipher name. If given I<$cipher_id> translates that ID into the corresponding name. If called as an object method, returns the (stripped) object's cipher class name; for example, if the object were of type I<Net::SSH::Perl::Cipher::IDEA>, I<name> would return I<IDEA>. =head1 CIPHER USAGE =head2 Net::SSH::Perl::Cipher->new($cipher_name, $key) Instantiates a new cipher object of the type I<$cipher_name> with the key I<$key>; returns the cipher object, which will be blessed into the actual cipher subclass. If I<$cipher_name> is the special type I<'None'> (no encryption cipher), the object will actually be blessed directly into the base class, and text to be encrypted and decrypted will be passed through without change. =head2 $cipher->encrypt($text) Encrypts I<$text> and returns the encrypted string. =head2 $cipher->decrypt($text) Decrypts I<$text> and returns the decrypted string. =head1 CIPHER DEVELOPMENT Classes implementing an encryption cipher must implement the following three methods: =over 4 =item * $class->new($key) Given a key I<$key>, should construct a new cipher object and bless it into I<$class>, presumably. =item * $cipher->encrypt($text) Given plain text I<$text>, should encrypt the text and return the encrypted string. =item * $cipher->decrypt($text) Given encrypted text I<$text>, should decrypt the text and return the decrypted string. =back =head1 AUTHOR & COPYRIGHTS Please see the Net::SSH::Perl manpage for author, copyright, and license information. =cut
carlgao/lenga
images/lenny64-peon/usr/share/perl5/Net/SSH/Perl/Cipher.pm
Perl
mit
6,006
#!/usr/bin/env perl =head1 NAME UpdateMetadataMdImageTableCharacterLength.pm =head1 SYNOPSIS mx-run UpdateMetadataMdImageTableCharacterLength [options] -H hostname -D dbname -u username [-F] this is a subclass of L<CXGN::Metadata::Dbpatch> see the perldoc of parent class for more details. =head1 DESCRIPTION This patch changes fields character length to greater than 100 chars This subclass uses L<Moose>. The parent class uses L<MooseX::Runnable> =head1 AUTHOR =head1 COPYRIGHT & LICENSE Copyright 2010 Boyce Thompson Institute for Plant Research This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut package UpdateMetadataMdImageTableCharacterLength; use Moose; extends 'CXGN::Metadata::Dbpatch'; has '+description' => ( default => <<''); This patch changes fields character length to greater than 100 chars has '+prereq' => ( default => sub { [], }, ); sub patch { my $self=shift; print STDOUT "Executing the patch:\n " . $self->name . ".\n\nDescription:\n ". $self->description . ".\n\nExecuted by:\n " . $self->username . " ."; print STDOUT "\nChecking if this db_patch was executed before or if previous db_patches have been executed.\n"; print STDOUT "\nExecuting the SQL commands.\n"; $self->dbh->do(<<EOSQL); ALTER TABLE metadata.md_image ALTER COLUMN original_filename TYPE varchar (250); ALTER TABLE metadata.md_image ALTER COLUMN name TYPE varchar (250); EOSQL print "You're done!\n"; } #### 1; # ####
solgenomics/sgn
db/00144/UpdateMetadataMdImageTableCharacterLength.pm
Perl
mit
1,554
# # $Header: svn://svn/SWM/trunk/web/PMSHold.pm 8251 2013-04-08 09:00:53Z rlee $ # package PMSHold; require Exporter; @ISA = qw(Exporter); @EXPORT=qw(checkForPMSHolds createPMSMassPayHold updatePMSHolds releasePMSHold finaliseRelease); @EXPORT_OK=qw(checkForPMSHolds createPMSMassPayHold updatePMSHolds releasePMSHold finaliseRelease); use strict; use Reg_common; use Utils; use DeQuote; use CGI qw(param); use CGI qw(param unescape escape); sub checkForPMSHolds { my ($db, $realmID, $paymentType) = @_; $paymentType ||= $Defs::PAYMENT_ONLINEPAYPAL; my %Holds=(); my $st = qq[ SELECT DISTINCT PH.strMassPayEmail, PH.strBSB, PH.strAccNum, PH.strAccName FROM tblPMSHold as PH INNER JOIN tblTransLog as TL ON ( TL.intLogID= PH.intTransLogOnHoldID ) WHERE PH.intHoldStatus=0 AND PH.intRealmID=? AND TL.intPaymentType=$paymentType AND PH.curBalanceToHold>0 ]; my $qry= $db->prepare($st) or query_error($st); $qry->execute($realmID) or query_error($st); my $count=0; while (my $dref=$qry->fetchrow_hashref()) { my $key = $dref->{strMassPayEmail}; if ($dref->{strBSB} and $dref->{strAccNum}) { $key = $dref->{strBSB} . qq[|] . $dref->{strAccNum} . qq[|] . $dref->{strAccName}; } $Holds{$key}=0 if ! ($Holds{$dref->{strMassPayEmail}} and $paymentType == $Defs::PAYMENT_ONLINEPAYPAL); $Holds{$key}=0 if ! ($Holds{$dref->{strBSB}} and $paymentType == $Defs::PAYMENT_ONLINEPAYNAB); $Holds{$key}++; } return \%Holds; } sub createPMSMassPayHold { my ($db, $realmID, $exportBankFileID, $email, $totalSending, $paymentType) = @_; $paymentType ||= $Defs::PAYMENT_ONLINEPAYPAL; my $totalAmount = $totalSending; my $qry =''; if ($paymentType == $Defs::PAYMENT_ONLINENAB) { my ($bsb, $accNum, $accountName) = split /\|/,$email; my $st = qq[ SELECT intPMSHoldingBayID, curBalanceToHold, curAmountToHold FROM tblPMSHold WHERE intRealmID=? AND strBSB=? AND strAccNum=? AND intHoldStatus=0 AND curBalanceToHold>0 ORDER BY dtHeld ]; $qry= $db->prepare($st) or query_error($st); $qry->execute($realmID, $bsb, $accNum) or query_error($st); } else { my $st = qq[ SELECT intPMSHoldingBayID, curBalanceToHold, curAmountToHold FROM tblPMSHold WHERE intRealmID=? AND strMassPayEmail=? AND intHoldStatus=0 AND curBalanceToHold>0 ORDER BY dtHeld ]; $qry= $db->prepare($st) or query_error($st); $qry->execute($realmID, $email) or query_error($st); } my $st_ins = qq[ INSERT INTO tblPMS_MassPayHolds ( intPMSHoldingBayID, curHold, intMassPayHeldOnID, intRealmID, dtHeld ) VALUES ( ?, ?, $exportBankFileID, $realmID, NOW() ) ]; my $qry_ins= $db->prepare($st_ins) or query_error($st_ins); my $totalBeingHeld=0; while (my $dref=$qry->fetchrow_hashref()) { last if ! $totalAmount; my $balanceToHold = 0; if ($dref->{'curBalanceToHold'} <= $totalAmount) { $balanceToHold = $dref->{'curBalanceToHold'} || $dref->{'curAmountToHold'} || 0; } else { $balanceToHold = $totalAmount; } $totalBeingHeld=$totalBeingHeld+$balanceToHold; $totalAmount=$totalAmount-$balanceToHold; next if ! $balanceToHold; $qry_ins->execute($dref->{'intPMSHoldingBayID'}, $balanceToHold) or query_error($st_ins); } $totalSending-=$totalBeingHeld; return $totalSending; } sub updatePMSHolds { my ($db, $realmID, $exportBankFileID, $status) = @_; my $st = qq[ UPDATE tblPMS_MassPayHolds SET intHoldStatus=$status WHERE intMassPayHeldOnID =$exportBankFileID ]; $db->do($st); if ($status == 1) { ## Lets update Balance remaining my $st = qq[ SELECT DISTINCT intPMSHoldingBayID FROM tblPMS_MassPayHolds WHERE intMassPayHeldOnID = ? AND intHoldStatus = 1 ]; my $qry= $db->prepare($st) or query_error($st); $qry->execute($exportBankFileID) or query_error($st); while (my $dref=$qry->fetchrow_hashref()) { recalculatePMSHold($db, $dref->{'intPMSHoldingBayID'}); } } sub recalculatePMSHold { my ($db, $holdID) = @_; my $st = qq[ SELECT SUM(curHold) as HeldAmount FROM tblPMS_MassPayHolds WHERE intPMSHoldingBayID= ? AND intHoldStatus = 1 ]; my $qry= $db->prepare($st) or query_error($st); $qry->execute($holdID) or query_error($st); my $amountHeld = $qry->fetchrow_array() || 0; $st = qq[ UPDATE tblPMSHold SET curBalanceToHold = curAmountToHold-$amountHeld WHERE intPMSHoldingBayID = $holdID LIMIT 1 ]; $db->do($st); } sub releasePMSHold { my ($db, $realmID, $paymentType) = @_; $paymentType ||= $Defs::PAYMENT_ONLINEPAYPAL; my $bsbWHERE = ($paymentType == $Defs::PAYMENT_ONLINENAB) ? qq[ AND PH.strBSB LIKE '08%'] : ''; my $st = qq[ SELECT PH.intPMSHoldingBayID, strMassPayEmail, PH.strBSB, PH.strAccNum, PH.strAccName, SUM(curHold) as AmountHeld FROM tblPMSHold as PH INNER JOIN tblPMS_MassPayHolds as MPH ON ( MPH.intPMSHoldingBayID= PH.intPMSHoldingBayID AND MPH.intHoldStatus>0 ) INNER JOIN tblTransLog as TL ON ( TL.intLogID= PH.intTransLogOnHoldID ) WHERE PH.intRealmID=$realmID AND PH.intMassPayReturnedOnID = 0 AND PH.intHoldStatus=2 AND TL.intPaymentType = $paymentType $bsbWHERE GROUP BY PH.intPMSHoldingBayID HAVING AmountHeld>0 ]; my $qry= $db->prepare($st) or query_error($st); $qry->execute() or query_error($st); my %ReleaseHolds=(); while (my $dref=$qry->fetchrow_hashref()) { $ReleaseHolds{$dref->{'intPMSHoldingBayID'}}{'amountheld'} = $dref->{'AmountHeld'}; $ReleaseHolds{$dref->{'intPMSHoldingBayID'}}{'email'} = $dref->{'strMassPayEmail'}; $ReleaseHolds{$dref->{'intPMSHoldingBayID'}}{'bsb'} = $dref->{'strBSB'}; $ReleaseHolds{$dref->{'intPMSHoldingBayID'}}{'accNum'} = $dref->{'strAccNum'}; $ReleaseHolds{$dref->{'intPMSHoldingBayID'}}{'accName'} = $dref->{'strAccName'}; } return \%ReleaseHolds; } sub finaliseRelease { my ($db, $holdID, $realmID, $exportBankFileID) = @_; $holdID ||= 0; $exportBankFileID ||= 0; return if (!$holdID or !$exportBankFileID); my $st = qq[ UPDATE tblPMSHold SET intMassPayReturnedOnID =$exportBankFileID WHERE intPMSHoldingBayID=$holdID AND intHoldStatus=2 AND intMassPayReturnedOnID=0 ]; $db->do($st); } }
facascante/slimerp
fifs/web/PMSHold.pm
Perl
mit
7,560
#!/usr/bin/perl use strict; use warnings; use Getopt::Long; ## Author: Qiang Gong <qgong@coh.org> my $file = shift or &usage; my ( $help, $ext, $int_file ); $ext = 10; GetOptions( 'extension=i' => \$ext, 'interval=s' => \$int_file, 'help!' => \$help, ); &usage if $help; &usage unless $int_file; &usage if $file =~ /^-\S+/; my %itpos; open IN, $int_file or die($!); while (<IN>) { chomp; my ( $c, $p1, $p2 ) = split; for ( my $i = $p1 - $ext ; $i <= $p2 + $ext ; $i++ ) { my $k = join ":", $c, $i; my $v; if ( $i > $p2 ) { $v = join "", "+", $i - $p2, ","; } else { $v = join "", $i - $p1, ","; } $itpos{$k} .= $v; } } close IN; open IN, $file or die($!); while (<IN>) { chomp; my @a = split; my $k = join ":", @a[ 0 .. 1 ]; if ( exists $itpos{$k} ) { print join "\t", @a, $itpos{$k}; } else { print join "\t", @a, "Out-of-Range"; } print "\n"; } close IN; sub usage { die( qq/ Usage: probe_pos.pl query.bed(ANNOVAR_style) -i interval_file.bed [-e <int>] OPTIONS: -e|--extension <int>: bps upstream (-) or downstream (+) of the intervals (default: 10) \n/ ); }
littlegq/PerlPrograms
probe_pos.pl
Perl
mit
1,260
#!/usr/bin/perl # ******************************************************************** # * Copyright (C) 2016 and later: Unicode, Inc. and others. # * License & terms of use: http://www.unicode.org/copyright.html#License # ******************************************************************** # ******************************************************************** # * COPYRIGHT: # * Copyright (c) 2002-2013, International Business Machines Corporation and # * others. All Rights Reserved. # ******************************************************************** #use strict; require "../perldriver/Common.pl"; use lib '../perldriver'; use PerfFramework; my $options = { "title"=>"Character property performance: ICU".$ICULatestVersion." vs. STDLib", "headers"=>"StdLib ICU".$ICULatestVersion, "operationIs"=>"code point", "timePerOperationIs"=>"Time per code point", "passes"=>"10", "time"=>"5", #"outputType"=>"HTML", "dataDir"=>"Not Using Data Files", "outputDir"=>"../results" }; # programs # tests will be done for all the programs. Results will be stored and connected my $p; if ($OnWindows) { $p = "cd ".$ICULatest."/bin && ".$ICUPathLatest."/charperf/$WindowsPlatform/Release/charperf.exe"; } else { $p = "LD_LIBRARY_PATH=".$ICULatest."/source/lib:".$ICULatest."/source/tools/ctestfw ".$ICUPathLatest."/charperf/charperf"; } my $tests = { "isAlpha", ["$p,TestStdLibIsAlpha" , "$p,TestIsAlpha" ], "isUpper", ["$p,TestStdLibIsUpper" , "$p,TestIsUpper" ], "isLower", ["$p,TestStdLibIsLower" , "$p,TestIsLower" ], "isDigit", ["$p,TestStdLibIsDigit" , "$p,TestIsDigit" ], "isSpace", ["$p,TestStdLibIsSpace" , "$p,TestIsSpace" ], "isAlphaNumeric", ["$p,TestStdLibIsAlphaNumeric" , "$p,TestIsAlphaNumeric" ], "isPrint", ["$p,TestStdLibIsPrint" , "$p,TestIsPrint" ], "isControl", ["$p,TestStdLibIsControl" , "$p,TestIsControl" ], "toLower", ["$p,TestStdLibToLower" , "$p,TestToLower" ], "toUpper", ["$p,TestStdLibToUpper" , "$p,TestToUpper" ], "isWhiteSpace", ["$p,TestStdLibIsWhiteSpace" , "$p,TestIsWhiteSpace" ], }; my $dataFiles; runTests($options, $tests, $dataFiles);
quyse/flaw
flaw-font-icu/src/icu/source/test/perf/charperf/CharPerf.pl
Perl
mit
2,368
#!/usr/bin/perl -w # *************************************************************************************** # FUNCTION: Upload, check and process cytogenetics Sample Report files to produce a # tab separated values (tsv) file in a user defined format (see example file). # # ARGUMENTS: Cytogenetics Sample Report file (xml format) and the respective # Interval Based Report (IBR) file (xls extension; tab delimited format) # # RETURNS: Uploads the input Sample Report (xml) and IBR (xls) files. # Produces an excel workbook as temporary file in folder /tmp/ # Converts excel workbook into tab separated values file (txt) in folder /var/www/Upload # Deletes uploaded Sample Report (xml) and IBR (xls) files. # Returns html file to browser with acknowledgement of processing and prompts # the user to restart with different files. # # NOTES: The web page cytoReport.html is used to upload the two input files and direct # filenames as arguments to this file using the perl CGI module. # Secure mode -T was disabled so that system commands could be passed to convert # the excel workbook to csv (ssconvert), change comma separators to tab separators # and change line separators from linefeed to "|" (vertical tab symbol). # The input files and the csv file are deleted after processing. # # *************************************************************************************** use strict; use warnings; use CGI qw(:standard); use CGI::Carp qw (warningsToBrowser fatalsToBrowser); use File::Basename; use XML::LibXML; use Spreadsheet::WriteExcel; use Text::CSV; $CGI::POST_MAX = 1024 * 5000; # limit the allowable size of an uploaded file to 5MB ###################################################################################### sub error { # FUNCTION: pass error messages to browser # REQUIRES: query object ($q) and string with error message ($reason) as arguments # USAGE: error($q, $error); my( $q, $reason ) = @_; print $q->header( "text/html" ), $q->start_html( "Error" ), $q->h1( "Error" ), $q->p( "Your upload was not processed because the following error occured:\n" ), $q->p( $q->i( $reason ) ), $q->p( "Please, try again.\n" ), $q->end_html; exit; }## end sub error ####################################################################################### ####################################################################################### sub wash_filename { # FUNCTION: clean file name from unsafe characters and spaces # REQUIRES: file name from file handle object $file # USAGE: wash_filename ($file); my $filename = shift(); # create a list of “safe” characters for filenames my $safe_filename_characters = "a-zA-Z0-9_.-"; # make the filename safe: # use the fileparse routine in the File::Basename module to split the filename into its # leading path (if any), the filename itself, and the file extension # regex '..*' means a literal period (.) followed by zero or more characters my ( $name, $path, $extension ) = fileparse ( $filename, '..*' ); $filename = $name . $extension; # clean up the filename to remove any characters that aren’t safe # convert spaces to underscore characters $filename =~ tr/ /_/; $filename =~ s/[^$safe_filename_characters]//g; #use regular expression matching to extract the safe characters if ( $filename =~ /^([$safe_filename_characters]+)$/ ){ $filename = $1; }else{ # extra caution: filename should not have any unsafe characters at this point die "Filenames contains invalid characters"; #safeguard NOT WORKING } return $filename; } ## end sub wash_filename ########################################################################################## ########################################################################################## # create a CGI object to read in the names of the files and the name of the user # from the html page my $query = new CGI (); my @files = $query->param('multiple_files'); if (scalar(@files) < 2){ error( $query, "Expected two files but only one file was selected." ); } ####################################################################### ########################################################################################### # Upload files to server ################# my $upload_dir = "/var/www/Upload/"; # a location on the server to store the uploaded files # Make sure the directory can be read and written to by the script # on a shared UNIX server # initialise clean file names my $xml_file = ''; my $xls_file = ''; foreach my $file (@files) { # test if $filename exists and report a problem if ( !$file ){ error( $query, "There was a problem uploading one of the files."); } # test file extension and exit if not xml or xls # use regex to check file extensions unless (($file =~ /\.xml$/i) or ($file =~ /\.xls$/i)){ error ( $query, "Unexpected file extension." ); exit; } } #upload files with safe names foreach my $file (@files) { my $safeFilename = wash_filename ($file); my $serverFullFilename = $upload_dir.$safeFilename; # read file and save it to the upload folder # if there’s an error writing the file, the 'die' function stops the script running # and reports the error message (stored in the special variable $!) open ( UPLOADFILE, ">$serverFullFilename" ) or die "$!"; # the binmode function tells Perl to write the file in binary mode, rather than in text mode # to prevent the uploaded file from being corrupted on non-UNIX servers (such as Windows machines) binmode UPLOADFILE; # use the value returned by param (in this case $file) # as a file handle in order to read from the file while ( <$file> ){ if ($file =~ /\.xml$/i) { # regex to match file extension to xml $xml_file = $safeFilename; print UPLOADFILE; } elsif ($file =~ /\.xls$/i){ # regex to match file extension to xls $xls_file = $safeFilename; print UPLOADFILE; } } close UPLOADFILE; } ############################################################################################ ############################################################################################ # File location and file name variables ############################### # INPUT and OUTPUT file names and paths my $input_dir = $upload_dir; #$input_dir = "/var/www/Upload/"; # INPUT IntervalBasedReport (ibr) file (.xls) my $ibrpath = $input_dir.$xls_file; # INPUT .xml file my $xmlpath = $input_dir.$xml_file; # OUTPUT to excel workbook and csv file # name files according to xml file name (remove .xml extension and add other extension) my @xml_namepart = split /[.]/, $xml_file; my $reportname = $xml_namepart[0]; # output xls file name and path my $xlsdir = "/tmp/"; my $outxls = $reportname."_processed.xls"; my $xlspath = $xlsdir."$outxls"; # output csvfile name and path my $outdir = "/var/www/Upload/"; my $outcsv = $reportname."_processed.csv"; my $csvpath = $outdir."$outcsv"; # output tab separated values file name (extension txt) and path my $outtxt = $reportname."_processed.txt"; my $txtpath = $outdir."$outtxt"; ############################################################################################ ############################################################################################ # Create Document Object Model (DOM) and find nodes in XML file; # Populate data structures %sample_info and %aberrations_info # my $parser = XML::LibXML->new(); my $xmldoc = $parser->parse_file($xmlpath); #check that xml file was parsed unless ($xmldoc){ error ( $query, "Could not open xml file." ); #print "ERROR: Could not open xml file : $!\n"; exit; } # Check if it is the right type of xml file my $header = $xmldoc->findnodes('/report/header/text'); my $str_header = sprintf("%s", $header); # use sprintf to convert $header to string unless ( $str_header =~ /OXFORD GENETICS LABORATORIES-CYTOGENETICS/){ system("rm '$ibrpath' '$xmlpath' "); error( $query, "The xml file had unexpected content. Please upload a signed off xml report."); exit; } # initialise hashes my %sample_info = (); my %aberrations_info = (); ###################### #%sample_info #SampleID my $sampleID = $xmldoc->findnodes('/report/header/headerattribValue'); $sample_info{'SampleID'} = sprintf("%s", $sampleID); #use sprintf to convert to string #Analysis method my $method = $xmldoc->findnodes('/report/footer/analysisMethod'); $sample_info{'AnalysisMethod'} = sprintf("%s", $method); #Polarity my $pol = $xmldoc->findnodes("/report/sections/section/ tname[text( )='sampleInformation']/../ sampleInformation/data/pair/ name[text( )='Polarity']/../value/text( )"); $sample_info{'Polarity'} = sprintf("%s", $pol); #ScanDate my $date = $xmldoc->findnodes("/report/sections/section/ tname[text( )='sampleInformation']/../ sampleInformation/data/pair/ name[text( )='Scan_Date']/../value/text( )"); $sample_info{'ScanDate'} = sprintf("%s", $date); #DLRSpread my $dlrs = $xmldoc->findnodes("/report/sections/section/ tname[text( )='sampleInformation']/../ sampleInformation/QcMetricTables/QcMetricTable/QcMetric/ QcMetricName[text( )='DerivativeLR_Spread']/../QcMetricValue/text( )"); $sample_info{'DLRSpread'} = sprintf("%s", $dlrs); ###################### #%aberrations_info my @aberrations = $xmldoc->findnodes("/report/sections/section/ tname[text( )='tableView']/../ sample/chromosomes/chromosome/aberrations/aberration"); my $aberration_count = 1; my @aberration_char = ('chr', 'location', 'size', 'cytoband', 'probes', 'type', 'amplification', 'deletion', 'classification'); #for each aberration entry, find value and add pair aberration_char = value to %aberrations_info foreach my $aberration (@aberrations){ foreach my $char (@aberration_char){ my $char_value = $aberration->findvalue('./'.$char); $aberrations_info{$aberration_count}{$char} = $char_value; } $aberration_count++; } ########################################################################################## ########################################################################################## # OPEN interval based report (ibr) file # Get GenomeBuild and gene list for each variant into %lookup_genes unless (open (FILE, $ibrpath)){ error ( $query, "Could not open Interval Based Report file." ); #print "ERROR: Could not open Interval Based Report file: $!\n"; exit; } my $fileline; my @line_data; while ($fileline = <FILE>){ # read in each line in the file chomp($fileline); # remove the ending to new line #print "$fileline"; push @line_data, $fileline; # generate array of lines } close FILE; # Get lines that contain "sample info: value" my @info_lines = grep { /.*:/ } @line_data; #match any character except new line(.), 0 or more times (*), followed by a : (:) # Get GenomeBuild and add it to %sample_info key = value pairs my @build = split (/: /, $info_lines[0]); $sample_info{'GenomeBuild'} = sprintf("%s", $build[1]); # Get aberrations my @aberration_lines = grep { /^[1-9]+/ } @line_data; #match any number ([1-9]+) at begining of line (^) # initialise hash to store gene lists (pair variant=>genes) my %lookup_genes = (); foreach my $aberration (@aberration_lines){ my @variant_char = split (/\t/, $aberration); my $chr = $variant_char[1]; $chr =~ s/[chr]//g; # remove 'chr' from $chr my $cytoband = $variant_char[2]; $cytoband =~ s/\s[-]\s//g; #?remove ' - ' from cytoband string my $start = $variant_char[3]; $start =~ s/[,]//g; # remove ',' from $start my $stop = $variant_char[4]; $stop =~ s/[,]//g; # remove ',' from $stop my $location = $start."-".$stop; my $variant = $chr.$cytoband."(".$location.")"; #corresponds to variant description in xls and is used to get genes my $genes = $variant_char[11]; # Add pair variant=>genes to hash %variant2genes $lookup_genes{$variant} = $genes; } ######################################################################################## ######################################################################################## # Create Excel workbook # Create a new workbook my $workbook = Spreadsheet::WriteExcel->new($xlspath); #check the return value of new before proceeding die "Problems creating new Excel file: $!" unless defined $workbook; #Format headers in worksheets my %format = (); $format{'header'} = $workbook->add_format(); $format{'header'}->set_bold(); # Add worksheet and respective headers my $worksheet = $workbook->add_worksheet("Report"); my @sample_headers = ("SampleID", "AnalysisMethod", "DLRSpread", "Polarity", "ScanDate", "GenomeBuild"); my @report_headers = ("Variant", "Chromosome", "Start", "Stop", "Cytoband", "#Probes", "Size", "Type", "Amp/Del", "Classification", "Genes", "Notes"); $worksheet->write_col(0, 0, \@sample_headers, $format{'header'}); $worksheet->write_row(7, 0, \@report_headers, $format{'header'}); ########################################################################################### ############################################################################################ # Write to workbook # #Sample Information for (my $i=0; $i <= (scalar(@sample_headers))-1; $i++) { #line $i, column 1; count starts at zero) $worksheet->write($i, 1, $sample_info{$sample_headers[$i]}); #get values from sample_info hash } # Aberration Information # line count starts at 8; column count starts at 0) # reminder: my @report_headers = ("Variant", "Chromosome", "Start", "Stop", "Cytoband", "#Probes", "Size", "Type", "Amp/Del", "Classification", "Genes", "Notes"); my $line = 8; # first destination line for aberration details in worksheet foreach my $key (sort keys (%aberrations_info)){ my $chr_number; # initialise variable to register chromosome coordinate my $variant; # initialise variable for variant name; needed to retrieve genes from %lookup_genes my $ISCN_variant; #initialise variant ICSN nomenclature my $xvariant; # initialise variable to add amp/del to variant ISCN numenclature my $genes; # initialise variable to add genes to column 10 my $interval2note; # initialise variable for interval, to retrieve interval note to column 11 foreach my $header (sort keys %{$aberrations_info{$key}}){ # print $header, " = ", $aberrations_info{$key}{$header}, "\n"; if ($header eq 'chr'){ $chr_number = $aberrations_info{$key}{$header}; # column 1 $worksheet->write($line, 1, $chr_number); # add $chr_number to $interval2note string $interval2note.= $chr_number.":"; # add $chr_number to $variant and $ISCN_variant $chr_number =~ s/[chr]//g; # remove 'chr' from $chr_number $variant.= $chr_number; $ISCN_variant.= $chr_number; } if ($header eq 'cytoband'){ # get cytoband and remove ' - ' from $cytoband for ISCN nomenclature my $cytoband = $aberrations_info{$key}{$header}; $cytoband =~ s/\s[-]\s//g; # column 4 $worksheet->write($line, 4, $cytoband); # add $cytoband to $variant string $variant .= $cytoband; $ISCN_variant.= $cytoband; } if ($header eq 'location'){ # get start and stop and add to worksheet at columns 2 and 3, respectively my $location = $aberrations_info{$key}{$header}; # variant nummenclature used to retrieve genes in %lookup_genes $variant .= "(".$location.")"; #print "variant: ", $variant, "\n"; my @start_stop = split(/-/, $location); my $start = $start_stop[0]; $worksheet->write($line, 2, $start); my $stop = $start_stop[1]; $worksheet->write($line, 3, $stop); # variant nomenclature with start_stop notation my $underscore_location = $start."_".$stop; # add $underscore_location to $ISCN_variant string $ISCN_variant .= "(".$underscore_location.")"; # add $location to $interval2note string $interval2note .= $location; #print "interval2note: ", $interval2note, "\n"; } if ($header eq 'probes'){ # column 5 $worksheet->write($line, 5, $aberrations_info{$key}{$header}); } if ($header eq 'size'){ my $size = $aberrations_info{$key}{$header}; # to remove ',' from $size $size =~ s/[,]//g; # column 6 $worksheet->write($line, 6, $size); } if ($header eq 'type'){ # column 7 $worksheet->write($line, 7, $aberrations_info{$key}{$header}); if ($aberrations_info{$key}{$header} eq 'Gain'){ my $amplification = $aberrations_info{$key}{'amplification'}; # column 8 $worksheet->write($line, 8, $amplification); # add amplification times to $ISCN_variant if ($amplification >= 0 and $amplification < 0.40){ $xvariant = $ISCN_variant."x2"; } if ($amplification >= 0.40 and $amplification < 0.75){ $xvariant = $ISCN_variant."x3"; } if ($amplification >= 0.75){ $xvariant = $ISCN_variant."x4"; } }elsif ($aberrations_info{$key}{$header} eq 'Loss'){ my $deletion = $aberrations_info{$key}{'deletion'}; # column 8 $worksheet->write($line, 8, $deletion); # add deletion times to $ISCN_variant if ($deletion > -0.70 and $deletion <= 0){ $xvariant = $ISCN_variant."x2"; } if ($deletion > -2.00 and $deletion <= -0.70){ $xvariant = $ISCN_variant."x1"; } if ($deletion <= -2.00){ $xvariant = $ISCN_variant."x0"; } } } if ($header eq 'classification'){ # column 9 $worksheet->write($line, 9, $aberrations_info{$key}{$header}); } } # variant name in column 0 unless ($chr_number eq 'X' | $chr_number eq 'Y'){ $worksheet->write($line, 0, $xvariant); }else{ $worksheet->write($line, 0, $ISCN_variant); } # variant genes in column 10 if (exists ($lookup_genes{$variant})){ $genes = $lookup_genes{$variant}; $worksheet->write($line, 10, $genes); } # get notes for $interval my $notes = $xmldoc->findnodes("/report/notes/intervalsNotes/intervalNote/ interval[text( )= '$interval2note' ]/../note/noteText"); my $separator = '; '; $separator =~ s/[ ]/\n/g; #regex to substitute space in $separator by newline - results in each note starting in a new line my $separatedNotes = $notes->to_literal_delimited($separator); #regex to remove the double hyphen '--' found when word coincides with a line break $separatedNotes =~ s/-\n-//g; #regex to replace 'en dash' (looks longer than a minus sign; is causing parsing problems) by an 'hyphen' (-) $separatedNotes =~ s/\x{2013}/-/g; #column 11 $worksheet->write($line, 11, $separatedNotes); #line counter increase $line++; } $workbook->close(); ########################################################################################### ####################################################################### # Use system tools to convert Excel workbook to txt file ################### system("ssconvert '$xlspath' '$csvpath'"); ########################################################################################### #Convert csv file to file with tab separated values and use | as end of line (eol) ############################ my $csv = Text::CSV->new ({ binary => 1 }); my $txt = Text::CSV->new ({ binary => 1, sep_char => "\t", eol => "|"}); open my $infh, "<:encoding(utf8)", "$csvpath"; open my $outfh, ">:encoding(utf8)", "$txtpath"; while (my $row = $csv->getline ($infh)) { $txt->print ($outfh, $row); } ########################################################################################## # Use system tools to delete input files and the csv file ################### system("rm '$ibrpath' '$xmlpath' '$csvpath' "); ########################################################################################## ########################################################################################## #Thank you note - acknowledge upload of files and processing ########################### print $query->header ( ); print <<END_HTML; <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Thanks!</title> <style> body { background-color: lightblue; } h1 { color: white; text-align: center; font-size: 44px; } p { font-size: 20px; text-align: center; } div { background-color: white; padding: 10px; margin: auto; width: 50%; text-align: center; } a:link { background-color: orange; border: none; text-decoration: none; padding: 16px 32px; font-size: 20px; font-weight: bold; cursor: pointer; } </style> </head> <body> <h1>The following files were successfully processed:</h1> <p>Sample Report (.xml):</p> <div>$xml_file</div> <p>Interval Based Report (.xls):</p> <div>$xls_file</div> <p>You can find the output file in the following directory: </p> <div>$outdir</div> <p>Process more files?</p> <p><a href="http://localhost/cytoReport.html">Click here to RESTART</a></p> </body> </html> END_HTML ###################################################################
LauraCarreto/CytoReport
cytoReport_tsv.pl
Perl
mit
21,891
#!/usr/bin/perl #### UNSTABLE (unsolicited) # todo: # -make spam/talk limiters channel-specific # -affection meters per person # -timer # -nickname randomizer # -config parsing # -20 questions: lose state # -trigger word stripper package Bot; use base qw(Bot::BasicBot); use POE; use Switch; use Time::localtime; use warnings; use strict; my @links; my $snacks = 0; my $linkspam = 0; my $talkspam = 0; my $last = ""; my $eavesdropping = 1; my $talking = 1; #======hardcoded shit that you should break into a config file my @OPLIST = ("hvincent", "kortec", "grym", "tpburns"); my $BOSS = "hvincent"; my $LOG = "klog"; #======20 questions my $answer; my $qcap = 20; my $asked = 0; my @qs; my @as; my $knower; my $qlength; #======vocabulary my @bro = ("bro", "broski", "dude", "pal", "chap", "buddy", "kid", "broslice", "homeslice", "brohammed", "brolshevik", "brobama", "broseph", "abroham"); sub bros { my $plural = &talk(\@bro); if ($plural =~ /buddy/) { $plural = "buddie"; } $plural .= "s"; return $plural; } my @affirm = ("sure", "okay", "right", "yeah", "yep", "fine", "alright"); my @neg = ("sorry", "nah", "negatory", "uh-uh", "not now"); my @ask = ("ask", "check with", "pester", "beg"); my @affection = ("<3", "aw thanks, ".&talk(\@bro), ":)"); my @defy = ("i don't have to do anything i don't want to do", "can it, ".&talk(\@bro), "i really only listen to $BOSS", "up yours", "gtfo", "dicks up your ass, ".&talk(\@bro)); my @telloff = ("you have smelly testicles", "if i had a dog as ugly as you, i'd shave his butt and make him walk backwards", "i can't even think of anything to say to you", "what the hell are you even doing here?", "tits or gtfo", "you're uncreative"); my @np = ("my pleasure, ".&talk(\@bro), "sure thing, ".&talk(\@bro), "whatever, no biggie", "all cool", "yep"); my @catchall = ("nothin to say to that, ".&talk(\@bro), "whatever, ".&talk(\@bro), "got nothin, ".&talk(\@bro), "...", "pssht", "yeah try again later, ".&talk(\@bro)); my @greet = ("sup", "hey", "hi", "yo", "how you doin"); my @alpha = ("a", "b", "c", "d", "e", "f", "g", " ", "h", "i", "j", "k", " ", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", " ", " ", " ", "w", "x", "y", "z"); my @usState = ("alabama", "alaska", "arizona", "arkansas", "california", "colorado", "connecticut", "delaware", "florida", "georgia", "hawaii", "idaho", "illinois", "inidiana", "iowa", "kansas", "kentucky", "louisiana", "maine", "maryland", "massachusetts", "michigan", "minnesota", "mississippi", "missouri", "montana", "nebraska", "nevada", "new hampshire", "new jersey", "new mexico", "new york", "north carolina", "north dakota", "ohio", "oklahoma", "oregon", "pennsylvania", "rhode island", "south carolina", "south dakota", "tennessee", "texas", "utah", "vermont", "virginia", "washington", "west virginia", "wisconsin", "wyoming"); my @unsolicited = ("sometimes you guys just bore me to fucking tears", "when was the last time i cared about this shit", "tell me about it", "that's cool, ".&talk(\@bro), "dicks", "ugh", "BUNDESGESETZBLATT", "sigh.", "is that okay?", "i wonder what it's like outside", "no1curr", "fuck it, i'm moving to ".&talk(\@usState)); #======eavesdrop lines my @news = ("what has this world come to", "wowwww.", "didn't this just happen?", "who cares"); my @heart = ("spread the love!", "gaaaaay", "http://images3.wikia.nocookie.net/__cb20120724043925/degrassi/images/8/8d/Gay-seal_large.jpg", "i want some <3, too"); my @exercise = ("spinach and walkies, you fatty", "get swoll!", "get pumped!", "http://willgadd.com/it-doesnt-matter-what-but-do-it/", "shut up and go run or something"); my @food = ("man, now i'm hungry", "if you have food, you better share it with the class", "you're gonna get fat", "come on, ".&talk(\@bro).", don't taunt me with your food talk"); my @mentioned = ("i heard that", "man, i love it when y'all talk about me", "hey, i'm right here", "blah blah blah"); my @work = ("quit slacking off", "be more productive", "shut up and do it"); my @imgur = ("omg i'm trying to break my imgur addiction stop it", "pics pics pics", "sweet shit, ".&talk(\@bro)); #======input parsing my @greeted = ("sup", "hey", "hi", "yo", "how are you", "how you doin", "hello"); #=====overriding sub said { my $self = shift; my $message = shift; if (($message->{body} =~ /http/) && ($message->{who} !~ /$BOSS/)) { &logUrl($self, $message); } if (($message->{body} =~ /^\?/) && ($message->{channel} !~ /giantfuckingqueens/)){ ##20q only works in trhq now return &twentyQ($self, $message); } if ($message->{address}) { if ($message->{body} =~ /go away/) { &banish($self, $message); } elsif ($message->{body} =~ /quit eavesdrop/){ return &toggleEaves; } elsif ($message->{body} =~ /shut up/) { return &toggleTalk; } elsif (($message->{who} =~ /$BOSS/) && ($message->{channel} =~ /msg/ )){ #&log($self, $message); return &boss_priv($self, $message); } elsif ($message->{who} =~ /$BOSS/) { $talkspam = 0; return &boss_pub($self, $message); } elsif ($talking) { return &talkLimiter($self, $message); } } if ($eavesdropping && $talking) { return &eavesdropper ($self, $message); } return; } sub noticed { my $self = shift; my $message = shift; &msg_boss($self, $message, "ugh"); } sub chanjoin { my ($self, $message) = @_; if ($message->{who} !~ $self->{nick}){ if ($message->{who} ~~ @OPLIST) { $self->say(channel => $message->{channel}, body => &giveOps($self, $message)); } } else { my @a = ("awake", "here", "up", "listening", "chillin", "running", "doing alright"); my $verb = $a[rand($#a+1)]; $self->say(channel => $message->{channel}, body => &talk(\@greet).", ".&bros.", i'm $verb now. someone op me up."); return; } } sub chanpart { my ($self, $message) = @_; $self->say(channel => $message->{channel}, body => "good fucking riddance. no more $message->{who}."); } sub help { return "i can't help you; you can only help yourself. but if you're actually getting sick of my bullshit, feel free to tell me to shut up, quit eavesdropping, or go away."; } ####### internal shit here sub talkback { my ($self, $message) = @_; switch ($message->{body}) { case /you suck/ { return "no u"; } case /who are you/ { return "i'm $BOSS"."'s bot"; } case /botsnack/ { if ($snacks < 5 ) { $snacks++; return &talk(\@affection); } else { $snacks = 0; return "i'm going to get fat, ".&talk(\@bro); } } case /be nice/ { return "i'm a fucking bot, i have no emotions."; } case /back.*cave/ { return &talk(\@defy); } case /get.*out/ { return &talk(\@defy); } case /<3/ { return "don't try to buy my love, ".&talk(\@bro); } case /dicks up my ass/ { return "if you say so, $message->{who}"; } case /dicks up your ass/ { return "hey, that's my line!"; } case /op up/ { return &opAll($self, $message); } case /thanks|thank you/ { return &talk(\@np); } case /:</ { return ";)"; } case /tell.*off/ { return &talk(\@defy); } case /op me/ { return &giveOps($self, $message); } case /me op/ { return &giveOps($self, $message); } case /\?/ { return "i don't make a habit of answering questions as a general rule"; } case /rude/ { return "i'm not sorry"; } case [@greeted] { return &talk(\@greet); } # case /$BOSS/ { # &msg_boss($self, $message, "$message->{who} just mentioned you in $message->{channel}, ".&talk(\@bro)); # return "one sec, ".&talk(\@bro).", i'm checking if $BOSS is around"; } else { return &talk(\@catchall); } } } sub eavesdropper { my ($self, $message) = @_; if (rand(100) < 20) { switch ($message->{body}) { ###misc context-sensitive responses case /panic/ { return &qPanic($self, $message); } case /bbc|nyt/ { return &talk(\@news); } case /facebook/ { return "quit using facebook"; } case /.* bots/ { return "i am only one"; } case /kvincent/ { my @a = ("i heard that, $message->{who}", "man, i love it when y'all talk about me", "hey, i'm right here", "blah blah blah"); return &talk(\@a); } case /<3/ { my @a = ("spread the love!", "gaaaaay", "http://images3.wikia.nocookie.net/__cb20120724043925/degrassi/images/8/8d/Gay-seal_large.jpg", "i want some <3, too"); return "$message->{who}: ".&talk(\@a); } case /exercise/ { my @a = ("spinach and walkies, you fatty", "get swoll!", "get pumped!", "http://willgadd.com/it-doesnt-matter-what-but-do-it/", "shut up and go run or something"); return "$message->{who}: ".&talk(\@a); } case /food|hungry/ { my @a = ("man, now i'm hungry", "if you have food, $message->{who}, you better share it with the class", "you're gonna get fat", "come on, ".&talk(\@bro).", don't taunt me with your food talk"); return &talk(\@a); } case /.* work / { my @a = ("quit slacking off", "be more productive", "shut up and do it"); return &talk(\@a); } case /imgur/ { my @a = ("omg i'm trying to break my imgur addiction stop it", "pics pics pics", "sweet shit, ".&talk(\@bro)); return &talk(\@a); } else { if (rand(100) < 40) { return &talk(\@unsolicited); } else { return; } } } } } sub logUrl { my ($self, $message) = @_; my @splitter = split(" ", $message->{body}); foreach (@splitter) { if ($_ =~ /http/) { if ($_ ~~ @links) { switch ($linkspam) { case 0 { $self->say(who => $message->{who}, channel => $message->{channel}, body => "quit spamming links, ".&talk(\@bro)); $linkspam++; } case 1 { $self->say(who => $message->{who}, channel => $message->{channel}, body => "i'm not listening anymore, ".&talk(\@bro)); $linkspam++; } else { return; } } } else { $linkspam = 0; push(@links, $_); &msg_boss($self, $message, "LINKIES! $message->{who} in $message->{channel}: $message->{body}"); } } } } sub gtfo { my ($self, $message) = @_; $self->reply($message, &talk(\@affirm).", ".&talk(\@bro).", i'm turning off now"); $self->shutdown('fuck it'); } sub boss_pub { my ($self, $message) = @_; switch ($message->{body}) { case /back.*cave/ { &gtfo($self, $message); } case /get.*out/ { &gtfo($self, $message); } case /<3/ { return &talk(\@affection); } case /tell.*off/ { my @input = split (' ', $message->{body}); return &talk(\@affirm).". $input[1], ".&talk(\@telloff); } case /you can talk/ { ($talking,$eavesdropping) = 1; return "sweet! ".&talk(\@affection); } case /you can eavesdrop/{ $eavesdropping = 1; return "sweet! ".&talk(\@affection). " gonna listen in again"; } else { return &talkback($self, $message) }; } } sub boss_priv { my ($self, $message) = @_; switch ($message->{body}) { case /join/ { my @channel = split (' *#', $message->{body}); $self->join('#'.$channel[1]); return &talk(\@affirm).", ".&talk(\@bro).", trying to join #$channel[1]"; } case /oplist/ { my @op = split (' ', $message->{body}); push(@OPLIST,$op[1]); return &talk(\@affirm).", ".&talk(\@bro).", oplist is now: @OPLIST"; } case /unop/ { my @op = split (' ', $message->{body}); if ($op[1] ~~ @OPLIST) { my $i = 0; $i++ until $OPLIST[$i] eq $op[1]; splice(@OPLIST, $i, 1); return &talk(\@affirm).", ".&talk(\@bro).", after booting out $op[1], oplist is now: @OPLIST"; } else { return "you sure, ".&talk(\@bro)."? $op[1] isn't even on the oplist."; } } case /who.* ops/ { return "i've got (@OPLIST) on the oplist right now, ".&talk(\@bro); } case /^say/ { my @r = split(' ', $message->{body}); shift(@r); my $chan = shift(@r); my $reply = join (' ', @r); $self->say(channel => "#$chan", body => $reply); return "telling #$chan \"$reply\""; } else { return &boss_pub($self, $message); } } } sub giveOps { my ($self, $message) = @_; if ($message->{who} ~~ @OPLIST) { $self->mode("$message->{channel} +o $message->{who}"); return "have some ops, $message->{who}"; } else { &msg_boss($self, $message, "$message->{who} just tried to ask for ops in $message->{channel}, ".&talk(\@bro).", just so you know"); return "i'd op you, ".&talk(\@bro).", but you gotta be on the list. ".&talk(\@ask)." $BOSS or something."; } } sub opAll { my ($self, $message) = @_; foreach (@OPLIST) { $self->mode("$message->{channel} +o $_"); } &msg_boss($self, $message, "$message->{who} just oped up $message->{channel}, ".&talk(\@bro)); return "roger that, $message->{who}; ops for everyone!"; } sub toggleEaves { if ($eavesdropping == 1) { $eavesdropping = 0; return &talk(\@affirm).", ".&talk(\@affirm).", i'll quit listening in on y'all"; } elsif ($eavesdropping != 2 ) { $eavesdropping = 2; return "already not listening, leave me alone, ".&talk(\@bro); } } sub toggleTalk { if ($talking == 1) { $talking = 0; $eavesdropping = 0; return &talk(\@affirm).", i'll be quiet"; } elsif ($talking != 2) { $talking = 2; return &talk(\@bro).", i'm already quiet, what do you want from me?"; } } sub banish { my ($self, $message) = @_; $self->reply($message, "fine! what a dick."); $self->part($message->{channel}, 'fuck it'); &msg_boss($self, $message, "$message->{who} just banished me from $message->{channel} :("); } sub talkLimiter { my ($self, $message) = @_; if ($talkspam < 3) { if ($last =~ $message->{who}) { #increment spam count $talkspam++; } else { $talkspam = 0; #reset spam count } $last = $message->{who}; return &talkback($self, $message); } else { if (($talkspam < 100) && ($last =~ $message->{who})) { #warn for spam $talkspam = 100; $last = $message->{who}; return "you talk too much; i'm not listening to you for a while"; } else { if ($last !~ $message ->{who} ) { $talkspam = 0; return &talkback($self, $message); } $last = $message->{who}; return; } } } sub msg_boss { my ($self, $message, $pm) = @_; $self->say(who => $BOSS, channel => "msg", body => $pm); } sub talk { my @words = @{$_[0]}; return $words[rand($#words+1)]; } sub stripTrigger { my ($self, $message) = @_; my @a = split(' ', $message->{body}); shift(@a); return join(' ', @a); } #sub log { #my ($self, $message) = @_; #my $channel = $message->{channel}; #my $who = $message->{who}; #my $body = $message->{body}; #my $outfile = "$LOG/$channel.txt"; #open OUT, ">>", $outfile; #select OUT; #print "< $who > $body"; #close OUT; #} #======== TWENTY QUESTIONS sub twentyQ { my ($self, $message) = @_; switch ($message->{body}) { case /^\?ask/ { return &qAsk($self, $message); } case /^\?answer/{ return &qAnswer($self, $message); } case /^\?skip/ { return &qSkip($self, $message); } case /^\?status/{ return &qStatus($self, $message); } case /^\?mercy/ { return &qMercy($self, $message); } case /^\?set/ { return &qSet($self, $message); } case /^\?win/ { return &qWin($self, $message); } case /^\?lose/ { return &qLose($self, $message); } case /^\?panic/ { return &qPanic($self, $message); } case /^\?help/ { return "Welcome to the kvincent 20 Questions Mediation Mode. Valid commands are: ?ask, ?answer, ?skip, ?status, ?mercy, ?set, ?win, ?lose, ?panic"; } else { return "you trying to play 20 questions, ".&talk(\@bro)."?"; } } } sub qAsk { my ($self, $message) = @_; if ($#qs == $#as) { my $newQ = &stripTrigger($self, $message); if (length($newQ) > $qlength) { $qlength = length($newQ); } push(@qs, $newQ); return; } else { return "whoa whoa one at a time, ".&bros; } } sub qAnswer { my ($self, $message) = @_; if ($#qs == $#as) { return "yo, ".&talk(\@bro).", you can't answer what hasn't been asked"; } else { push(@as, &stripTrigger($self, $message)); $asked++; my $left = $qcap-$asked; if ($left == 0 ) { # LOSE STATE return &qLose($self, $message); } else { return "y'all have $left questions left"; } } } sub qSkip { my ($self, $message) = @_; if ($#qs == $#as) { return "you can only skip unanswered quesions, ".&talk(\@bro); } else { pop(@qs); return "axing that question"; } } sub qStatus { my ($self, $message) = @_; if ($answer) { my $i = 0; my $statusline; foreach (@qs) { $statusline = "[$_]"; my $l = $qlength - length($_); while ($l > 0) { $l--; $statusline .= " "; } $statusline .= "--[$as[$i]]"; $i++; $self->say(channel => $message->{channel}, body => $statusline); } my $left = $qcap - $asked; return "current asshole is $knower. y'all have $left questions left."; } else { return "no one's thinking of anything interesting. wanna start a game, ".&talk(\@bro)."?"; } } sub qMercy { my ($self, $message) = @_; $qcap++; my $left = $qcap - $asked; return "giving y'all more questions since you suck. now you have $left questions left"; } sub qSet { my ($self, $message) = @_; if ($message->{channel} =~ /msg/ ) { if (!$answer) { $answer = &stripTrigger($self, $message); $knower = $message->{who}; $self->say(channel => "#trhq", body => "hey ".&bros.", $message->{who} is thinking of something"); return &talk(\@affirm).", ".&talk(\@bro).", starting a new game of 20 questions for $answer"; } else { return "whoa, ".&talk(\@bro).", one game at a time here"; } } else { return "shit, ".&talk(\@bro).", not where everyone can hear you, okay?"; } } sub qLose { my ($self, $message) = @_; my $report = $answer; ($answer, $knower, @qs, @as) = undef; return "you guys suck. the answer was $report"; } sub qWin { my ($self, $message) = @_; ($answer, $knower, @qs, @as) = undef; return "yaaaaay finally"; } sub qPanic { my $panic; my $size = rand(40)+10; my $i = 0; while ($i < $size) { $i++; $panic .= &talk(\@alpha); } return $panic; } #===== BOT INITIALIZATION Bot->new( server => "irc.freenode.net", channels => [ '#kvincent,#giantfuckingqueens,#trhq,#cmubuggy' ], nick => 'kvincent', name => $BOSS."'s bot", quit_message => "fuck it", )->run();
modgethanc/kvincent
dep/_kvincent.pl
Perl
mit
18,200
% random_generate.pl %--------------------------------------------------------------- :- module(random_generate, [random_generate_words/2, random_generate_atom_list/3, random_generate_and_print_atom_list/3] ). %--------------------------------------------------------------- :- use_module('$REGULUS/PrologLib/utilities'). :- use_module(library(lists)). :- use_module(library(random)). :- use_module(library(timeout)). %---------------------------------------------------------------------- % Max amount of time to spend trying to generate a sentence, in seconds. generation_time_limit(1). %---------------------------------------------------------------------- random_generate_words(Words, MaxDepth) :- generation_time_limit(TimeLimit), TimeLimitInMilliseconds is integer( 1000 * TimeLimit ), time_out(random_generate_words1(Words, MaxDepth), TimeLimitInMilliseconds, Result), ( Result = time_out -> fail ; true ). random_generate_words1(Words, MaxDepth) :- random_pick_top_category(Cat), arg(6, Cat, []), random_generate_from_category(Cat, MaxDepth), arg(5, Cat, Words), !. random_generate_atom_list(N, List, _MaxDepth) :- N < 1, List = [], !. random_generate_atom_list(N, List, MaxDepth) :- N >= 1, ( random_generate_words(Words, MaxDepth) -> join_with_spaces(Words, F), format('.', []), N1 is N - 1, List = [F | R] ; format('-', []), N1 is N, List = R ), flush_output(user), !, random_generate_atom_list(N1, R, MaxDepth). random_generate_and_print_atom_list(N, Stream, MaxDepth) :- random_generate_atom_list(N, List, MaxDepth), print_generated_sentences_to_stream(List, Stream). %---------------------------------------------------------------------- random_pick_top_category(RandomCat) :- findall(Cat, top_level_category(Cat), Cats), random_element_of_list(RandomCat, Cats). top_level_category(Cat) :- regulus_preds:top_level_category(TopLevelGrammar), functor(Cat, TopLevelGrammar, 6). %---------------------------------------------------------------------- random_generate_from_category(Cat, MaxDepth) :- MaxDepth > 0, random_expand_cat(Cat, Body), MaxDepth1 is MaxDepth - 1, random_generate_from_body(Body, MaxDepth1). %---------------------------------------------------------------------- random_expand_cat(Cat, RandomBody) :- findall([Cat, Body], expand_head(Cat, Body), Pairs), random_element_of_list([RandomHead, RandomBody], Pairs), Cat = RandomHead. expand_head(Head, Body) :- current_predicate(dcg_clause, user:dcg_clause(_, _)), user:dcg_clause(Head, Body). %---------------------------------------------------------------------- random_generate_from_body((F, R), MaxDepth) :- !, random_generate_from_body(F, MaxDepth), random_generate_from_body(R, MaxDepth). random_generate_from_body(Disjunction, MaxDepth) :- is_disjunction(Disjunction), !, disjunction_to_list(Disjunction, List), random_element_of_list(Element, List), random_generate_from_body(Element, MaxDepth). random_generate_from_body(Cat, MaxDepth) :- functor(Cat, _CatSymbol, 6), !, random_generate_from_category(Cat, MaxDepth). random_generate_from_body('C'(F, Word, R), _MaxDepth) :- !, F = [Word | R]. random_generate_from_body(true, _MaxDepth) :- !. random_generate_from_body((X = Y), _MaxDepth) :- !, X = Y. random_generate_from_body(merge_globals(_, _), _MaxDepth) :- !. %---------------------------------------------------------------------- print_generated_sentences_to_stream([], _Stream). print_generated_sentences_to_stream([F | R], S) :- format(S, '~N~w~n', [F]), !, print_generated_sentences_to_stream(R, S). %---------------------------------------------------------------------- random_element_of_list(X, List) :- length(List, N), N > 0, N1 is N + 1, random(1, N1, Index), safe_nth(Index, List, RandomElt), delete(List, RandomElt, RList), !, ( X = RandomElt ; random_element_of_list(X, RList) ). %---------------------------------------------------------------------- is_disjunction(Disjunction) :- compound(Disjunction), functor(Disjunction, ';', 2). disjunction_to_list(Disjunction, List) :- is_disjunction(Disjunction), Disjunction = (F ; R), List = [F | R1], !, disjunction_to_list(R, R1). disjunction_to_list(Disjunction, List) :- List = [Disjunction].
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_nlu/ext/regulus/Prolog/random_generate.pl
Perl
mit
4,356
use utf8; package eduity::Schema::Userskill; # Created by DBIx::Class::Schema::Loader # DO NOT MODIFY THE FIRST PART OF THIS FILE =head1 NAME eduity::Schema::Userskill =cut use strict; use warnings; use Moose; use MooseX::NonMoose; use MooseX::MarkAsMethods autoclean => 1; extends 'DBIx::Class::Core'; =head1 COMPONENTS LOADED =over 4 =item * L<DBIx::Class::InflateColumn::DateTime> =item * L<DBIx::Class::InflateColumn::FS> =back =cut __PACKAGE__->load_components("InflateColumn::DateTime", "InflateColumn::FS"); =head1 TABLE: C<userskills> =cut __PACKAGE__->table("userskills"); =head1 ACCESSORS =head2 id data_type: 'integer' is_auto_increment: 1 is_nullable: 0 sequence: 'userskills_id_seq' =head2 userid data_type: 'integer' is_nullable: 0 =head2 skill data_type: 'varchar' is_nullable: 0 size: 20 =head2 rating data_type: 'smallint' default_value: 0 is_nullable: 0 =cut __PACKAGE__->add_columns( "id", { data_type => "integer", is_auto_increment => 1, is_nullable => 0, sequence => "userskills_id_seq", }, "userid", { data_type => "integer", is_nullable => 0 }, "skill", { data_type => "varchar", is_nullable => 0, size => 20 }, "rating", { data_type => "smallint", default_value => 0, is_nullable => 0 }, ); =head1 PRIMARY KEY =over 4 =item * L</id> =back =cut __PACKAGE__->set_primary_key("id"); # Created by DBIx::Class::Schema::Loader v0.07024 @ 2012-09-15 18:55:24 # DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:+azTh1G5gh4SYZq5fNankw # You can replace this text with custom code or comments, and it will be preserved on regeneration __PACKAGE__->meta->make_immutable; 1;
vendion/Eduity
lib/eduity/Schema/Userskill.pm
Perl
mit
1,702
package Paws::SQS::SetQueueAttributes; use Moose; has Attributes => (is => 'ro', isa => 'Paws::SQS::QueueAttributeMap', traits => ['NameInRequest'], request_name => 'Attribute' , required => 1); has QueueUrl => (is => 'ro', isa => 'Str', required => 1); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'SetQueueAttributes'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::API::Response'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::SQS::SetQueueAttributes - Arguments for method SetQueueAttributes on Paws::SQS =head1 DESCRIPTION This class represents the parameters used for calling the method SetQueueAttributes on the Amazon Simple Queue Service service. Use the attributes of this class as arguments to method SetQueueAttributes. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to SetQueueAttributes. As an example: $service_obj->SetQueueAttributes(Att1 => $value1, Att2 => $value2, ...); Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object. =head1 ATTRIBUTES =head2 B<REQUIRED> Attributes => L<Paws::SQS::QueueAttributeMap> A map of attributes to set. The following lists the names, descriptions, and values of the special request parameters that the C<SetQueueAttributes> action uses: =over =item * C<DelaySeconds> - The length of time, in seconds, for which the delivery of all messages in the queue is delayed. Valid values: An integer from 0 to 900 (15 minutes). The default is 0 (zero). =item * C<MaximumMessageSize> - The limit of how many bytes a message can contain before Amazon SQS rejects it. Valid values: An integer from 1,024 bytes (1 KiB) up to 262,144 bytes (256 KiB). The default is 262,144 (256 KiB). =item * C<MessageRetentionPeriod> - The length of time, in seconds, for which Amazon SQS retains a message. Valid values: An integer representing seconds, from 60 (1 minute) to 1,209,600 (14 days). The default is 345,600 (4 days). =item * C<Policy> - The queue's policy. A valid AWS policy. For more information about policy structure, see Overview of AWS IAM Policies in the I<Amazon IAM User Guide>. =item * C<ReceiveMessageWaitTimeSeconds> - The length of time, in seconds, for which a C< ReceiveMessage > action waits for a message to arrive. Valid values: an integer from 0 to 20 (seconds). The default is 0. =item * C<RedrivePolicy> - The string that includes the parameters for the dead-letter queue functionality of the source queue. For more information about the redrive policy and dead-letter queues, see Using Amazon SQS Dead-Letter Queues in the I<Amazon SQS Developer Guide>. =over =item * C<deadLetterTargetArn> - The Amazon Resource Name (ARN) of the dead-letter queue to which Amazon SQS moves messages after the value of C<maxReceiveCount> is exceeded. =item * C<maxReceiveCount> - The number of times a message is delivered to the source queue before being moved to the dead-letter queue. =back The dead-letter queue of a FIFO queue must also be a FIFO queue. Similarly, the dead-letter queue of a standard queue must also be a standard queue. =item * C<VisibilityTimeout> - The visibility timeout for the queue. Valid values: an integer from 0 to 43,200 (12 hours). The default is 30. For more information about the visibility timeout, see Visibility Timeout in the I<Amazon SQS Developer Guide>. =back The following attributes apply only to server-side-encryption: =over =item * C<KmsMasterKeyId> - The ID of an AWS-managed customer master key (CMK) for Amazon SQS or a custom CMK. For more information, see Key Terms. While the alias of the AWS-managed CMK for Amazon SQS is always C<alias/aws/sqs>, the alias of a custom CMK can, for example, be C<alias/I<MyAlias> >. For more examples, see KeyId in the I<AWS Key Management Service API Reference>. =item * C<KmsDataKeyReusePeriodSeconds> - The length of time, in seconds, for which Amazon SQS can reuse a data key to encrypt or decrypt messages before calling AWS KMS again. An integer representing seconds, between 60 seconds (1 minute) and 86,400 seconds (24 hours). The default is 300 (5 minutes). A shorter time period provides better security but results in more calls to KMS which might incur charges after Free Tier. For more information, see How Does the Data Key Reuse Period Work?. =back The following attribute applies only to FIFO (first-in-first-out) queues: =over =item * C<ContentBasedDeduplication> - Enables content-based deduplication. For more information, see Exactly-Once Processing in the I<Amazon SQS Developer Guide>. =over =item * Every message must have a unique C<MessageDeduplicationId>, =over =item * You may provide a C<MessageDeduplicationId> explicitly. =item * If you aren't able to provide a C<MessageDeduplicationId> and you enable C<ContentBasedDeduplication> for your queue, Amazon SQS uses a SHA-256 hash to generate the C<MessageDeduplicationId> using the body of the message (but not the attributes of the message). =item * If you don't provide a C<MessageDeduplicationId> and the queue doesn't have C<ContentBasedDeduplication> set, the action fails with an error. =item * If the queue has C<ContentBasedDeduplication> set, your C<MessageDeduplicationId> overrides the generated one. =back =item * When C<ContentBasedDeduplication> is in effect, messages with identical content sent within the deduplication interval are treated as duplicates and only one copy of the message is delivered. =item * If you send one message with C<ContentBasedDeduplication> enabled and then another message with a C<MessageDeduplicationId> that is the same as the one generated for the first C<MessageDeduplicationId>, the two messages are treated as duplicates and only one copy of the message is delivered. =back =back Any other valid special request parameters (such as the following) are ignored: =over =item * C<ApproximateNumberOfMessages> =item * C<ApproximateNumberOfMessagesDelayed> =item * C<ApproximateNumberOfMessagesNotVisible> =item * C<CreatedTimestamp> =item * C<LastModifiedTimestamp> =item * C<QueueArn> =back =head2 B<REQUIRED> QueueUrl => Str The URL of the Amazon SQS queue whose attributes are set. Queue URLs are case-sensitive. =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method SetQueueAttributes in L<Paws::SQS> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/SQS/SetQueueAttributes.pm
Perl
apache-2.0
6,865
# Copyright 2020, Google LLC # # 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 Google::Ads::GoogleAds::V8::Services::CampaignFeedService::GetCampaignFeedRequest; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = {resourceName => $args->{resourceName}}; # Delete the unassigned fields in this object for a more concise JSON payload remove_unassigned_fields($self, $args); bless $self, $class; return $self; } 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V8/Services/CampaignFeedService/GetCampaignFeedRequest.pm
Perl
apache-2.0
1,057
#!/software/bin/perl -w # Copyright [1999-2014] EMBL-European Bioinformatics Institute # and Wellcome Trust Sanger 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. # All EG specific Display Xrefs, like JGI or Broad or GeneDB ones use strict; use Getopt::Long; use Bio::EnsEMBL::Registry; my $regfile = $ENV{'REGISTRY'}; my $user = $ENV{'USER'}; my $species = ''; my $all = ''; my $help; my $out; $| = 1; GetOptions( 'regfile:s' => \$regfile, 'species:s' => \$species, 'all!' => \$all, 'help!' => \$help, 'h!' => \$help, 'out=s' => \$out, ); die("Cannot do anything without a kill list file and a registry file and a compara database 'regfile:s' => $regfile, 'species:s' => $species, (single species to run on ) 'all!' => $all, ( run on all species ) ") if ($species eq '' and $all eq '' or $help); Bio::EnsEMBL::Registry->load_all($regfile); open ( SQL,">$out") or die("Cannot open file $out for writing\n"); my @dbas; if ($all){ @dbas = @{Bio::EnsEMBL::Registry->get_all_DBAdaptors()}; } if ($species ne ''){ my @db = @{Bio::EnsEMBL::Registry->get_all_DBAdaptors(-species => "$species")}; die ("Cannot find adaptor for species $species in registry\n") unless scalar(@db) == 1; push @dbas, @db; } @dbas = sort { $a->species cmp $b->species } @dbas; foreach my $dba (@dbas){ # print STDERR "db name: " . $dba->dbc->dbname . "\n"; next unless $dba->dbc->dbname !~ /collection/; next unless $dba->group eq 'core'; if ( $dba->species =~ /(\w+)\s(\w+)/ ){ my $shortname = uc(substr($1,0,4)); $shortname .= "_". uc(substr($2,0,1)); my $name = $dba->species; print "NAME $name\n"; my $meta = $dba->get_MetaContainer; my $tax_id = $meta->get_taxonomy_id; # we want to fetch all the protein coding genes and their associated xrefs my $ga = $dba->get_GeneAdaptor; print STDERR "got " . @{$ga->fetch_all_by_logic_name('protein_coding')} . " protein coding genes\n"; my @protein_coding_genes = @{$ga->fetch_all_by_biotype('protein_coding')}; push (@protein_coding_genes, @{$ga->fetch_all_by_biotype('pseudogene')}); push (@protein_coding_genes, @{$ga->fetch_all_by_biotype('non_translating_cds')}); foreach my $pc_gene ( @protein_coding_genes ) { foreach my $pcRNA ( @{$pc_gene->get_all_Transcripts} ) { # Get the display_xref and keep it if it is ENA_GENE or PGD_GENE my $display_db_entry_xref = $pc_gene->display_xref; if ($display_db_entry_xref->dbname =~ /ena_gene|pgd_gene/i) { print SQL "INSERT INTO EG_Xref values (\\N,\"" . $name . '",' . $tax_id. ',"' . $pc_gene->stable_id . '",' . $pc_gene->dbID . ',"' . $pcRNA->stable_id .'",' . $pcRNA->dbID .',"' . $pcRNA->biotype . '","' . $display_db_entry_xref->database .'","' . $display_db_entry_xref->display_id .'","' . $display_db_entry_xref->primary_id .'","' . $display_db_entry_xref->description . '");'."\n" ; } # Xrefs are at the Gene levels in our case ! foreach my $xref ( @{$pc_gene->get_all_DBEntries} ) { next unless $xref->database =~ /broad/i or $xref->database =~ /jgi/i or $xref->database =~ /genedb/i or $xref->database =~ /cadre/i or $xref->database =~ /aspgd/i or $xref->database =~ /ena_gene/i or $xref->database =~ /pgd_gene/i or $xref->database =~ /schistodb/i or $xref->database =~ /mycgr3_jgi_v2.0_gene/i ; my $description = $xref->description; $description =~ s/'/`/g unless !defined $description; if (! defined $description) { $description = $pc_gene->description; if (defined $description) { $description =~ s/ \[Source.+//; } else { print STDERR "gene, " . $pc_gene->stable_id . ", without a description!\n"; } } if ($description =~ /'/) { print SQL "INSERT INTO EG_Xref values (\\N,\"" . $name . '",' . $tax_id. ',"' . $pc_gene->stable_id . '",' . $pc_gene->dbID . ',"' . $pcRNA->stable_id .'",' . $pcRNA->dbID .',"' . $pcRNA->biotype . '","' . $xref->database .'","' . $xref->display_id .'","' . $xref->primary_id .'","' . $description . '");'."\n" ; } else { print SQL "INSERT INTO EG_Xref values (\\N,'" . $name . "'," . $tax_id. ",'" . $pc_gene->stable_id . "'," . $pc_gene->dbID . ",'" . $pcRNA->stable_id ."'," . $pcRNA->dbID .",'" . $pcRNA->biotype . "','" . $xref->database ."','" . $xref->display_id ."','" . $xref->primary_id ."','" . $description . "');\n" ; } } } # End foreach transcript } # End foreach gene } $dba->dbc->disconnect_if_idle; } 1;
navygit/ncRNA_Pipeline
scripts/xrefs_pipeline/make_EGs_xref_db.pl
Perl
apache-2.0
5,234
# # Copyright 2022 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::microsoft::sccm::local::plugin; use strict; use warnings; use base qw(centreon::plugins::script_simple); sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '0.1'; $self->{modes} = { 'database-replication-status' => 'apps::microsoft::sccm::local::mode::databasereplicationstatus', 'site-status' => 'apps::microsoft::sccm::local::mode::sitestatus' }; return $self; } 1; __END__ =head1 PLUGIN DESCRIPTION Check SCCM through powershell. =cut
centreon/centreon-plugins
apps/microsoft/sccm/local/plugin.pm
Perl
apache-2.0
1,373
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2019] 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 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut =head1 NAME Bio::EnsEMBL::Gene - Object representing a genes =head1 SYNOPSIS my $gene = Bio::EnsEMBL::Gene->new( -START => 123, -END => 1045, -STRAND => 1, -SLICE => $slice ); # print gene information print("gene start:end:strand is " . join( ":", map { $gene->$_ } qw(start end strand) ) . "\n" ); # set some additional attributes $gene->stable_id('ENSG000001'); $gene->description('This is the gene description'); =head1 DESCRIPTION A representation of a Gene within the Ensembl system. A gene is a set of one or more alternative transcripts. =head1 METHODS =cut package Bio::EnsEMBL::Gene; use strict; use POSIX; use Bio::EnsEMBL::Feature; use Bio::EnsEMBL::Intron; use Bio::EnsEMBL::Biotype; use Bio::EnsEMBL::Utils::Argument qw(rearrange); use Bio::EnsEMBL::Utils::Exception qw(throw warning); use Bio::EnsEMBL::Utils::Scalar qw(assert_ref); use parent qw(Bio::EnsEMBL::Feature); use constant SEQUENCE_ONTOLOGY => { acc => 'SO:0000704', term => 'gene', }; =head2 new Arg [-START] : int - start postion of the gene Arg [-END] : int - end position of the gene Arg [-STRAND] : int - 1,-1 tehe strand the gene is on Arg [-SLICE] : Bio::EnsEMBL::Slice - the slice the gene is on Arg [-STABLE_ID] : string - the stable identifier of this gene Arg [-VERSION] : int - the version of the stable identifier of this gene Arg [-EXTERNAL_NAME] : string - the external database name associated with this gene Arg [-EXTERNAL_DB] : string - the name of the database the external name is from Arg [-EXTERNAL_STATUS]: string - the status of the external identifier Arg [-DISPLAY_XREF]: Bio::EnsEMBL::DBEntry - The external database entry that is used to label this gene when it is displayed. Arg [-TRANSCRIPTS]: Listref of Bio::EnsEMBL::Transcripts - this gene's transcripts Arg [-CREATED_DATE]: string - the date the gene was created Arg [-MODIFIED_DATE]: string - the date the gene was last modified Arg [-DESCRIPTION]: string - the genes description Arg [-BIOTYPE]: string - the biotype e.g. "protein_coding" Arg [-SOURCE]: string - the genes source, e.g. "ensembl" Arg [-IS_CURRENT]: Boolean - specifies if this is the current version of the gene Arg [-CANONICAL_TRANSCRIPT]: Bio::EnsEMBL::Transcript - the canonical transcript of this gene Arg [-CANONICAL_TRANSCRIPT_ID]: integer - the canonical transcript dbID of this gene, if the transcript object itself is not available. Example : $gene = Bio::EnsEMBL::Gene->new(...); Description: Creates a new gene object Returntype : Bio::EnsEMBL::Gene Exceptions : none Caller : general Status : Stable =cut sub new { my $caller = shift; my $class = ref($caller) || $caller; my $self = $class->SUPER::new(@_); my ( $stable_id, $version, $external_name, $type, $external_db, $external_status, $display_xref, $description, $transcripts, $created_date, $modified_date, $confidence, $biotype, $source, $is_current, $canonical_transcript_id, $canonical_transcript ) = rearrange( [ 'STABLE_ID', 'VERSION', 'EXTERNAL_NAME', 'TYPE', 'EXTERNAL_DB', 'EXTERNAL_STATUS', 'DISPLAY_XREF', 'DESCRIPTION', 'TRANSCRIPTS', 'CREATED_DATE', 'MODIFIED_DATE', 'CONFIDENCE', 'BIOTYPE', 'SOURCE', 'IS_CURRENT', 'CANONICAL_TRANSCRIPT_ID', 'CANONICAL_TRANSCRIPT' ], @_ ); if ($transcripts) { $self->{'_transcript_array'} = $transcripts; $self->recalculate_coordinates(); } $self->stable_id($stable_id); $self->{'created_date'} = $created_date; $self->{'modified_date'} = $modified_date; $self->external_name($external_name) if ( defined $external_name ); $self->external_db($external_db) if ( defined $external_db ); $self->external_status($external_status) if ( defined $external_status ); $self->display_xref($display_xref) if ( defined $display_xref ); $self->{'biotype'} = $biotype || $type; $self->description($description); $self->source($source); # Default version if ( !defined($version) ) { $version = 1 } $self->{'version'} = $version; # default to is_current $is_current = 1 unless (defined($is_current)); $self->{'is_current'} = $is_current; # Add the canonical transcript if we were given one, otherwise add the # canonical transcript internal ID if we were given one. if ( defined($canonical_transcript) ) { $self->canonical_transcript($canonical_transcript); } elsif ( defined($canonical_transcript_id) ) { $self->{'canonical_transcript_id'} = $canonical_transcript_id; } return $self; } =head2 external_name Arg [1] : (optional) String - the external name to set Example : $gene->external_name('BRCA2'); Description: Getter/setter for attribute external_name. Returntype : String or undef Exceptions : none Caller : general Status : Stable =cut sub external_name { my $self = shift; $self->{'external_name'} = shift if (@_); if (defined $self->{'external_name'}) { return $self->{'external_name'}; } my $display_xref = $self->display_xref(); if (defined $display_xref) { return $display_xref->display_id(); } else { return undef; } } =head2 source Arg [1] : (optional) String - the source to set Example : $gene->source('ensembl'); Description: Getter/setter for attribute source Returntype : String Exceptions : none Caller : general Status : Stable =cut sub source { my $self = shift; $self->{'source'} = shift if( @_ ); return ( $self->{'source'} || "ensembl" ); } =head2 external_db Arg [1] : (optional) String - name of external db to set Example : $gene->external_db('HGNC'); Description: Getter/setter for attribute external_db. The db is the one that belongs to the external_name. Returntype : String Exceptions : none Caller : general Status : Stable =cut sub external_db { my $self = shift; $self->{'external_db'} = shift if( @_ ); if( exists $self->{'external_db'} ) { return $self->{'external_db'}; } my $display_xref = $self->display_xref(); if( defined $display_xref ) { return $display_xref->dbname() } else { return undef; } } =head2 external_status Arg [1] : (optional) String - status of the external db Example : $gene->external_status('KNOWNXREF'); Description: Getter/setter for attribute external_status. The status of the external db of the one that belongs to the external_name. Returntype : String Exceptions : none Caller : general Status : Stable =cut sub external_status { my $self = shift; $self->{'_ext_status'} = shift if ( @_ ); return $self->{'_ext_status'} if exists $self->{'_ext_status'}; my $display_xref = $self->display_xref(); if( defined $display_xref ) { return $display_xref->status() } else { return undef; } } =head2 description Arg [1] : (optional) String - the description to set Example : $gene->description('This is the gene\'s description'); Description: Getter/setter for gene description Returntype : String Exceptions : none Caller : general Status : Stable =cut sub description { my $self = shift; $self->{'description'} = shift if( @_ ); return $self->{'description'}; } =head2 equals Arg [1] : Bio::EnsEMBL::Gene gene Example : if ($geneA->equals($geneB)) { ... } Description : Compares two genes for equality. The test for eqality goes through the following list and terminates at the first true match: 1. If Bio::EnsEMBL::Feature::equals() returns false, then the genes are *not* equal. 2. If the biotypes differ, then the genes are *not* equal. 3. If both genes have stable IDs: if these are the same, the genes are equal, otherwise not. 4. If both genes have the same number of transcripts and if these are (when compared pair-wise sorted by start-position and length) the same, then they are equal, otherwise not. Return type : Boolean (0, 1) Exceptions : Thrown if a non-gene is passed as the argument. =cut sub equals { my ( $self, $gene ) = @_; if ( !defined($gene) ) { return 0 } if ( $self eq $gene ) { return 1 } assert_ref( $gene, 'Bio::EnsEMBL::Gene' ); my $feature_equals = $self->SUPER::equals($gene); if ( defined($feature_equals) && $feature_equals == 0 ) { return 0; } if ( $self->get_Biotype->name ne $self->get_Biotype->name ) { return 0; } if ( defined( $self->stable_id() ) && defined( $gene->stable_id() ) ) { if ( $self->stable_id() eq $gene->stable_id() ) { return 1 } else { return 0 } } my @self_transcripts = sort { $a->start() <=> $b->start() || $a->length() <=> $b->length() } @{ $self->get_all_Transcripts() }; my @gene_transcripts = sort { $a->start() <=> $b->start() || $a->length() <=> $b->length() } @{ $gene->get_all_Transcripts() }; if ( scalar(@self_transcripts) != scalar(@gene_transcripts) ) { return 0; } while (@self_transcripts) { my $self_transcript = shift(@self_transcripts); my $gene_transcript = shift(@gene_transcripts); if ( !$self_transcript->equals($gene_transcript) ) { return 0; } } return 1; } ## end sub equals =head2 canonical_transcript Arg [1] : (optional) Bio::EnsEMBL::Transcript - canonical_transcript object Example : $gene->canonical_transcript($canonical_transcript); Description: Getter/setter for the canonical_transcript Returntype : Bio::EnsEMBL::Transcript Exceptions : Throws if argument is not a transcript object. Caller : general Status : Stable =cut sub canonical_transcript { my ( $self, $transcript ) = @_; if ( defined($transcript) ) { # We're attaching a new canonical transcript. assert_ref( $transcript, 'Bio::EnsEMBL::Transcript' ); # If there's already a canonical transcript, make sure it doesn't # think it's still canonical. if ( defined( $self->{'canonical_transcript'} ) ) { $self->{'canonical_transcript'}->is_canonical(0); } $self->{'canonical_transcript'} = $transcript; $self->{'canonical_transcript_id'} = $transcript->dbID(); $transcript->is_canonical(1); } elsif ( !defined( $self->{'canonical_transcript'} ) && defined( $self->{'canonical_transcript_id'} ) && $self->{'canonical_transcript_id'} != 0 ) { # We have not attached a canoncical transcript, but we have the dbID # of one. if ( defined( $self->adaptor() ) ) { my $transcript_adaptor = $self->adaptor()->db()->get_TranscriptAdaptor(); my $canonical_transcript = $transcript_adaptor->fetch_by_dbID( $self->{'canonical_transcript_id'} ); if ( defined($canonical_transcript) ) { # Recusive call... $self->canonical_transcript($canonical_transcript); } } else { warning( "Gene has no adaptor " . "when trying to fetch canonical transcript." ); } } ## end elsif ( !defined( $self->...)) return $self->{'canonical_transcript'}; } ## end sub canonical_transcript =head2 get_all_Attributes Arg [1] : (optional) String $attrib_code The code of the attribute type to retrieve values for Example : my ($author) = @{ $gene->get_all_Attributes('author') }; my @gene_attributes = @{ $gene->get_all_Attributes }; Description: Gets a list of Attributes of this gene. Optionally just get Attributes for given code. Returntype : Listref of Bio::EnsEMBL::Attribute Exceptions : warning if gene does not have attached adaptor and attempts lazy load. Caller : general Status : Stable =cut sub get_all_Attributes { my $self = shift; my $attrib_code = shift; if ( ! exists $self->{'attributes' } ) { if (!$self->adaptor() ) { return []; } my $attribute_adaptor = $self->adaptor->db->get_AttributeAdaptor(); $self->{'attributes'} = $attribute_adaptor->fetch_all_by_Gene($self); } if ( defined $attrib_code ) { my @results = grep { uc($_->code()) eq uc($attrib_code) } @{$self->{'attributes'}}; return \@results; } else { return $self->{'attributes'}; } } =head2 add_Attributes Arg [1-N] : list of Bio::EnsEMBL::Attribute's @attribs Attribute(s) to add Example : my $attrib = Bio::EnsEMBL::Attribute->new(...); $gene->add_Attributes($attrib); Description: Adds an Attribute to the Gene. If you add an attribute before you retrieve any from database, lazy loading will be disabled. Returntype : none Exceptions : throw on incorrect arguments Caller : general Status : Stable =cut sub add_Attributes { my $self = shift; my @attribs = @_; if( ! exists $self->{'attributes'} ) { $self->{'attributes'} = []; } for my $attrib ( @attribs ) { if( ! $attrib->isa( "Bio::EnsEMBL::Attribute" )) { throw( "Argument to add_Attribute has to be an Bio::EnsEMBL::Attribute" ); } push( @{$self->{'attributes'}}, $attrib ); } return; } =head2 add_DBEntry Arg [1] : Bio::EnsEMBL::DBEntry $dbe The dbEntry to be added Example : my $dbe = Bio::EnsEMBL::DBEntery->new(...); $gene->add_DBEntry($dbe); Description: Associates a DBEntry with this gene. Note that adding DBEntries will prevent future lazy-loading of DBEntries for this gene (see get_all_DBEntries). Returntype : none Exceptions : thrown on incorrect argument type Caller : general Status : Stable =cut sub add_DBEntry { my $self = shift; my $dbe = shift; unless($dbe && ref($dbe) && $dbe->isa('Bio::EnsEMBL::DBEntry')) { throw('Expected DBEntry argument'); } $self->{'dbentries'} ||= []; push @{$self->{'dbentries'}}, $dbe; } =head2 get_all_DBEntries Arg [1] : (optional) String, external database name, SQL wildcard characters (_ and %) can be used to specify patterns. Arg [2] : (optional) String, external_db type, can be one of ('ARRAY','ALT_TRANS','ALT_GENE','MISC','LIT','PRIMARY_DB_SYNONYM','ENSEMBL'), SQL wildcard characters (_ and %) can be used to specify patterns. Example : my @dbentries = @{ $gene->get_all_DBEntries() }; @dbentries = @{ $gene->get_all_DBEntries('Uniprot%') }; @dbentries = @{ $gene->get_all_DBEntries('%', 'ENSEMBL') };} Description: Retrieves DBEntries (xrefs) for this gene. This does *not* include DBEntries that are associated with the transcripts and corresponding translations of this gene (see get_all_DBLinks()). This method will attempt to lazy-load DBEntries from a database if an adaptor is available and no DBEntries are present on the gene (i.e. they have not already been added or loaded). Return type: Listref of Bio::EnsEMBL::DBEntry objects Exceptions : none Caller : get_all_DBLinks, GeneAdaptor::store Status : Stable =cut sub get_all_DBEntries { my ( $self, $db_name_exp, $ex_db_type ) = @_; my $cache_name = 'dbentries'; if ( defined($db_name_exp) ) { $cache_name .= $db_name_exp; } if ( defined($ex_db_type) ) { $cache_name .= $ex_db_type; } # if not cached, retrieve all of the xrefs for this gene if ( !defined( $self->{$cache_name} ) && defined( $self->adaptor() ) ) { $self->{$cache_name} = $self->adaptor()->db()->get_DBEntryAdaptor() ->fetch_all_by_Gene( $self, $db_name_exp, $ex_db_type ); } $self->{$cache_name} ||= []; return $self->{$cache_name}; } ## end sub get_all_DBEntries =head2 get_all_object_xrefs Arg [1] : (optional) String, external database name Arg [2] : (optional) String, external_db type Example : @oxrefs = @{ $gene->get_all_object_xrefs() }; Description: Retrieves xrefs for this gene. This does *not* include xrefs that are associated with the transcripts or corresponding translations of this gene (see get_all_xrefs()). This method will attempt to lazy-load xrefs from a database if an adaptor is available and no xrefs are present on the gene (i.e. they have not already been added or loaded). NB: This method is an alias for the get_all_DBentries() method. Return type: Listref of Bio::EnsEMBL::DBEntry objects Status : Stable =cut sub get_all_object_xrefs { my $self = shift; return $self->get_all_DBEntries(@_); } =head2 get_all_DBLinks Arg [1] : String database name (optional) SQL wildcard characters (_ and %) can be used to specify patterns. Arg [2] : (optional) String, external database type, can be one of ('ARRAY','ALT_TRANS','ALT_GENE','MISC','LIT','PRIMARY_DB_SYNONYM','ENSEMBL'), SQL wildcard characters (_ and %) can be used to specify patterns. Example : @dblinks = @{ $gene->get_all_DBLinks() }; @dblinks = @{ $gene->get_all_DBLinks('Uniprot%') }; @dblinks = @{ $gene->get_all_DBLinks('%', 'ENSEMBL') };} Description: Retrieves *all* related DBEntries for this gene. This includes all DBEntries that are associated with the transcripts and corresponding translations of this gene. If you only want to retrieve the DBEntries associated with the gene (and not the transcript and translations) then you should use the get_all_DBEntries() call instead. Note: Each entry may be listed more than once. No uniqueness checks are done. Also if you put in an incorrect external database name no checks are done to see if this exists, you will just get an empty list. Return type: Listref of Bio::EnsEMBL::DBEntry objects Exceptions : none Caller : general Status : Stable =cut sub get_all_DBLinks { my ( $self, $db_name_exp, $ex_db_type ) = @_; my @links = @{ $self->get_all_DBEntries( $db_name_exp, $ex_db_type ) }; # Add all of the transcript and translation xrefs to the return list. foreach my $transcript ( @{ $self->get_all_Transcripts() } ) { push( @links, @{$transcript->get_all_DBLinks( $db_name_exp, $ex_db_type ) } ); } return \@links; } =head2 get_all_xrefs Arg [1] : String database name (optional) SQL wildcard characters (_ and %) can be used to specify patterns. Example : @xrefs = @{ $gene->get_all_xrefs() }; @xrefs = @{ $gene->get_all_xrefs('Uniprot%') }; Description: Retrieves *all* related xrefs for this gene. This includes all xrefs that are associated with the transcripts and corresponding translations of this gene. If you want to retrieve the xrefs associated with only the gene (and not the transcript or translations) then you should use the get_all_object_xrefs() method instead. Note: Each entry may be listed more than once. No uniqueness checks are done. Also if you put in an incorrect external database name no checks are done to see if this exists, you will just get an empty list. NB: This method is an alias for the get_all_DBLinks() method. Return type: Listref of Bio::EnsEMBL::DBEntry objects Status : Stable =cut sub get_all_xrefs { my $self = shift; return $self->get_all_DBLinks(@_); } =head2 get_all_Exons Example : my @exons = @{ $gene->get_all_Exons }; Description: Returns a set of all the exons associated with this gene. Returntype : Listref of Bio::EnsEMBL::Exon objects Exceptions : none Caller : general Status : Stable =cut sub get_all_Exons { my $self = shift; my %h; my @out = (); foreach my $trans ( @{$self->get_all_Transcripts} ) { foreach my $e ( @{$trans->get_all_Exons} ) { $h{$e->start()."-".$e->end()."-".$e->strand()."-".$e->phase()."-".$e->end_phase()} = $e; } } push @out, values %h; return \@out; } =head2 get_all_Introns Arg [1] : none Example : my @introns = @{$gene->get_all_Introns()}; Description: Returns an listref of the introns in this gene in order. i.e. the first intron in the listref is the 5prime most exon in the gene. Returntype : listref to Bio::EnsEMBL::Intron objects Exceptions : none Caller : general Status : Stable =cut sub get_all_Introns { my $self = shift; my %h; my @out = (); my @introns; foreach my $trans ( @{$self->get_all_Transcripts} ) { my @exons = @{ $trans->get_all_Exons() }; for (my $i = 0; $i < scalar(@exons) - 1; $i++) { my $intron = new Bio::EnsEMBL::Intron($exons[$i], $exons[$i+1]); push (@introns, $intron); } } return \@introns; } =head2 get_all_homologous_Genes Arg[1] : String The compara synonym to use when looking for a database in the registry. If not provided we will use the very first compara database we find. Description: Queries the Ensembl Compara database and retrieves all Genes from other species that are orthologous. REQUIRES properly setup Registry conf file. Meaning that one of the aliases for each core db has to be "Genus species" e.g. "Homo sapiens" (as in the name column in genome_db table in the compara database). The data is cached in this Object for faster re-retreival. Returntype : listref [ Bio::EnsEMBL::Gene, Bio::EnsEMBL::Compara::Homology, string $species # needed as cannot get spp from Gene ] Exceptions : none Caller : general Status : Stable =cut sub get_all_homologous_Genes { my ($self, $db_synonym) = @_; #Look for DBAdaptors which have a group of compara; these are compara DBAs. #If given a synonym my %args = (-GROUP => 'compara'); $args{-SPECIES} = $db_synonym if $db_synonym; my ($compara_dba) = @{Bio::EnsEMBL::Registry->get_all_DBAdaptors(%args)}; unless( $compara_dba ) { throw("No compara found in Bio::EnsEMBL::Registry. Please fully populate the Registry or construct a Bio::EnsEMBL::Compara::DBSQL::DBAdaptor"); } my $compara_species = $compara_dba->species(); if( exists( $self->{'homologues'}->{$compara_species} ) ){ return $self->{'homologues'}->{$compara_species}; } $self->{'homologues'}->{$compara_species} = []; # Get the compara 'member' corresponding to self my $member_adaptor = $compara_dba->get_adaptor('GeneMember'); my $query_member = $member_adaptor->fetch_by_stable_id($self->stable_id); unless( $query_member ){ return $self->{'homologues'}->{$compara_species} }; # Get the compara 'homologies' corresponding to 'member' my $homology_adaptor = $compara_dba->get_adaptor('Homology'); my @homolos = @{$homology_adaptor->fetch_all_by_Member($query_member)}; unless( scalar(@homolos) ){ return $self->{'homologues'}->{$compara_species} }; # Get the ensembl 'genes' corresponding to 'homologies' foreach my $homolo( @homolos ){ foreach my $member( @{$homolo->get_all_GeneMembers} ){ my $hstable_id = $member->stable_id; next if ($hstable_id eq $query_member->stable_id); # Ignore self my $hgene = undef; eval { $hgene = $member->get_Gene;} ; unless( $hgene ){ # Something up with DB. Create a new gene is best we can do $hgene = Bio::EnsEMBL::Gene->new ( -stable_id=>$hstable_id, -description=>$member->description, ); } my $hspecies = $member->genome_db->name; push @{$self->{'homologues'}->{$compara_species}}, [$hgene,$homolo,$hspecies]; } } return $self->{'homologues'}->{$compara_species}; } =head2 _clear_homologues Description: Removes any cached homologues from the Gene which could have been fetched from the C<get_all_homologous_Genes()> call. Returntype : none Exceptions : none Caller : general =cut sub _clear_homologues { my ($self) = @_; delete $self->{homologues}; } =head2 add_Transcript Arg [1] : Bio::EnsEMBL::Transcript $trans The transcript to add to the gene Example : my $transcript = Bio::EnsEMBL::Transcript->new(...); $gene->add_Transcript($transcript); Description: Adds another Transcript to the set of alternatively spliced Transcripts of this gene. If it shares exons with another Transcript, these should be object-identical. Returntype : none Exceptions : none Caller : general Status : Stable =cut sub add_Transcript { my ($self, $trans) = @_; if( !ref $trans || ! $trans->isa("Bio::EnsEMBL::Transcript") ) { throw("$trans is not a Bio::EnsEMBL::Transcript!"); } $self->{'_transcript_array'} ||= []; push(@{$self->{'_transcript_array'}},$trans); $self->recalculate_coordinates(); } sub remove_Transcript { my ($self,$trans) = @_; if( !ref $trans || ! $trans->isa("Bio::EnsEMBL::Transcript") ) { throw("$trans is not a Bio::EnsEMBL::Transcript!"); } # Clean transcript from live data $self->get_all_Transcripts; # force lazy load. my $array = $self->{_transcript_array}; my $db_id = $trans->dbID; @$array = grep { $_->dbID != $db_id } @$array; # Recalculate and store new gene coordinates $self->adaptor->update_coords($self); } =head2 get_all_Transcripts Example : my @transcripts = @{ $gene->get_all_Transcripts }; Description: Returns the Transcripts in this gene. Returntype : Listref of Bio::EnsEMBL::Transcript objects Warning : This method returns the internal transcript array used by this object. Avoid any modification of this array. We class use of shift and reassignment of the loop variable when iterating this array as modification. Dereferencing the structure as shown in the example is a safe way of using this data structure. Exceptions : none Caller : general Status : Stable =cut sub get_all_Transcripts { my $self = shift; if( ! exists $self->{'_transcript_array'} ) { if( defined $self->adaptor() ) { my $ta = $self->adaptor()->db()->get_TranscriptAdaptor(); my $transcripts = $ta->fetch_all_by_Gene( $self ); $self->{'_transcript_array'} = $transcripts; } } my @array_copy; if (defined $self->{'_transcript_array'}) { @array_copy = @{ $self->{'_transcript_array'} } ; return \@array_copy; } return; } =head2 get_all_alt_alleles Example : my @alt_genes = @{ $gene->get_all_alt_alleles }; foreach my $alt_gene (@alt_genes) { print "Alternate allele: " . $alt_gene->stable_id() . "\n"; } Description: Returns a listref of Gene objects that represent this Gene on an alternative haplotype. Empty list if there is no such Gene (eg there is no overlapping haplotype). Returntype : listref of Bio::EnsEMBL::Gene objects Exceptions : none Caller : general Status : Stable =cut sub get_all_alt_alleles { my $self = shift; my $result = $self->adaptor()->fetch_all_alt_alleles( $self ); return $result; } =head2 version Arg [1] : (optional) Int A version number for the stable_id Example : $gene->version(2); Description: Getter/setter for version number Returntype : Int Exceptions : none Caller : general Status : Stable =cut sub version { my $self = shift; $self->{'version'} = shift if(@_); return $self->{'version'}; } =head2 stable_id Arg [1] : (optional) String - the stable ID to set Example : $gene->stable_id("ENSG0000000001"); Description: Getter/setter for stable id for this gene. Returntype : String Exceptions : none Caller : general Status : Stable =cut sub stable_id { my $self = shift; $self->{'stable_id'} = shift if(@_); return $self->{'stable_id'}; } =head2 stable_id_version Arg [1] : (optional) String - the stable ID with version to set Example : $gene->stable_id("ENSG0000000001.3"); Description: Getter/setter for stable id with version for this gene. Returntype : String Exceptions : none Caller : general Status : Stable =cut sub stable_id_version { my $self = shift; if(my $stable_id = shift) { # See if there's an embedded period, assume that's a # version, might not work for some species but you # should use ->stable_id() and version() if you're worried # about ambiguity my $vindex = rindex($stable_id, '.'); # Set the stable_id and version pair depending on if # we found a version delimiter in the stable_id ($self->{stable_id}, $self->{version}) = ($vindex > 0 ? (substr($stable_id,0,$vindex), substr($stable_id,$vindex+1)) : $stable_id, undef); } return $self->{stable_id} . ($self->{version} ? ".$self->{version}" : ''); } =head2 is_current Arg [1] : Boolean $is_current Example : $gene->is_current(1) Description: Getter/setter for is_current state of this gene. Returntype : Int Exceptions : none Caller : general Status : Stable =cut sub is_current { my $self = shift; $self->{'is_current'} = shift if (@_); return $self->{'is_current'}; } =head2 created_date Arg [1] : (optional) String - created date to set (as a UNIX time int) Example : $gene->created_date('1141948800'); Description: Getter/setter for attribute created_date Returntype : String Exceptions : none Caller : general Status : Stable =cut sub created_date { my $self = shift; $self->{'created_date'} = shift if ( @_ ); return $self->{'created_date'}; } =head2 modified_date Arg [1] : (optional) String - modified date to set (as a UNIX time int) Example : $gene->modified_date('1141948800'); Description: Getter/setter for attribute modified_date Returntype : String Exceptions : none Caller : general Status : Stable =cut sub modified_date { my $self = shift; $self->{'modified_date'} = shift if ( @_ ); return $self->{'modified_date'}; } =head2 transform Arg [1] : String - coordinate system name to transform to Arg [2] : String - coordinate system version Example : my $new_gene = $gene->transform('supercontig'); Description: Moves this gene to the given coordinate system. If this gene has Transcripts attached, they move as well. Returntype : Bio::EnsEMBL::Gene Exceptions : throw on wrong parameters Caller : general Status : Stable =cut sub transform { my $self = shift; my $new_gene = $self->SUPER::transform(@_); if ( !defined($new_gene) ) { # check if this gene projects at all to requested coord system, # if not we are done. my @segments = @{ $self->project(@_) }; if ( !@segments ) { return undef; } } # # If you are transforming the gene then make sure the transcripts and exons are loaded # foreach my $tran (@{$self->get_all_Transcripts}){ $tran->get_all_Exons(); } if( exists $self->{'_transcript_array'} ) { my @new_transcripts; my ( $strand, $slice ); my $low_start = POSIX::INT_MAX; my $hi_end = POSIX::INT_MIN; for my $old_transcript ( @{$self->{'_transcript_array'}} ) { my $new_transcript = $old_transcript->transform( @_ ); # this can fail if gene transform failed return undef unless $new_transcript; if( ! defined $new_gene ) { if( $new_transcript->start() < $low_start ) { $low_start = $new_transcript->start(); } if( $new_transcript->end() > $hi_end ) { $hi_end = $new_transcript->end(); } $slice = $new_transcript->slice(); $strand = $new_transcript->strand(); } push( @new_transcripts, $new_transcript ); } if( ! defined $new_gene ) { %$new_gene = %$self; bless $new_gene, ref( $self ); $new_gene->start( $low_start ); $new_gene->end( $hi_end ); $new_gene->strand( $strand ); $new_gene->slice( $slice ); } $new_gene->{'_transcript_array'} = \@new_transcripts; } if(exists $self->{attributes}) { $new_gene->{attributes} = [@{$self->{attributes}}]; } return $new_gene; } =head2 transfer Arg [1] : Bio::EnsEMBL::Slice $destination_slice Example : my $new_gene = $gene->transfer($slice); Description: Moves this Gene to given target slice coordinates. If Transcripts are attached they are moved as well. Returns a new gene. Returntype : Bio::EnsEMBL::Gene Exceptions : none Caller : general Status : Stable =cut sub transfer { my $self = shift; my $new_gene = $self->SUPER::transfer( @_ ); return undef unless $new_gene; if( exists $self->{'_transcript_array'} ) { my @new_transcripts; for my $old_transcript ( @{$self->{'_transcript_array'}} ) { my $new_transcript = $old_transcript->transfer( @_ ); push( @new_transcripts, $new_transcript ); } $new_gene->{'_transcript_array'} = \@new_transcripts; } if(exists $self->{attributes}) { $new_gene->{attributes} = [@{$self->{attributes}}]; } return $new_gene; } =head2 display_xref Arg [1] : (optional) Bio::EnsEMBL::DBEntry - the display xref to set Example : $gene->display_xref($db_entry); Description: Getter/setter display_xref for this gene. Returntype : Bio::EnsEMBL::DBEntry Exceptions : none Caller : general Status : Stable =cut sub display_xref { my $self = shift; $self->{'display_xref'} = shift if(@_); return $self->{'display_xref'}; } =head2 display_id Example : print $gene->display_id(); Description: This method returns a string that is considered to be the 'display' identifier. For genes this is (depending on availability and in this order) the stable Id, the dbID or an empty string. Returntype : String Exceptions : none Caller : web drawing code Status : Stable =cut sub display_id { my $self = shift; return $self->{'stable_id'} || $self->dbID || ''; } =head2 recalculate_coordinates Example : $gene->recalculate_coordinates; Description: Called when transcript added to the gene, tries to adapt the coords for the gene. Returntype : none Exceptions : none Caller : internal Status : Stable =cut sub recalculate_coordinates { my $self = shift; my $transcripts = $self->get_all_Transcripts(); return if(!$transcripts || !@$transcripts); my ( $slice, $start, $end, $strand ); $slice = $transcripts->[0]->slice(); $strand = $transcripts->[0]->strand(); $start = $transcripts->[0]->start(); $end = $transcripts->[0]->end(); my $transsplicing = 0; for my $t ( @$transcripts ) { if( $t->start() < $start ) { $start = $t->start(); } if( $t->end() > $end ) { $end = $t->end(); } if( $t->slice()->name() ne $slice->name() ) { throw( "Transcripts with different slices not allowed on one Gene" ); } if( $t->strand() != $strand ) { $transsplicing = 1; } } if( $transsplicing ) { warning( "Gene contained trans splicing event" ); } $self->start( $start ); $self->end( $end ); $self->strand( $strand ); $self->slice( $slice ); } =head2 get_all_DASFactories Example : $dasref = $prot->get_all_DASFactories Description: Retrieves a listref of registered DAS objects TODO: Abstract to a DBLinkContainer obj Returntype : [ DAS_objects ] Exceptions : none Caller : general Status : Stable =cut sub get_all_DASFactories { my $self = shift; return [ $self->adaptor()->db()->_each_DASFeatureFactory ]; } =head2 get_all_DAS_Features Example : $features = $prot->get_all_DAS_Features; Description: Retrieves a hash reference to a hash of DAS feature sets, keyed by the DNS, NOTE the values of this hash are an anonymous array containing: (1) a pointer to an array of features (2) a pointer to the DAS stylesheet Returntype : hashref of Bio::SeqFeatures Exceptions : none Caller : webcode Status : Stable =cut sub get_all_DAS_Features{ my ($self, @args) = @_; my $slice = $self->feature_Slice; return $self->SUPER::get_all_DAS_Features($slice); } =head2 load Arg [1] : Boolean $load_xrefs Load (or don't load) xrefs. Default is to load xrefs. Example : $gene->load(); Description : The Ensembl API makes extensive use of lazy-loading. Under some circumstances (e.g., when copying genes between databases), all data of an object needs to be fully loaded. This method loads the parts of the object that are usually lazy-loaded. It will also call the equivalent method on all the transcripts of the gene. Returns : =cut sub load { my ( $self, $load_xrefs ) = @_; if ( !defined($load_xrefs) ) { $load_xrefs = 1 } foreach my $transcript ( @{ $self->get_all_Transcripts() } ) { $transcript->load($load_xrefs); } $self->analysis(); $self->get_all_Attributes(); $self->stable_id(); $self->canonical_transcript(); if ($load_xrefs) { $self->get_all_DBEntries(); } } =head2 flush_Transcripts Description : Empties out caches and unsets fields of this Gene. Beware of further actions without adding some new transcripts. Example : $gene->flush_Transcripts(); =cut sub flush_Transcripts { my $self = shift; $self->{'_transcript_array'} = []; $self->{'canonical_transcript_id'} = undef; $self->{'canonical_transcript'} = undef; return; } =head2 is_ref Description: getter setter for the gene attribute is_ref Arg [1] : (optional) 1 or 0 return : boolean =cut sub is_reference{ my ( $self, $is_ref) = @_; if(defined($is_ref)){ $self->{'is_ref'} = $is_ref; } else{ $self->{'is_ref'} = $self->adaptor->is_ref($self->dbID); } return $self->{'is_ref'}; } =head2 summary_as_hash Example : $gene_summary = $gene->summary_as_hash(); Description : Extends Feature::summary_as_hash Retrieves a summary of this Gene object. Returns : hashref of arrays of descriptive strings Status : Intended for internal use =cut sub summary_as_hash { my $self = shift; my $summary_ref = $self->SUPER::summary_as_hash; $summary_ref->{'description'} = $self->description; $summary_ref->{'biotype'} = $self->get_Biotype->name; $summary_ref->{'Name'} = $self->external_name if $self->external_name; $summary_ref->{'logic_name'} = $self->analysis->logic_name() if defined $self->analysis(); $summary_ref->{'source'} = $self->source(); $summary_ref->{'gene_id'} = $summary_ref->{'id'}; ## Will only work for for merged species my $havana_gene = $self->havana_gene(); $summary_ref->{'havana_gene'} = $havana_gene->display_id() if defined $havana_gene; $summary_ref->{'havana_version'} = $havana_gene->version() if defined $havana_gene; ## Stable identifier of the parent gene this gene was projected from my $proj_parent_attributes = $self->get_all_Attributes("proj_parent_g"); if (@{$proj_parent_attributes}) { $summary_ref->{'projection_parent_gene'} = $proj_parent_attributes->[0]->value; } return $summary_ref; } =head2 havana_gene Example : $havana_gene = $transcript->havana_gene(); Description : Locates the corresponding havana gene Returns : Bio::EnsEMBL::DBEntry =cut sub havana_gene { my $self = shift; my @otts = @{ $self->get_all_DBEntries('Vega_gene') }; my $ott; foreach my $xref (@otts) { if ($xref->display_id() =~ /OTT/) { $ott = $xref; last; } } return $ott; } =head2 get_Biotype Example : my $biotype = $gene->get_Biotype; Description: Returns the Biotype object of this gene. When no biotype exists, defaults to 'protein_coding'. When used to set to a biotype that does not exist in the biotype table, a biotype object is created with the provided argument as name and object_type gene. Returntype : Bio::EnsEMBL::Biotype Exceptions : none =cut sub get_Biotype { my ( $self ) = @_; # have a biotype object, return it if ( ref $self->{'biotype'} eq 'Bio::EnsEMBL::Biotype' ) { return $self->{'biotype'}; } # biotype is first set as a string retrieved from the gene table # there is no biotype object in the gene object, retrieve it using the biotype string # if no string, default to protein_coding. this is legacy behaviour and should probably be revisited my $biotype_name = $self->{'biotype'} // 'protein_coding'; return $self->set_Biotype( $biotype_name ); } =head2 set_Biotype Arg [1] : Arg [1] : String - the biotype name to set Example : my $biotype = $gene->set_Biotype('protin_coding'); Description: Sets the Biotype of this gene to the provided biotype name. Returns the Biotype object of this gene. When no biotype exists, defaults to 'protein_coding' name. When setting a biotype that does not exist in the biotype table, a biotype object is created with the provided argument as name and object_type gene. Returntype : Bio::EnsEMBL::Biotype Exceptions : If no argument provided =cut sub set_Biotype { my ( $self, $name ) = @_; throw('No argument provided') unless defined $name; # retrieve biotype object from the biotype adaptor if( defined $self->adaptor() ) { my $ba = $self->adaptor()->db()->get_BiotypeAdaptor(); $self->{'biotype'} = $ba->fetch_by_name_object_type( $name, 'gene' ); } # if $self->adaptor is unavailable, create a new biotype object containing name and object_type only else { $self->{'biotype'} = Bio::EnsEMBL::Biotype->new( -NAME => $name, -OBJECT_TYPE => 'gene', ) } return $self->{'biotype'} ; } =head2 biotype Arg [1] : (optional) String - the biotype to set Example : $gene->biotype("protein_coding"); Description: Getter/setter for the attribute biotype name. Recommended to use instead for a getter: $biotype = $gene->get_Biotype; and for a setter: $biotype = $gene->set_Biotype("protein_coding"); The String biotype name can then be retrieved by calling name on the Biotype object: $biotype_name = $biotype->name; Returntype : String Exceptions : none Caller : general Status : Stable =cut sub biotype { my ( $self, $biotype_name) = @_; # Setter? set_Biotype() if (defined $biotype_name) { return $self->set_Biotype($biotype_name)->name; } # Getter? get_Biotype() return $self->get_Biotype->name; } 1;
muffato/ensembl
modules/Bio/EnsEMBL/Gene.pm
Perl
apache-2.0
45,424
split(L,L1,L2) :- append(L1,L2,L), L1 = [_|_], L2 = [_|_]. %?- split([a,b,c,d,e],A,B) % A=[a] % B=[b,c,d,e] % A=[a,b] % B=[c,d,e] % A=[a,b,c] % B=[d,e] % A=[a,b,c,d] % B=[e] %NO
s-webber/projog
src/test/prolog/miscellaneous/55.pl
Perl
apache-2.0
179
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2021] 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::Document::Image::R2R; use strict; use EnsEMBL::Web::File::Dynamic; use base qw(EnsEMBL::Web::Document::Image); sub render { my ($self, $display_name, $is_thumbnail) = @_; my $database = $self->hub->database('compara'); my ($found_compara, $found_core, $aln_array, $transcript_stable_id, $model_name, $ss_cons); ## Let's try to get the secondary structure from the Compara database ($found_compara, $aln_array, $transcript_stable_id, $model_name, $ss_cons) = $self->find_ss_in_compara($database) if $database; ## Or from Core ($found_core, $aln_array, $transcript_stable_id, $model_name, $ss_cons) = $self->find_ss_in_core() unless $found_compara; return unless ($found_compara or $found_core); ## Here, we can do the drawing my $name = $display_name.'-'.$self->hub->param('g'); my $filename = $name.($is_thumbnail ? '_thumbnail' : '').'.svg'; my $aln_file = $self->_dump_multiple_alignment($aln_array, $model_name, $ss_cons); my ($thumbnail_path, $plot_path) = $self->_create_svg($aln_file, $transcript_stable_id, $model_name, $found_compara ? 1 : 0); return $is_thumbnail ? $thumbnail_path : $plot_path; } sub find_ss_in_compara { my ($self, $database) = @_; my $gma = $database->get_GeneMemberAdaptor(); my $gta = $database->get_GeneTreeAdaptor(); my $member = $gma->fetch_by_stable_id($self->component->object->stable_id); if ($member and $member->has_GeneTree) { my $transcript = $member->get_canonical_SeqMember(); my $gene_tree = $gta->fetch_default_for_Member($member); if ($gene_tree) { my $model_name = $gene_tree->get_tagvalue('model_name'); my $ss_cons = $gene_tree->get_tagvalue('ss_cons'); if ($ss_cons) { my $input_aln = $gene_tree->get_SimpleAlign(); my @aln_array = map {[$_->display_id, $_->seq]} $input_aln->each_seq; return (1, \@aln_array, $transcript->stable_id, $model_name, $ss_cons); } } } return (0); } sub find_ss_in_core { my ($self) = @_; my $gene = $self->hub->core_object('gene')->Obj; my $transcript = $gene->canonical_transcript; if ($transcript) { my $model_name = $gene->display_xref && $gene->display_xref->display_id || $gene->stable_id; my $ss_attr = $transcript->get_all_Attributes('ncRNA'); if ($ss_attr and scalar(@$ss_attr)) { my $ss_cons = $ss_attr->[0]->value; $ss_cons =~ s/^.*\t//; $ss_cons =~ s/([().])(\d+)/$1 x $2/ge; #Expand my $seq = $transcript->spliced_seq; if (length($seq) == length($ss_cons)) { my @aln_array = ([$transcript->stable_id, $seq]); return (1, [[$transcript->stable_id, $seq]], $transcript->stable_id, $model_name, $ss_cons); } } } return (0); } sub _dump_multiple_alignment { my ($self, $aln_array, $model_name, $ss_cons) = @_; if ($ss_cons =~ /^\.+$/) { warn "The tree has no structure\n"; return undef; } ## Note - r2r needs a file on disk, so we explicitly set the driver to IO my $aln_file = EnsEMBL::Web::File::Dynamic->new( hub => $self->hub, sub_dir => 'r2r_'.$self->hub->species, name => $model_name.'.aln', input_drivers => ['IO'], output_drivers => ['IO'], ); unless ($aln_file->exists) { my $content = "# STOCKHOLM 1.0\n"; for my $aln_seq (@$aln_array) { $content .= sprintf ("%-20s %s\n", @$aln_seq); } $content .= sprintf ("%-20s\n", "#=GF R2R keep allpairs"); $content .= sprintf ("%-20s %s\n//\n", "#=GC SS_cons", $ss_cons); $aln_file->write($content); } return $aln_file; } sub _create_svg { my ($self, $aln_file, $peptide_id, $model_name, $with_consensus_structure) = @_; ## Path to the files we dumped earlier my $sub_dir = 'r2r_'.$self->hub->species; my $path = $aln_file->base_read_path.'/'.$sub_dir; my $cons_filename = $model_name.'.cons'; ## For information about these options, check http://breaker.research.yale.edu/R2R/R2R-manual-1.0.3.pdf $self->_run_r2r_and_check("--GSC-weighted-consensus", $aln_file->absolute_read_path, $path, $cons_filename, "3 0.97 0.9 0.75 4 0.97 0.9 0.75 0.5 0.1"); my $thumbnail = $model_name.'_thumbnail.svg'; ## Note - r2r needs a file on disk, so we explicitly set the driver to IO my $th_file = EnsEMBL::Web::File::Dynamic->new( hub => $self->hub, sub_dir => $sub_dir, name => $thumbnail, input_drivers => ['IO'], output_drivers => ['IO'], ); unless ($th_file->exists) { my $th_meta = EnsEMBL::Web::File::Dynamic->new( hub => $self->hub, sub_dir => $sub_dir, name => $model_name.'_thumbnail.meta', input_drivers => ['IO'], output_drivers => ['IO'], ); unless ($th_meta->exists) { my $th_content = "$path/$cons_filename\tskeleton-with-pairbonds\n"; $th_meta->write($th_content); } $self->_run_r2r_and_check("--disable-usage-warning", $th_meta->absolute_read_path, $path, $thumbnail, ""); } my $plot = $model_name.'.svg'; ## Note - r2r needs a file on disk, so we explicitly set the driver to IO my $plot_file = EnsEMBL::Web::File::Dynamic->new( hub => $self->hub, sub_dir => $sub_dir, name => $plot, input_drivers => ['IO'], output_drivers => ['IO'], ); unless ($plot_file->exists) { my $plot_meta = EnsEMBL::Web::File::Dynamic->new( hub => $self->hub, sub_dir => $sub_dir, name => $model_name.'.meta', input_drivers => ['IO'], output_drivers => ['IO'], ); unless ($plot_meta->exists) { my $content = $with_consensus_structure ? "$path/$cons_filename\n" : ''; $content .= $aln_file->absolute_read_path."\toneseq\t$peptide_id\n"; $plot_meta->write($content); } $self->_run_r2r_and_check("--disable-usage-warning", $plot_meta->absolute_read_path, $path, $plot, ""); } return ($th_file->read_url, $plot_file->read_url); } sub _run_r2r_and_check { my ($self, $opts, $inpath, $outpath, $outfile, $extra_params) = @_; my $r2r_exe = $self->hub->species_defs->R2R_BIN; warn "$r2r_exe doesn't exist" unless ($r2r_exe); ## Make temporary directory mkdir($outpath) unless -e $outpath; $outpath .= '/'.$outfile; my $cmd = "$r2r_exe $opts $inpath $outpath $extra_params"; system($cmd); if (! -e $outpath) { warn "Problem running r2r: $outpath doesn't exist\nThis is the command I tried to run:\n$cmd\n"; } return; } 1;
Ensembl/ensembl-webcode
modules/EnsEMBL/Web/Document/Image/R2R.pm
Perl
apache-2.0
8,919
package Google::Ads::AdWords::v201402::PendingInvitation; use strict; use warnings; __PACKAGE__->_set_element_form_qualified(1); sub get_xmlns { 'https://adwords.google.com/api/adwords/mcm/v201402' }; our $XML_ATTRIBUTE_CLASS; undef $XML_ATTRIBUTE_CLASS; sub __get_attr_class { return $XML_ATTRIBUTE_CLASS; } use Class::Std::Fast::Storable constructor => 'none'; use base qw(Google::Ads::SOAP::Typelib::ComplexType); { # BLOCK to scope variables my %manager_of :ATTR(:get<manager>); my %client_of :ATTR(:get<client>); my %creationDate_of :ATTR(:get<creationDate>); my %expirationDate_of :ATTR(:get<expirationDate>); __PACKAGE__->_factory( [ qw( manager client creationDate expirationDate ) ], { 'manager' => \%manager_of, 'client' => \%client_of, 'creationDate' => \%creationDate_of, 'expirationDate' => \%expirationDate_of, }, { 'manager' => 'Google::Ads::AdWords::v201402::ManagedCustomer', 'client' => 'Google::Ads::AdWords::v201402::ManagedCustomer', 'creationDate' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'expirationDate' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', }, { 'manager' => 'manager', 'client' => 'client', 'creationDate' => 'creationDate', 'expirationDate' => 'expirationDate', } ); } # end BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201402::PendingInvitation =head1 DESCRIPTION Perl data type class for the XML Schema defined complexType PendingInvitation from the namespace https://adwords.google.com/api/adwords/mcm/v201402. Pending invitation result for the getPendingInvitations method. =head2 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * manager =item * client =item * creationDate =item * expirationDate =back =head1 METHODS =head2 new Constructor. The following data structure may be passed to new(): =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201402/PendingInvitation.pm
Perl
apache-2.0
2,070
# # Copyright 2022 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 database::informix::sql::mode::globalcache; use base qw(centreon::plugins::mode); use strict; use warnings; use centreon::plugins::statefile; use centreon::plugins::misc; sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { "warning-read:s" => { name => 'warning_read', }, "critical-read:s" => { name => 'critical_read', }, "warning-write:s" => { name => 'warning_write', }, "critical-write:s" => { name => 'critical_write', }, "lookback" => { name => 'lookback', }, }); $self->{statefile_cache} = centreon::plugins::statefile->new(%options); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); if (($self->{perfdata}->threshold_validate(label => 'warning_read', value => $self->{option_results}->{warning_read})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong warning-read threshold '" . $self->{option_results}->{warning_read} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'critical_read', value => $self->{option_results}->{critical_read})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong critical-read threshold '" . $self->{option_results}->{critical_read} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'warning_write', value => $self->{option_results}->{warning_write})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong warning-read threshold '" . $self->{option_results}->{warning_write} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'critical_write', value => $self->{option_results}->{critical_write})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong critical-write threshold '" . $self->{option_results}->{critical_write} . "'."); $self->{output}->option_exit(); } $self->{statefile_cache}->check_options(%options); } sub run { my ($self, %options) = @_; # $options{sql} = sqlmode object $self->{sql} = $options{sql}; $self->{sql}->connect(); $self->{sql}->query(query => q{SELECT name, value FROM sysprofile WHERE name IN ( 'dskreads', 'bufreads', 'bufwrites', 'dskwrites' ) }); my $new_datas = {dskreads => undef, bufreads => undef, bufwrites => undef, dskwrites => undef}; my $result = $self->{sql}->fetchall_arrayref(); foreach my $row (@{$result}) { $new_datas->{centreon::plugins::misc::trim($$row[0])} = $$row[1]; } foreach (keys %$new_datas) { if (!defined($new_datas->{$_})) { $self->{output}->add_option_msg(short_msg => "Cannot get '$_' variable."); $self->{output}->option_exit(); } } $self->{statefile_cache}->read(statefile => 'informix_' . $self->{mode} . '_' . $self->{sql}->get_unique_id4save()); my $old_timestamp = $self->{statefile_cache}->get(name => 'last_timestamp'); $new_datas->{last_timestamp} = time(); if (defined($old_timestamp)) { my $old_dskreads = $self->{statefile_cache}->get(name => 'dskreads'); my $old_bufreads = $self->{statefile_cache}->get(name => 'bufreads'); my $old_bufwrites = $self->{statefile_cache}->get(name => 'bufwrites'); my $old_dskwrites = $self->{statefile_cache}->get(name => 'dskwrites'); $old_dskreads = 0 if ($old_dskreads > $new_datas->{dskreads}); $old_bufreads = 0 if ($old_bufreads > $new_datas->{bufreads}); $old_bufwrites = 0 if ($old_bufwrites > $new_datas->{bufwrites}); $old_dskwrites = 0 if ($old_dskwrites > $new_datas->{dskwrites}); my $diff_bufreads = $new_datas->{bufreads} - $old_bufreads; my $diff_dskreads = $new_datas->{dskreads} - $old_dskreads; my $diff_bufwrites = $new_datas->{bufwrites} - $old_bufwrites; my $diff_dskwrites = $new_datas->{dskwrites} - $old_dskwrites; # 100 * (bufreads - dskreads) / bufreads # 100 * (bufwrits - dskwrits) / bufwrits my %prcts = (); $prcts{readcached_now} = ($diff_bufreads == 0) ? 0 : 100 * ($diff_bufreads - $diff_dskreads) / $diff_bufreads; $prcts{readcached} = ($new_datas->{bufreads} == 0) ? 0 : 100 * ($new_datas->{bufreads} - $new_datas->{dskreads}) / $new_datas->{bufreads}; $prcts{readcached_now} = 0 if ($prcts{readcached_now} < 0); $prcts{readcached} = 0 if ($prcts{readcached} < 0); $prcts{writecached_now} = ($diff_bufwrites == 0) ? 0 : 100 * ($diff_bufwrites - $diff_dskwrites) / $diff_bufwrites; $prcts{writecached} = ($new_datas->{bufwrites} == 0) ? 0 : 100 * ($new_datas->{bufwrites} - $new_datas->{dskwrites}) / $new_datas->{bufwrites}; $prcts{writecached_now} = 0 if ($prcts{writecached_now} < 0); $prcts{writecached} = 0 if ($prcts{writecached} < 0); my $exit_code = $self->{perfdata}->threshold_check(value => $prcts{'readcached' . ((defined($self->{option_results}->{lookback})) ? '' : '_now' )}, threshold => [ { label => 'critical_read', 'exit_litteral' => 'critical' }, { label => 'warning_read', exit_litteral => 'warning' } ]); $self->{output}->output_add(severity => $exit_code, short_msg => sprintf("Read Cached hitrate at %.2f%%", $prcts{'readcached' . ((defined($self->{option_results}->{lookback})) ? '' : '_now')}) ); $self->{output}->perfdata_add(label => 'readcached' . ((defined($self->{option_results}->{lookback})) ? '' : '_now'), unit => '%', value => sprintf("%.2f", $prcts{'readcached' . ((defined($self->{option_results}->{lookback})) ? '' : '_now')}), warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning_read'), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical_read'), min => 0, max => 100); $self->{output}->perfdata_add(label => 'readcached' . ((defined($self->{option_results}->{lookback})) ? '_now' : ''), unit => '%', value => sprintf("%.2f", $prcts{'readcached' . ((defined($self->{option_results}->{lookback})) ? '_now' : '')}), min => 0, max => 100); $exit_code = $self->{perfdata}->threshold_check(value => $prcts{'writecached' . ((defined($self->{option_results}->{lookback})) ? '' : '_now' )}, threshold => [ { label => 'critical_write', 'exit_litteral' => 'critical' }, { label => 'warning_write', exit_litteral => 'warning' } ]); $self->{output}->output_add(severity => $exit_code, short_msg => sprintf("Write Cached hitrate at %.2f%%", $prcts{'writecached' . ((defined($self->{option_results}->{lookback})) ? '' : '_now')}) ); $self->{output}->perfdata_add(label => 'writecached' . ((defined($self->{option_results}->{lookback})) ? '' : '_now'), unit => '%', value => sprintf("%.2f", $prcts{'writecached' . ((defined($self->{option_results}->{lookback})) ? '' : '_now')}), warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning_write'), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical_write'), min => 0, max => 100); $self->{output}->perfdata_add(label => 'writecached' . ((defined($self->{option_results}->{lookback})) ? '_now' : ''), unit => '%', value => sprintf("%.2f", $prcts{'writecached' . ((defined($self->{option_results}->{lookback})) ? '_now' : '')}), min => 0, max => 100); } $self->{statefile_cache}->write(data => $new_datas); if (!defined($old_timestamp)) { $self->{output}->output_add(severity => 'OK', short_msg => "Buffer creation..."); } $self->{output}->display(); $self->{output}->exit(); } 1; __END__ =head1 MODE Check write/read cached. =over 8 =item B<--warning-read> Threshold read cached warning in percent. =item B<--critical-read> Threshold read cached critical in percent. =item B<--warning-write> Threshold write cached warning in percent. =item B<--critical-write> Threshold write cached critical in percent. =item B<--lookback> Threshold isn't on the percent calculated from the difference ('xxxcached_now'). =back =cut
centreon/centreon-plugins
database/informix/sql/mode/globalcache.pm
Perl
apache-2.0
9,867
package Paws::CloudFront::UpdateStreamingDistributionResult; use Moose; has ETag => (is => 'ro', isa => 'Str', traits => ['ParamInHeader'], header_name => 'ETag'); has StreamingDistribution => (is => 'ro', isa => 'Paws::CloudFront::StreamingDistribution'); use MooseX::ClassAttribute; class_has _payload => (is => 'ro', default => 'StreamingDistribution'); has _request_id => (is => 'ro', isa => 'Str'); 1; ### main pod documentation begin ### =head1 NAME Paws::CloudFront::UpdateStreamingDistributionResult =head1 ATTRIBUTES =head2 ETag => Str The current version of the configuration. For example: C<E2QWRUHAPOMQZL>. =head2 StreamingDistribution => L<Paws::CloudFront::StreamingDistribution> The streaming distribution's information. =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/CloudFront/UpdateStreamingDistributionResult.pm
Perl
apache-2.0
771
package VMOMI::VirtualDiskSparseVer1BackingInfo; use parent 'VMOMI::VirtualDeviceFileBackingInfo'; use strict; use warnings; our @class_ancestors = ( 'VirtualDeviceFileBackingInfo', 'VirtualDeviceBackingInfo', 'DynamicData', ); our @class_members = ( ['diskMode', undef, 0, ], ['split', 'boolean', 0, 1], ['writeThrough', 'boolean', 0, 1], ['spaceUsedInKB', undef, 0, 1], ['contentId', undef, 0, 1], ['parent', 'VirtualDiskSparseVer1BackingInfo', 0, 1], ); 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;
stumpr/p5-vmomi
lib/VMOMI/VirtualDiskSparseVer1BackingInfo.pm
Perl
apache-2.0
715
=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. =head1 NAME Bio::EnsEMBL::Compara::PipeConfig::Parts::PrepareMasterDatabaseForRelease =head1 DESCRIPTION This is a partial PipeConfig for most part of the PrepareMasterDatabaseForRelease pipeline. This will update the NCBI taxonomy, add/update all species to master database, update master database's metadata, and update collections and mlss. Finally, it will run the datachecks and perform a backup of the updated master database. =cut package Bio::EnsEMBL::Compara::PipeConfig::Parts::PrepareMasterDatabaseForRelease; use strict; use warnings; use Bio::EnsEMBL::Hive::Version 2.4; use Bio::EnsEMBL::Hive::PipeConfig::HiveGeneric_conf; sub pipeline_analyses_prep_master_db_for_release { my ($self) = @_; return [ { -logic_name => 'patch_master_db', -module => 'Bio::EnsEMBL::Compara::RunnableDB::PrepareMaster::PatchMasterDB', -parameters => { 'schema_file' => $self->o('schema_file'), 'patch_dir' => $self->o('patch_dir'), 'patch_names' => '#patch_dir#/patch_' . $self->o('prev_release') . '_#release#_*.sql', }, -flow_into => ['load_ncbi_node'], }, { -logic_name => 'load_ncbi_node', -module => 'Bio::EnsEMBL::Hive::RunnableDB::MySQLTransfer', -parameters => { 'src_db_conn' => $self->o('taxonomy_db'), 'dest_db_conn' => '#master_db#', 'mode' => 'overwrite', 'filter_cmd' => 'sed "s/ENGINE=MyISAM/ENGINE=InnoDB/g"', 'table' => 'ncbi_taxa_node', }, -flow_into => ['load_ncbi_name'] }, { -logic_name => 'load_ncbi_name', -module => 'Bio::EnsEMBL::Hive::RunnableDB::MySQLTransfer', -parameters => { 'src_db_conn' => $self->o('taxonomy_db'), 'dest_db_conn' => '#master_db#', 'mode' => 'overwrite', 'filter_cmd' => 'sed "s/ENGINE=MyISAM/ENGINE=InnoDB/g"', 'table' => 'ncbi_taxa_name', }, -flow_into => ['import_aliases'], }, { -logic_name => 'import_aliases', -module => 'Bio::EnsEMBL::Compara::RunnableDB::PatchDB', -parameters => { 'db_conn' => '#master_db#', 'patch_file' => $self->o('alias_file'), 'ignore_failure' => 1, 'record_output' => 1, }, -flow_into => ['hc_taxon_names'], }, { -logic_name => 'hc_taxon_names', -module => 'Bio::EnsEMBL::Compara::RunnableDB::PrepareMaster::SqlHealthChecks', -parameters => { 'mode' => 'taxonomy', 'db_conn' => '#master_db#', }, -flow_into => ['assembly_patch_factory'], }, { -logic_name => 'assembly_patch_factory', -module => 'Bio::EnsEMBL::Hive::RunnableDB::JobFactory', -parameters => { 'inputlist' => $self->o('assembly_patch_species'), 'column_names' => ['species_name'], }, -flow_into => { '2->A' => [ 'list_assembly_patches' ], 'A->1' => WHEN( '#do_update_from_metadata#' => 'update_genome_from_metadata_factory', ELSE 'update_genome_from_registry_factory', ), }, }, { -logic_name => 'list_assembly_patches', -module => 'Bio::EnsEMBL::Compara::RunnableDB::PrepareMaster::ListChangedAssemblyPatches', -parameters => { 'compara_db' => '#master_db#', 'work_dir' => $self->o('work_dir'), }, }, { -logic_name => 'update_genome_from_metadata_factory', -module => 'Bio::EnsEMBL::Compara::RunnableDB::PrepareMaster::UpdateGenomesFromMetadataFactory', -parameters => { 'list_genomes_script' => $self->o('list_genomes_script'), 'report_genomes_script' => $self->o('report_genomes_script'), 'additional_species' => $self->o('additional_species'), 'work_dir' => $self->o('work_dir'), 'annotation_file' => $self->o('annotation_file'), 'meta_host' => $self->o('meta_host'), 'allowed_species_file' => $self->o('config_dir') . '/allowed_species.json', 'perc_threshold' => $self->o('perc_threshold'), }, -flow_into => { '2->A' => [ 'add_species_into_master' ], '3->A' => [ 'retire_species_from_master' ], '4->A' => [ 'rename_genome' ], '5->A' => [ 'verify_genome' ], 'A->1' => [ 'sync_metadata' ], }, -rc_name => '16Gb_job', }, { -logic_name => 'update_genome_from_registry_factory', -module => 'Bio::EnsEMBL::Compara::RunnableDB::PrepareMaster::UpdateGenomesFromRegFactory', -parameters => { 'master_db' => $self->o('master_db'), }, -flow_into => { '2->A' => [ 'add_species_into_master' ], '3->A' => [ 'retire_species_from_master' ], '5->A' => [ 'verify_genome' ], 'A->1' => [ 'sync_metadata' ], }, -rc_name => '16Gb_job', }, { -logic_name => 'add_species_into_master', -module => 'Bio::EnsEMBL::Compara::RunnableDB::PrepareMaster::AddSpeciesToMaster', -parameters => { 'release' => 1 }, -hive_capacity => 10, -rc_name => '16Gb_job', }, { -logic_name => 'retire_species_from_master', -module => 'Bio::EnsEMBL::Compara::RunnableDB::PrepareMaster::RetireSpeciesFromMaster', }, { -logic_name => 'rename_genome', -module => 'Bio::EnsEMBL::Compara::RunnableDB::PrepareMaster::RenameGenome', -parameters => { 'prev_dbs' => $self->o('prev_dbs'), 'xml_file' => $self->o('xml_file'), 'species_trees' => $self->o('species_trees'), 'genome_dumps_dir' => $self->o('genome_dumps_dir'), 'sketch_dir' => $self->o('sketch_dir'), }, }, { -logic_name => 'verify_genome', -module => 'Bio::EnsEMBL::Compara::RunnableDB::PrepareMaster::VerifyGenome', -parameters => { 'compara_db' => $self->o('master_db'), }, -hive_capacity => 10, -rc_name => '16Gb_job', }, { -logic_name => 'sync_metadata', -module => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd', -parameters => { 'update_metadata_script' => $self->o('update_metadata_script'), 'reg_conf' => $self->o('reg_conf'), 'cmd' => 'perl #update_metadata_script# --reg_conf #reg_conf# --compara #master_db# --division #division# --nocheck_species_missing_from_compara' }, -flow_into => [ 'update_collection' ], }, { -logic_name => 'update_collection', -module => 'Bio::EnsEMBL::Compara::RunnableDB::CreateReleaseCollection', -parameters => { 'collection_name' => '#division#', 'incl_components' => $self->o('incl_components'), }, -flow_into => [ 'add_mlss_to_master' ], }, { -logic_name => 'add_mlss_to_master', -module => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd', -parameters => { 'create_all_mlss_exe' => $self->o('create_all_mlss_exe'), 'reg_conf' => $self->o('reg_conf'), 'xml_file' => $self->o('xml_file'), 'report_file' => $self->o('report_file'), 'cmd' => 'perl #create_all_mlss_exe# --reg_conf #reg_conf# --compara #master_db# -xml #xml_file# --release --output_file #report_file# --verbose', }, -flow_into => [ 'retire_old_species_sets' ], -rc_name => '2Gb_job', }, { -logic_name => 'retire_old_species_sets', -module => 'Bio::EnsEMBL::Hive::RunnableDB::DbCmd', -parameters => { 'db_conn' => '#master_db#', 'input_query' => 'UPDATE species_set_header JOIN (SELECT species_set_id, MAX(method_link_species_set.last_release) AS highest_last_release FROM species_set_header JOIN method_link_species_set USING (species_set_id) WHERE species_set_header.first_release IS NOT NULL AND species_set_header.last_release IS NULL GROUP BY species_set_id HAVING SUM(method_link_species_set.first_release IS NOT NULL AND method_link_species_set.last_release IS NULL) = 0) _t USING (species_set_id) SET last_release = highest_last_release;', }, -flow_into => WHEN( '#do_load_timetree#' => 'load_timetree', ELSE 'reset_master_urls', ), }, { -logic_name => 'load_timetree', -module => 'Bio::EnsEMBL::Compara::RunnableDB::SpeciesTree::LoadTimeTree', -parameters => { 'compara_db' => '#master_db#', }, -flow_into => [ 'reset_master_urls' ], }, { -logic_name => 'reset_master_urls', -module => 'Bio::EnsEMBL::Hive::RunnableDB::DbCmd', -parameters => { 'db_conn' => '#master_db#', 'input_query' => 'UPDATE method_link_species_set SET url = "" WHERE source = "ensembl"', }, -flow_into => [ 'dc_master' ], }, { -logic_name => 'dc_master', -module => 'Bio::EnsEMBL::Compara::RunnableDB::RunDataChecks', -parameters => { 'datacheck_groups' => ['compara_master'], 'work_dir' => $self->o('work_dir'), 'history_file' => '#work_dir#/datacheck.compara_master.history.json', 'output_file' => '#work_dir#/datacheck.compara_master.tap.txt', 'failures_fatal' => 1, 'datacheck_types' => ['critical'], 'registry_file' => $self->o('reg_conf'), 'compara_db' => '#master_db#', }, -flow_into => { 1 => { 'backup_master' => {} }, }, -max_retry_count => 0, -rc_name => '500Mb_job', }, { -logic_name => 'backup_master', -module => 'Bio::EnsEMBL::Hive::RunnableDB::DatabaseDumper', -parameters => { 'src_db_conn' => '#master_db#', 'output_file' => $self->o('master_backup_file'), }, -flow_into => [ 'copy_pre_backup_to_warehouse' ], -rc_name => '1Gb_job', }, { -logic_name => 'copy_pre_backup_to_warehouse', -module => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd', -parameters => { 'backups_dir' => $self->o('backups_dir'), 'warehouse_dir' => $self->o('warehouse_dir'), 'cmd' => 'cp #backups_dir#/compara_master_#division#.pre#release#.sql #warehouse_dir#/master_db_dumps/ensembl_compara_master_#division#.$(date "+%Y%m%d").pre#release#.sql', }, -flow_into => [ 'copy_post_backup_to_warehouse' ], }, { -logic_name => 'copy_post_backup_to_warehouse', -module => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd', -parameters => { 'backups_dir' => $self->o('backups_dir'), 'warehouse_dir' => $self->o('warehouse_dir'), 'cmd' => 'cp #backups_dir#/compara_master_#division#.post#release#.sql #warehouse_dir#/master_db_dumps/ensembl_compara_master_#division#.$(date "+%Y%m%d").during#release#.sql', }, -flow_into => WHEN( '#do_update_from_metadata#' => 'copy_annotations_to_shared_loc' ), }, { -logic_name => 'copy_annotations_to_shared_loc', -module => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd', -parameters => { 'annotation_file' => $self->o('annotation_file'), 'shared_hps_dir' => $self->o('shared_hps_dir'), 'cmd' => 'install -C --mode=664 #annotation_file# #shared_hps_dir#/genome_reports/', }, -flow_into => [ 'copy_json_reports_to_shared_loc' ], }, { -logic_name => 'copy_json_reports_to_shared_loc', -module => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd', -parameters => { 'work_dir' => $self->o('work_dir'), 'shared_hps_dir' => $self->o('shared_hps_dir'), 'cmd' => 'install -C --mode=664 -t #shared_hps_dir#/genome_reports/ #work_dir#/report_updates.*.json', }, }, ]; } 1;
Ensembl/ensembl-compara
modules/Bio/EnsEMBL/Compara/PipeConfig/Parts/PrepareMasterDatabaseForRelease.pm
Perl
apache-2.0
14,214
package VMOMI::ArrayOfHostTpmEventLogEntry; use parent 'VMOMI::ComplexType'; use strict; use warnings; our @class_ancestors = ( ); our @class_members = ( ['HostTpmEventLogEntry', 'HostTpmEventLogEntry', 1, 1], ); 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;
stumpr/p5-vmomi
lib/VMOMI/ArrayOfHostTpmEventLogEntry.pm
Perl
apache-2.0
438
use strict; use warnings; package CPAN::Testers::Metabase::AWS; # ABSTRACT: Metabase backend on Amazon Web Services our $VERSION = '1.999002'; # VERSION use Moose; use Metabase::Archive::S3 1.000; use Metabase::Index::SimpleDB 1.000; use Metabase::Librarian 1.000; use Net::Amazon::Config; use namespace::autoclean; with 'Metabase::Gateway'; has 'bucket' => ( is => 'ro', isa => 'Str', required => 1, ); has 'namespace' => ( is => 'ro', isa => 'Str', required => 1, ); has 'amazon_config' => ( is => 'ro', isa => 'Net::Amazon::Config', default => sub { return Net::Amazon::Config->new }, ); has 'profile_name' => ( is => 'ro', isa => 'Str', default => 'cpantesters' ); has '_profile' => ( is => 'ro', isa => 'Net::Amazon::Config::Profile', lazy => 1, builder => '_build__profile', handles => [ qw/access_key_id secret_access_key/ ], ); sub _build__profile { my $self = shift; return $self->amazon_config->get_profile( $self->profile_name ); } sub _build_fact_classes { return [qw/CPAN::Testers::Report/] } sub _build_public_librarian { return $_[0]->__build_librarian("public") } sub _build_private_librarian { return $_[0]->__build_librarian("private") } sub __build_librarian { my ($self, $subspace) = @_; my $bucket = $self->bucket; my $namespace = $self->namespace; my $s3_prefix = "metabase/${namespace}/${subspace}/"; my $sdb_domain = "${bucket}.metabase.${namespace}.${subspace}"; return Metabase::Librarian->new( archive => Metabase::Archive::S3->new( access_key_id => $self->access_key_id, secret_access_key => $self->secret_access_key, bucket => $self->bucket, prefix => $s3_prefix, compressed => 1, retry => 1, ), index => Metabase::Index::SimpleDB->new( access_key_id => $self->access_key_id, secret_access_key => $self->secret_access_key, domain => $sdb_domain, ), ); } __PACKAGE__->meta->make_immutable; 1; =pod =head1 NAME CPAN::Testers::Metabase::AWS - Metabase backend on Amazon Web Services =head1 VERSION version 1.999002 =head1 SYNOPSIS =head2 Direct usage use CPAN::Testers::Metabase::AWS; my $mb = CPAN::Testers::Metabase::AWS->new( bucket => 'myS3bucket', namespace => 'prod' ); $mb->public_librarian->search( %search spec ); ... =head2 Metabase::Web config --- Model::Metabase: class: CPAN::Testers::Metabase::AWS args: bucket: myS3bucket namespace: prod =head1 DESCRIPTION This class instantiates a Metabase backend on the S3 and SimpleDB Amazon Web Services (AWS). It uses L<Net::Amazon::Config> to provide user credentials and the L<Metabase::Gateway> Role to provide actual functionality. As such, it is mostly glue to get the right credentials to setup AWS clients and provide them with standard resource names. For example, given the C<<< bucket >>> "example" and the C<<< namespace >>> "alpha", the following resource names would be used: Public S3: http://example.s3.amazonaws.com/metabase/alpha/public/* Public SDB domain: example.metabase.alpha.public Private S3: http://example.s3.amazonaws.com/metabase/alpha/private/* Private SDB domain: example.metabase.alpha.private =head1 USAGE =head2 new my $mb = CPAN::Testers::Metabase::AWS->new( bucket => 'myS3bucket', namespace => 'prod', profile_name => 'cpantesters', ); Arguments for C<<< new >>>: =over =item * C<<< bucket >>> -- required -- the Amazon S3 bucket name to hold both public and private fact content. Bucket names must be unique across all of AWS. The bucket name is also used as part of the SimpleDB namespace for consistency. =item * C<<< namespace >>> -- required -- a short phrase that uniquely identifies this metabase. E.g. "dev", "test" or "prod". It is used to specify specific locations within the S3 bucket and to uniquely identify a SimpleDB domain for indexing. =item * C<<< amazon_config >>> -- optional -- a L<Net::Amazon::Config> object containing Amazon Web Service credentials. If not provided, one will be created using the default location for the config file. =item * C<<< profile_name >>> -- optional -- the name of a profile for use with Net::Amazon::Config. If not provided, it defaults to 'cpantesters'. =back =head2 access_key_id Returns the AWS Access Key ID. =head2 secret_access_key Returns the AWS Secret Access Key =head2 Metabase::Gateway Role This class does the L<Metabase::Gateway> role, including the following methods: =over =item * C<<< handle_submission >>> =item * C<<< handle_registration >>> =item * C<<< enqueue >>> =back see L<Metabase::Gateway> for more. =head1 SEE ALSO =over =item * L<CPAN::Testers::Metabase> =item * L<Metabase::Gateway> =item * L<Metabase::Web> =item * L<Net::Amazon::Config> =back =for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan =head1 SUPPORT =head2 Bugs / Feature Requests Please report any bugs or feature requests through the issue tracker at L<http://rt.cpan.org/Public/Dist/Display.html?Name=CPAN-Testers-Metabase-AWS>. You will be notified automatically of any progress on your issue. =head2 Source Code This is open source software. The code repository is available for public review and contribution under the terms of the license. L<https://github.com/dagolden/cpan-testers-metabase-aws> git clone https://github.com/dagolden/cpan-testers-metabase-aws.git =head1 AUTHOR David Golden <dagolden@cpan.org> =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2012 by David Golden. This is free software, licensed under: The Apache License, Version 2.0, January 2004 =cut __END__
gitpan/CPAN-Testers-Metabase-AWS
lib/CPAN/Testers/Metabase/AWS.pm
Perl
apache-2.0
5,918
package VMOMI::ArrayOfHostSystemResourceInfo; use parent 'VMOMI::ComplexType'; use strict; use warnings; our @class_ancestors = ( ); our @class_members = ( ['HostSystemResourceInfo', 'HostSystemResourceInfo', 1, 1], ); 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;
stumpr/p5-vmomi
lib/VMOMI/ArrayOfHostSystemResourceInfo.pm
Perl
apache-2.0
444
# # This file is part of HTML-FormFu-ExtJS # # This software is Copyright (c) 2011 by Moritz Onken. # # This is free software, licensed under: # # The (three-clause) BSD License # package HTML::FormFu::ExtJS::Element::Repeatable; BEGIN { $HTML::FormFu::ExtJS::Element::Repeatable::VERSION = '0.090'; } use strict; use warnings; use utf8; sub render { my $class = shift; my $self = shift; return @{$self->form->_render_items($self)}; } 1; __END__ =pod =head1 NAME HTML::FormFu::ExtJS::Element::Repeatable =head1 VERSION version 0.090 =head1 AUTHOR Moritz Onken <onken@netcubed.de> =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2011 by Moritz Onken. This is free software, licensed under: The (three-clause) BSD License =cut
gitpan/HTML-FormFu-ExtJS
lib/HTML/FormFu/ExtJS/Element/Repeatable.pm
Perl
bsd-3-clause
762
#!/usr/bin/env perl use strict; die "USAGE: $0 KEGGftp/ligand/compound/compound" unless $#ARGV == 1; $/ = '///'; open COMPOUND, $ARGV[0] || die $!; while(<COMPOUND>) { /^ENTRY\s+ (?<CPD>C\d{5}).* ^NAME\s+ (?<NAME> .*?)\n.* /xsm; my $cpd = $+{CPD}; my $name = $+{NAME}; my $exact = 0; my $mol = 0; if(m/^EXACT_MASS\s+ \S+.* ^MOL_WEIGHT\s+ \S+\n/xsm){ m/^EXACT_MASS\s+ (?<EXACT>\S+).* ^MOL_WEIGHT\s+ (?<MOL>\S+)\n/xsm; $exact = $+{EXACT}; $mol = $+{MOL}; } print join("\t", "cpd:$cpd", $name, $exact, $mol),"\n" unless (length($cpd) == 0); } close COMPOUND; open GLYCAN, $ARGV[1] || die $!; while(<GLYCAN>) { my ($cpd) = $_ =~ /ENTRY\s+(G\d{5})/xsm; /NAME\s+(?<NAME> .*?)\n #I'm just taking the first symbol name associated with this /xsm; print "gl:$cpd\t$+{NAME}\n" unless (length($cpd) == 0) } close GLYCAN; __DATA__ ENTRY C00001 Compound NAME H2O; Water FORMULA H2O EXACT_MASS 18.0106 MOL_WEIGHT 18.0153 REMARK Same as: D00001 REACTION R00001 R00002 R00004 R00005 R00009 R00010 R00011 R00017 R00022 R00024 R00025 R00026 R00028 R00036 R00041 R00044 R00045 R00047 R00048 R00052 R00053 R00054 R00055 R00056
etheleon/keggParser
kegg.0200.cpd_nodedetails.pl
Perl
mit
1,275
#!/usr/bin/perl print "Content-type: text/html \n\n"; print "Hello, World.";
rbowen/presentations
big_tent/first.pl
Perl
apache-2.0
78
package Paws::CloudDirectory::DetachFromIndexResponse; use Moose; has DetachedObjectIdentifier => (is => 'ro', isa => 'Str'); has _request_id => (is => 'ro', isa => 'Str'); 1; ### main pod documentation begin ### =head1 NAME Paws::CloudDirectory::DetachFromIndexResponse =head1 ATTRIBUTES =head2 DetachedObjectIdentifier => Str The C<ObjectIdentifier> of the object that was detached from the index. =head2 _request_id => Str =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/CloudDirectory/DetachFromIndexResponse.pm
Perl
apache-2.0
451
# ${license-info} # ${developer-info} # ${author-info} # ${build-info} package Test::Quattor::TextRender::Suite; use strict; use warnings; use Test::More; use Cwd qw(abs_path); use File::Basename; use File::Find; use Test::Quattor::ProfileCache qw(prepare_profile_cache set_profile_cache_options); use Test::Quattor::Panc qw(set_panc_includepath get_panc_includepath); use Test::Quattor::TextRender::RegexpTest; use base qw(Test::Quattor::Object); =pod =head1 NAME Test::Quattor::TextRender::Suite - Class for a template test suite. =head1 DESCRIPTION A TextRender test suite corresponds to one or more regexptests that are tested against the profile genereated from one corresponding object template. A test suite can be a combination of file (implying one regexptest, and that file being the regexptest) and/or a directory (one or more regexptests; each file in the directory is one regexptest; no subdirectory structure allowed); with the file or directory name identical to the corresponding object template. The names cannot start with a '.'. =head1 new Support options =over =item testspath Basepath for the suite tests. =item regexps Path to the suite regexptests (C<testspath>/regexps is default when not specified). =item profiles Path to the suite object templates (C<testspath>/profiles is default when not specified). =item ttincludepath Includepath to use for CAF::TextRender. =item ttrelpath relpath to use for CAF::TextRender. =item filter A compiled regular expression that is used to filter the found regexptest files (matching relative filenames are kept; non-matcing ones are removed). One can also set the C<QUATTOR_TEST_SUITE_FILTER> enviroment variable, which will be used as regular expression pattern for the filter. =back =cut # TODO rename all references here and in actual directories to resources for uniform naming sub _initialize { my ($self) = @_; # TT includepath $self->{ttincludepath} = abs_path($self->{ttincludepath}); if (defined($self->{ttincludepath})) { ok(-d $self->{ttincludepath}, "TT includepath $self->{ttincludepath} exists"); } else { $self->notok("ttincludepath not defined"); } # TT relpath ok($self->{ttrelpath}, "TT relpath defined ".($self->{ttrelpath} || '<undef>')); # testspath $self->{testspath} = abs_path($self->{testspath}); if (defined($self->{testspath})) { ok(-d $self->{testspath}, "testspath $self->{testspath} exists"); } else { $self->notok("testspath not defined"); } # profilespath if ($self->{profilespath}) { if ($self->{profilespath} !~ m/^\//) { $self->verbose("Relative profilespath $self->{profilespath} found"); $self->{profilespath} = "$self->{testspath}/$self->{profilespath}"; } } else { $self->{profilespath} = "$self->{testspath}/profiles"; } $self->{profilespath} = abs_path($self->{profilespath}); if (defined($self->{profilespath})) { ok(-d $self->{profilespath}, "profilespath $self->{profilespath} exists"); } else { $self->notok("profilespath not defined"); } # regexpspath if ($self->{regexpspath}) { if ($self->{regexpspath} !~ m/^\//) { $self->verbose("Relative regexpspath $self->{regexpspath} found"); $self->{regexpspath} = "$self->{testspath}/$self->{regexpspath}"; } } else { $self->{regexpspath} = "$self->{testspath}/regexps"; } $self->{regexpspath} = abs_path($self->{regexpspath}); if (defined($self->{regexpspath})) { ok(-d $self->{regexpspath}, "regexpspath $self->{regexpspath} exists"); } else { $self->notok("regexpspath not defined"); } # Filter my $filter = $ENV{QUATTOR_TEST_SUITE_FILTER}; if ($filter) { $self->{filter} = qr{$filter}; $self->info( "Filter $self->{filter} set via environment variable QUATTOR_TEST_SUITE_FILTER"); } if ($self->{filter}) { $self->verbose("Filter $self->{filter} defined"); } } =pod =head2 gather_regexp Find all regexptests. Files/directories that start with a '.' are ignored. Returns hash ref with name as key and array ref of the regexptests paths. =cut sub gather_regexp { my ($self) = @_; my %regexps; if (!-d $self->{regexpspath}) { $self->notok("regexpspath $self->{regexpspath} is not a directory"); return \%regexps; } opendir(DIR, $self->{regexpspath}); foreach my $name (grep {!m/^\./} sort readdir(DIR)) { my $abs = "$self->{regexpspath}/$name"; my @files; if (-f $abs) { $self->verbose("Found regexps file $name (abs $abs)"); push(@files, $name); } elsif (-d $abs) { opendir(my $dh, $abs); # only files @files = map {"$name/$_"} grep {!m/^\./ && -T "$abs/$_"} sort readdir($dh); closedir $dh; $self->verbose( "Found regexps directory $name (abs $abs) with files " . join(", ", @files)); } else { $self->notok("Invalid regexp abs $abs found"); } if ($self->{filter}) { @files = grep {/$self->{filter}/} @files; $self->verbose("After filter $self->{filter} files " . join(", ", @files)); } $regexps{$name} = \@files if @files; } closedir(DIR); return \%regexps; } =pod =head2 gather_profile Create a hash reference of all object templates in the 'profilespath' with name key and filepath as value. =cut sub gather_profile { my ($self) = @_; # empty namespace my ($pans, $ipans) = $self->gather_pan($self->{profilespath}, $self->{profilespath}, ''); is(scalar @$ipans, 0, 'No invalid pan templates'); my %objs; while (my ($pan, $value) = each %$pans) { my $name = basename($pan); $name =~ s/\.pan$//; if ($value->{type} eq 'object') { if ((! $self->{filter}) || $name =~ m/$self->{filter}/) { $objs{$name} = $pan; } } } return \%objs; } =pod =head2 one_test Run all regexptest C<$regexps> for a single test profile C<profile> with name C<name>. =cut sub regexptest { my ($self, $name, $profile, $regexps) = @_; $self->verbose("regexptest name $name profile $profile"); # Compile, setup CCM cache and get the configuration instance my $cfg = prepare_profile_cache($profile); foreach my $regexp (@$regexps) { my $regexptest = Test::Quattor::TextRender::RegexpTest->new( regexp => "$self->{regexpspath}/$regexp", config => $cfg, ttrelpath => $self->{ttrelpath}, ttincludepath => $self->{ttincludepath}, )->test(); } } =pod =head2 test Run all tests to validate the suite. =cut sub test { my ($self) = @_; my $regexps = $self->gather_regexp(); ok($regexps, "Found regexps"); my $profiles = $self->gather_profile(); ok($profiles, "Found profiles"); is_deeply([sort keys %$regexps], [sort keys %$profiles], "All regexps have matching profile"); my $incdirs = get_panc_includepath(); push(@$incdirs, $self->{profilespath}) if (! (grep { $_ eq $self->{profilespath}} @$incdirs)); set_panc_includepath(@$incdirs); set_profile_cache_options(resources => $self->{profilespath}); foreach my $name (sort keys %$regexps) { $self->regexptest($name, "$self->{profilespath}/$profiles->{$name}", $regexps->{$name}); } } 1;
quattor/maven-tools
build-scripts/src/main/perl/Test/Quattor/TextRender/Suite.pm
Perl
apache-2.0
7,602
package Google::Ads::AdWords::v201406::TrafficEstimatorService::ResponseHeader; use strict; use warnings; { # BLOCK to scope variables sub get_xmlns { 'https://adwords.google.com/api/adwords/o/v201406' } __PACKAGE__->__set_name('ResponseHeader'); __PACKAGE__->__set_nillable(); __PACKAGE__->__set_minOccurs(); __PACKAGE__->__set_maxOccurs(); __PACKAGE__->__set_ref(); use base qw( SOAP::WSDL::XSD::Typelib::Element Google::Ads::AdWords::v201406::SoapResponseHeader ); } 1; =pod =head1 NAME Google::Ads::AdWords::v201406::TrafficEstimatorService::ResponseHeader =head1 DESCRIPTION Perl data type class for the XML Schema defined element ResponseHeader from the namespace https://adwords.google.com/api/adwords/o/v201406. =head1 METHODS =head2 new my $element = Google::Ads::AdWords::v201406::TrafficEstimatorService::ResponseHeader->new($data); Constructor. The following data structure may be passed to new(): $a_reference_to, # see Google::Ads::AdWords::v201406::SoapResponseHeader =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201406/TrafficEstimatorService/ResponseHeader.pm
Perl
apache-2.0
1,063
#------------------------------------------------------------------------------ # File: PICT.pm # # Description: Read PICT meta information # # Revisions: 10/10/2005 - P. Harvey Created # # Notes: Extraction of PICT opcodes is still experimental # # - size difference in PixPat color table?? (imagemagick reads only 1 long per entry) # - other differences in the way imagemagick reads 16-bit images # # References: 1) http://developer.apple.com/documentation/mac/QuickDraw/QuickDraw-2.html # 2) http://developer.apple.com/documentation/QuickTime/INMAC/QT/iqImageCompMgr.a.htm #------------------------------------------------------------------------------ package Image::ExifTool::PICT; use strict; use vars qw($VERSION); use Image::ExifTool qw(:DataAccess :Utils); $VERSION = '1.03'; sub ReadPictValue($$$;$); my ($vers, $extended); # PICT version number, and extended flag my ($verbose, $out, $indent); # used in verbose mode # ranges of reserved opcodes. # opcodes at the start of each range must be defined in the tag table my @reserved = ( 0x0017 => 0x0019, 0x0024 => 0x0027, 0x0035 => 0x0037, 0x003d => 0x003f, 0x0045 => 0x0047, 0x004d => 0x004f, 0x0055 => 0x0057, 0x005d => 0x005f, 0x0065 => 0x0067, 0x006d => 0x006f, 0x0075 => 0x0077, 0x007d => 0x007f, 0x0085 => 0x0087, 0x008d => 0x008f, 0x0092 => 0x0097, 0x00a2 => 0x00af, 0x00b0 => 0x00cf, 0x00d0 => 0x00fe, 0x0100 => 0x01ff, 0x0300 => 0x0bfe, 0x0c01 => 0x7eff, 0x7f00 => 0x7fff, 0x8000 => 0x80ff, 0x8100 => 0x81ff, 0x8201 => 0xffff, ); # Apple data structures in PICT images my %structs = ( Arc => [ rect => 'Rect', startAng => 'int16s', arcAng => 'int16s', ], BitMap => [ # (no baseAddr) rowBytes => 'int16u', bounds => 'Rect', ], # BitsRect data for PICT version 1 BitsRect1 => [ bitMap => 'BitMap', srcRect => 'Rect', dstRect => 'Rect', mode => 'int16u', dataSize => 'int16u', bitData => 'binary[$val{dataSize}]', ], # BitsRect data for PICT version 2 BitsRect2 => [ pixMap => 'PixMap', colorTable => 'ColorTable', srcRect => 'Rect', dstRect => 'Rect', mode => 'int16u', pixData => \ 'GetPixData($val{pixMap}, $raf)', ], # BitsRgn data for PICT version 1 BitsRgn1 => [ bitMap => 'BitMap', srcRect => 'Rect', dstRect => 'Rect', mode => 'int16u', maskRgn => 'Rgn', dataSize => 'int16u', bitData => 'binary[$val{dataSize}]', ], # BitsRgn data for PICT version 2 BitsRgn2 => [ pixMap => 'PixMap', colorTable => 'ColorTable', srcRect => 'Rect', dstRect => 'Rect', mode => 'int16u', maskRgn => 'Rgn', pixData => \ 'GetPixData($val{pixMap}, $raf)', ], ColorSpec => [ value => 'int16u', rgb => 'RGBColor', ], ColorTable => [ ctSeed => 'int32u', ctFlags => 'int16u', ctSize => 'int16u', ctTable => 'ColorSpec[$val{ctSize}+1]', ], # http://developer.apple.com/documentation/QuickTime/INMAC/QT/iqImageCompMgr.a.htm CompressedQuickTime => [ size => 'int32u', # size NOT including size word version => 'int16u', matrix => 'int32u[9]', matteSize => 'int32u', matteRect => 'Rect', mode => 'int16u', srcRect => 'Rect', accuracy => 'int32u', maskSize => 'int32u', matteDescr => 'Int32uData[$val{matteSize} ? 1 : 0]', matteData => 'int8u[$val{matteSize}]', maskRgn => 'int8u[$val{maskSize}]', imageDescr => 'ImageDescription', # size should be $val{imageDescr}->{dataSize}, but this is unreliable imageData => q{binary[$val{size} - 68 - $val{maskSize} - $val{imageDescr}->{size} - ($val{matteSize} ? $val{mattSize} + $val{matteDescr}->{size} : 0)] }, ], DirectBitsRect => [ baseAddr => 'int32u', pixMap => 'PixMap', srcRect => 'Rect', dstRect => 'Rect', mode => 'int16u', pixData => \ 'GetPixData($val{pixMap}, $raf)', ], DirectBitsRgn => [ baseAddr => 'int32u', pixMap => 'PixMap', srcRect => 'Rect', dstRect => 'Rect', mode => 'int16u', maskRgn => 'Rgn', pixData => \ 'GetPixData($val{pixMap}, $raf)', ], # http://developer.apple.com/technotes/qd/qd_01.html FontName => [ size => 'int16u', # size NOT including size word oldFontID => 'int16u', nameLen => 'int8u', fontName => 'string[$val{nameLen}]', padding => 'binary[$val{size} - $val{nameLen} - 3]', ], # http://developer.apple.com/documentation/QuickTime/APIREF/imagedescription.htm ImageDescription => [ size => 'int32u', # size INCLUDING size word cType => 'string[4]', res1 => 'int32u', res2 => 'int16u', dataRefIndex => 'int16u', version => 'int16u', revision => 'int16u', vendor => 'string[4]', temporalQuality => 'int32u', quality => 'int32u', width => 'int16u', height => 'int16u', hRes => 'fixed32u', vRes => 'fixed32u', dataSize => 'int32u', frameCount => 'int16u', nameLen => 'int8u', compressor => 'string[31]', depth => 'int16u', clutID => 'int16u', clutData => 'binary[$val{size}-86]', ], Int8uText => [ val => 'int8u', count => 'int8u', text => 'string[$val{count}]', ], Int8u2Text => [ val => 'int8u[2]', count => 'int8u', text => 'string[$val{count}]', ], Int16Data => [ size => 'int16u', # size NOT including size word data => 'int8u[$val{size}]', ], Int32uData => [ size => 'int32u', # size NOT including size word data => 'int8u[$val{size}]', ], LongComment => [ kind => 'int16u', size => 'int16u', # size of data only data => 'binary[$val{size}]', ], PixMap => [ # Note: does not contain baseAddr # (except for DirectBits opcodes in which it is loaded separately) rowBytes => 'int16u', bounds => 'Rect', pmVersion => 'int16u', packType => 'int16u', packSize => 'int32u', hRes => 'fixed32s', vRes => 'fixed32s', pixelType => 'int16u', pixelSize => 'int16u', cmpCount => 'int16u', cmpSize => 'int16u', planeBytes => 'int32u', pmTable => 'int32u', pmReserved => 'int32u', ], PixPat => [ patType => 'int16u', # 1 = non-dithered, 2 = dithered pat1Data => 'int8u[8]', # dithered PixPat has RGB entry RGB => 'RGBColor[$val{patType} == 2 ? 1 : 0]', # non-dithered PixPat has other stuff instead nonDithered=> 'PixPatNonDithered[$val{patType} == 2 ? 0 : 1]', ], PixPatNonDithered => [ pixMap => 'PixMap', colorTable => 'ColorTable', pixData => \ 'GetPixData($val{pixMap}, $raf)', ], Point => [ v => 'int16s', h => 'int16s', ], PointText => [ txLoc => 'Point', count => 'int8u', text => 'string[$val{count}]', ], Polygon => [ polySize => 'int16u', polyBBox => 'Rect', polyPoints => 'int16u[($val{polySize}-10)/2]', ], Rect => [ topLeft => 'Point', botRight => 'Point', ], RGBColor => [ red => 'int16u', green => 'int16u', blue => 'int16u', ], Rgn => [ rgnSize => 'int16u', rgnBBox => 'Rect', data => 'int8u[$val{rgnSize}-10]', ], ShortLine => [ pnLoc => 'Point', dh => 'int8s', dv => 'int8s', ], # http://developer.apple.com/documentation/QuickTime/INMAC/QT/iqImageCompMgr.a.htm UncompressedQuickTime => [ size => 'int32u', # size NOT including size word version => 'int16u', matrix => 'int32u[9]', matteSize => 'int32u', matteRect => 'Rect', matteDescr => 'Int32uData[$val{matteSize} ? 1 : 0]', matteData => 'binary[$val{matteSize}]', subOpcodeData => q{ binary[ $val{size} - 50 - ($val{matteSize} ? $val{mattSize} + $val{matteDescr}->{size} : 0)] }, ], ); # PICT image opcodes %Image::ExifTool::PICT::Main = ( PROCESS_PROC => 0, # set this to zero to omit tags from lookup NOTES => q{ The PICT format contains no true meta information, except for the possible exception of the LongComment opcode. By default, only ImageWidth, ImageHeight and X/YResolution are extracted from a PICT image. Tags in the following table represent image opcodes. Extraction of these tags is experimental, and is only enabled with the Verbose or Unknown options. }, 0x0000 => { Name => 'Nop', Description => 'No Operation', Format => 'null', }, 0x0001 => { Name => 'ClipRgn', Description => 'Clipping Region', Format => 'Rgn', }, 0x0002 => { Name => 'BkPat', Description => 'Background Pattern', Format => 'int8u[8]', }, 0x0003 => { Name => 'TxFont', Description => 'Font Number', Format => 'int16u', }, 0x0004 => { Name => 'TxFace', Description => 'Text Font Style', Format => 'int8u', }, 0x0005 => { Name => 'TxMode', Description => 'Text Source Mode', Format => 'int16u', }, 0x0006 => { Name => 'SpExtra', Description => 'Extra Space', Format => 'fixed32s', }, 0x0007 => { Name => 'PnSize', Description => 'Pen Size', Format => 'Point', }, 0x0008 => { Name => 'PnMode', Description => 'Pen Mode', Format => 'int16u', }, 0x0009 => { Name => 'PnPat', Description => 'Pen Pattern', Format => 'int8u[8]', }, 0x000a => { Name => 'FillPat', Description => 'Fill Pattern', Format => 'int8u[8]', }, 0x000b => { Name => 'OvSize', Description => 'Oval Size', Format => 'Point', }, 0x000c => { Name => 'Origin', Format => 'Point', }, 0x000d => { Name => 'TxSize', Description => 'Text Size', Format => 'int16u', }, 0x000e => { Name => 'FgColor', Description => 'Foreground Color', Format => 'int32u', }, 0x000f => { Name => 'BkColor', Description => 'Background Color', Format => 'int32u', }, 0x0010 => { Name => 'TxRatio', Description => 'Text Ratio', Format => 'Rect', }, 0x0011 => { Name => 'VersionOp', Description => 'Version', Format => 'int8u', }, 0x0012 => { Name => 'BkPixPat', Description => 'Background Pixel Pattern', Format => 'PixPat', }, 0x0013 => { Name => 'PnPixPat', Description => 'Pen Pixel Pattern', Format => 'PixPat', }, 0x0014 => { Name => 'FillPixPat', Description => 'Fill Pixel Pattern', Format => 'PixPat', }, 0x0015 => { Name => 'PnLocHFrac', Description => 'Fractional Pen Position', Format => 'int16u', }, 0x0016 => { Name => 'ChExtra', Description => 'Added Width for NonSpace Characters', Format => 'int16u', }, 0x0017 => { Name => 'Reserved', Format => 'Unknown', }, 0x001a => { Name => 'RGBFgCol', Description => 'Foreground Color', Format => 'RGBColor', }, 0x001b => { Name => 'RGBBkCol', Description => 'Background Color', Format => 'RGBColor', }, 0x001c => { Name => 'HiliteMode', Description => 'Highlight Mode Flag', Format => 'null', }, 0x001d => { Name => 'HiliteColor', Description => 'Highlight Color', Format => 'RGBColor', }, 0x001e => { Name => 'DefHilite', Description => 'Use Default Highlight Color', Format => 'null', }, 0x001f => { Name => 'OpColor', Format => 'RGBColor', }, 0x0020 => { Name => 'Line', Format => 'Rect', }, 0x0021 => { Name => 'LineFrom', Format => 'Point', }, 0x0022 => { Name => 'ShortLine', Format => 'ShortLine', }, 0x0023 => { Name => 'ShortLineFrom', Format => 'int8u[2]', }, 0x0024 => { Name => 'Reserved', Format => 'Int16Data', }, 0x0028 => { Name => 'LongText', Format => 'PointText', }, 0x0029 => { Name => 'DHText', Format => 'Int8uText', }, 0x002a => { Name => 'DVText', Format => 'Int8uText', }, 0x002b => { Name => 'DHDVText', Format => 'Int8u2Text', }, 0x002c => { Name => 'FontName', Format => 'FontName', }, 0x002d => { Name => 'LineJustify', Format => 'int8u[10]', }, 0x002e => { Name => 'GlyphState', Format => 'int8u[8]', }, 0x002f => { Name => 'Reserved', Format => 'Int16Data', }, 0x0030 => { Name => 'FrameRect', Format => 'Rect', }, 0x0031 => { Name => 'PaintRect', Format => 'Rect', }, 0x0032 => { Name => 'EraseRect', Format => 'Rect', }, 0x0033 => { Name => 'InvertRect', Format => 'Rect', }, 0x0034 => { Name => 'FillRect', Format => 'Rect', }, 0x0035 => { Name => 'Reserved', Format => 'Rect', }, 0x0038 => { Name => 'FrameSameRect', Format => 'null', }, 0x0039 => { Name => 'PaintSameRect', Format => 'null', }, 0x003a => { Name => 'EraseSameRect', Format => 'null', }, 0x003b => { Name => 'InvertSameRect', Format => 'null', }, 0x003c => { Name => 'FillSameRect', Format => 'null', }, 0x003d => { Name => 'Reserved', Format => 'null', }, 0x0040 => { Name => 'FrameRRect', Format => 'Rect', }, 0x0041 => { Name => 'PaintRRect', Format => 'Rect', }, 0x0042 => { Name => 'EraseRRect', Format => 'Rect', }, 0x0043 => { Name => 'InvertRRect', Format => 'Rect', }, 0x0044 => { Name => 'FillRRect', Format => 'Rect', }, 0x0045 => { Name => 'Reserved', Format => 'Rect', }, 0x0048 => { Name => 'FrameSameRRect', Format => 'null', }, 0x0049 => { Name => 'PaintSameRRect', Format => 'null', }, 0x004a => { Name => 'EraseSameRRect', Format => 'null', }, 0x004b => { Name => 'InvertSameRRect', Format => 'null', }, 0x004c => { Name => 'FillSameRRect', Format => 'null', }, 0x004d => { Name => 'Reserved', Format => 'null', }, 0x0050 => { Name => 'FrameOval', Format => 'Rect', }, 0x0051 => { Name => 'PaintOval', Format => 'Rect', }, 0x0052 => { Name => 'EraseOval', Format => 'Rect', }, 0x0053 => { Name => 'InvertOval', Format => 'Rect', }, 0x0054 => { Name => 'FillOval', Format => 'Rect', }, 0x0055 => { Name => 'Reserved', Format => 'Rect', }, 0x0058 => { Name => 'FrameSameOval', Format => 'null', }, 0x0059 => { Name => 'PaintSameOval', Format => 'null', }, 0x005a => { Name => 'EraseSameOval', Format => 'null', }, 0x005b => { Name => 'InvertSameOval', Format => 'null', }, 0x005c => { Name => 'FillSameOval', Format => 'null', }, 0x005d => { Name => 'Reserved', Format => 'null', }, 0x0060 => { Name => 'FrameArc', Format => 'Arc', }, 0x0061 => { Name => 'PaintArc', Format => 'Arc', }, 0x0062 => { Name => 'EraseArc', Format => 'Arc', }, 0x0063 => { Name => 'InvertArc', Format => 'Arc', }, 0x0064 => { Name => 'FillArc', Format => 'Arc', }, 0x0065 => { Name => 'Reserved', Format => 'Arc', }, 0x0068 => { Name => 'FrameSameArc', Format => 'Point', }, 0x0069 => { Name => 'PaintSameArc', Format => 'Point', }, 0x006a => { Name => 'EraseSameArc', Format => 'Point', }, 0x006b => { Name => 'InvertSameArc', Format => 'Point', }, 0x006c => { Name => 'FillSameArc', Format => 'Point', }, 0x006d => { Name => 'Reserved', Format => 'int32u', }, 0x0070 => { Name => 'FramePoly', Format => 'Polygon', }, 0x0071 => { Name => 'PaintPoly', Format => 'Polygon', }, 0x0072 => { Name => 'ErasePoly', Format => 'Polygon', }, 0x0073 => { Name => 'InvertPoly', Format => 'Polygon', }, 0x0074 => { Name => 'FillPoly', Format => 'Polygon', }, 0x0075 => { Name => 'Reserved', Format => 'Polygon', }, 0x0078 => { Name => 'FrameSamePoly', Format => 'null', }, 0x0079 => { Name => 'PaintSamePoly', Format => 'null', }, 0x007a => { Name => 'EraseSamePoly', Format => 'null', }, 0x007b => { Name => 'InvertSamePoly', Format => 'null', }, 0x007c => { Name => 'FillSamePoly', Format => 'null', }, 0x007d => { Name => 'Reserved', Format => 'null', }, 0x0080 => { Name => 'FrameRgn', Format => 'Rgn', }, 0x0081 => { Name => 'PaintRgn', Format => 'Rgn', }, 0x0082 => { Name => 'EraseRgn', Format => 'Rgn', }, 0x0083 => { Name => 'InvertRgn', Format => 'Rgn', }, 0x0084 => { Name => 'FillRgn', Format => 'Rgn', }, 0x0085 => { Name => 'Reserved', Format => 'Rgn', }, 0x0088 => { Name => 'FrameSameRgn', Format => 'null', }, 0x0089 => { Name => 'PaintSameRgn', Format => 'null', }, 0x008a => { Name => 'EraseSameRgn', Format => 'null', }, 0x008b => { Name => 'InvertSameRgn', Format => 'null', }, 0x008c => { Name => 'FillSameRgn', Format => 'null', }, 0x008d => { Name => 'Reserved', Format => 'null', }, 0x0090 => { Name => 'BitsRect', Description => 'CopyBits with Clipped Rectangle', Format => 'BitsRect#', # (version-dependent format) }, 0x0091 => { Name => 'BitsRgn', Description => 'CopyBits with Clipped Region', Format => 'BitsRgn#', # (version-dependent format) }, 0x0092 => { Name => 'Reserved', Format => 'Int16Data', }, 0x0098 => { Name => 'PackBitsRect', Description => 'Packed CopyBits with Clipped Rectangle', Format => 'BitsRect#', # (version-dependent format) }, 0x0099 => { Name => 'PackBitsRgn', Description => 'Packed CopyBits with Clipped Region', Format => 'BitsRgn#', # (version-dependent format) }, 0x009a => { Name => 'DirectBitsRect', Format => 'DirectBitsRect', }, 0x009b => { Name => 'DirectBitsRgn', Format => 'DirectBitsRgn', }, 0x009c => { Name => 'Reserved', Format => 'Int16Data', }, 0x009d => { Name => 'Reserved', Format => 'Int16Data', }, 0x009e => { Name => 'Reserved', Format => 'Int16Data', }, 0x009f => { Name => 'Reserved', Format => 'Int16Data', }, 0x00a0 => { Name => 'ShortComment', Format => 'int16u', }, 0x00a1 => [ # this list for documentation only [not currently extracted] { # (not actually a full Photohop IRB record it appears, but it does start # with '8BIM', and does contain resolution information at offset 0x0a) Name => 'LongComment', # kind = 498 Format => 'LongComment', SubDirectory => { TagTable => 'Image::ExifTool::Photoshop::Main' }, }, { Name => 'LongComment', # kind = 224 Format => 'LongComment', SubDirectory => { TagTable => 'Image::ExifTool::ICC_Profile::Main', Start => '$valuePtr + 4', }, }, ], 0x00a2 => { Name => 'Reserved', Format => 'Int16Data', }, 0x00b0 => { Name => 'Reserved', Format => 'null', }, 0x00d0 => { Name => 'Reserved', Format => 'Int32uData', }, 0x00ff => { Name => 'OpEndPic', Description => 'End of picture', Format => 'null', # 2 for version 2!? }, 0x0100 => { Name => 'Reserved', Format => 'int16u', }, 0x0200 => { Name => 'Reserved', Format => 'int32u', }, 0x02ff => { Name => 'Version', Description => 'Version number of picture', Format => 'int16u', }, 0x0300 => { Name => 'Reserved', Format => 'int16u', }, 0x0bff => { Name => 'Reserved', Format => 'int8u[22]', }, 0x0c00 => { Name => 'HeaderOp', Format => 'int16u[12]', }, 0x0c01 => { Name => 'Reserved', Format => 'int8u[24]', }, 0x7f00 => { Name => 'Reserved', Format => 'int8u[254]', }, 0x8000 => { Name => 'Reserved', Format => 'null', }, 0x8100 => { Name => 'Reserved', Format => 'Int32uData', }, 0x8200 => { Name => 'CompressedQuickTime', Format => 'CompressedQuickTime', }, 0x8201 => { Name => 'UncompressedQuickTime', Format => 'Int32uData', }, 0xffff => { Name => 'Reserved', Format => 'Int32uData', }, ); # picture comment 'kind' codes # http://developer.apple.com/technotes/qd/qd_10.html my %commentKind = ( 150 => 'TextBegin', 151 => 'TextEnd', 152 => 'StringBegin', 153 => 'StringEnd', 154 => 'TextCenter', 155 => 'LineLayoutOff', 156 => 'LineLayoutOn', 157 => 'ClientLineLayout', 160 => 'PolyBegin', 161 => 'PolyEnd', 163 => 'PolyIgnore', 164 => 'PolySmooth', 165 => 'PolyClose', 180 => 'DashedLine', 181 => 'DashedStop', 182 => 'SetLineWidth', 190 => 'PostScriptBegin', 191 => 'PostScriptEnd', 192 => 'PostScriptHandle', 193 => 'PostScriptFile', 194 => 'TextIsPostScript', 195 => 'ResourcePS', 196 => 'PSBeginNoSave', 197 => 'SetGrayLevel', 200 => 'RotateBegin', 201 => 'RotateEnd', 202 => 'RotateCenter', 210 => 'FormsPrinting', 211 => 'EndFormsPrinting', 224 => '<ICC Profile>', 498 => '<Photoshop Data>', 1000 => 'BitMapThinningOff', 1001 => 'BitMapThinningOn', ); #------------------------------------------------------------------------------ # Get PixData data # Inputs: 0) reference to PixMap, 1) RAF reference # Returns: reference to PixData or undef on error sub GetPixData($$) { my ($pixMap, $raf) = @_; my $packType = $pixMap->{packType}; my $rowBytes = $pixMap->{rowBytes} & 0x3fff; # remove flags bits my $height = $pixMap->{bounds}->{botRight}->{v} - $pixMap->{bounds}->{topLeft}->{v}; my ($data, $size, $buff, $i); if ($packType == 1 or $rowBytes < 8) { # unpacked data $size = $rowBytes * $height; return undef unless $raf->Read($data, $size) == $size; } elsif ($packType == 2) { # pad byte dropped $size = int($rowBytes * $height * 3 / 4 + 0.5); return undef unless $raf->Read($data, $size) == $size; } else { $data = ''; for ($i=0; $i<$height; ++$i) { if ($rowBytes > 250) { $raf->Read($buff,2) == 2 or return undef; $size = unpack('n',$buff); } else { $raf->Read($buff,1) == 1 or return undef; $size = unpack('C',$buff); } $data .= $buff; $raf->Read($buff,$size) == $size or return undef; $data .= $buff; } } return \$data; } #------------------------------------------------------------------------------ # Read value from PICT file # Inputs: 0) RAF reference, 1) tag, 2) format, 3) optional count # Returns: value, reference to structure hash, or undef on error sub ReadPictValue($$$;$) { my ($raf, $tag, $format, $count) = @_; return undef unless $format; unless (defined $count) { if ($format =~ /(.+)\[(.+)\]/s) { $format = $1; $count = $2; } else { $count = 1; # count undefined: assume 1 } } my $cntStr = ($count == 1) ? '' : "[$count]"; # no size if count is 0 my $size = $count ? Image::ExifTool::FormatSize($format) : 0; if (defined $size or $format eq 'null') { my $val; if ($size) { my $buff; $size *= $count; $raf->Read($buff, $size) == $size or return undef; $val = ReadValue(\$buff, 0, $format, $count, $size); } else { $val = ''; } if ($verbose) { print $out "${indent}$tag ($format$cntStr)"; if ($size) { if (not defined $val) { print $out " = <undef>\n"; } elsif ($format eq 'binary') { print $out " = <binary data>\n"; if ($verbose > 2) { my %parms = ( Out => $out ); $parms{MaxLen} = 96 if $verbose < 4; Image::ExifTool::HexDump(\$val, undef, %parms); } } else { print $out " = $val\n"; } } else { print $out "\n"; } } return \$val if $format eq 'binary' and defined $val; return $val; } $verbose and print $out "${indent}$tag ($format$cntStr):\n"; my $struct = $structs{$format} or return undef; my ($c, @vals); for ($c=0; $c<$count; ++$c) { my (%val, $i); for ($i=0; ; $i+=2) { my $tag = $$struct[$i] or last; my $fmt = $$struct[$i+1]; my ($cnt, $val); $indent .= ' '; if (ref $fmt) { $val = eval $$fmt; $@ and warn $@; if ($verbose and defined $val) { printf $out "${indent}$tag (binary[%d]) = <binary data>\n",length($$val); if ($verbose > 2) { my %parms = ( Out => $out ); $parms{MaxLen} = 96 if $verbose < 4; Image::ExifTool::HexDump($val, undef, %parms); } } } elsif ($fmt =~ /(.+)\[(.+)\]/s) { $fmt = $1; $cnt = eval $2; $@ and warn $@; $val = ReadPictValue($raf, $tag, $fmt, $cnt); } else { $val = ReadPictValue($raf, $tag, $fmt); } $indent = substr($indent, 2); return undef unless defined $val; $val{$tag} = $val; } return \%val if $count == 1; push @vals, \%val; } return \@vals; } #------------------------------------------------------------------------------ # Extract meta information from a PICT image # Inputs: 0) ExifTool object reference, 1) dirInfo reference # Returns: 1 on success, 0 if this wasn't a valid PICT image sub ProcessPICT($$) { my ($exifTool, $dirInfo) = @_; my $raf = $$dirInfo{RAF}; $verbose = $exifTool->Options('Verbose'); $out = $exifTool->Options('TextOut'); $indent = ''; my ($buff, $tried, @hdr, $op, $hRes, $vRes); # recognize both PICT files and PICT resources (PICT files have a # 512-byte header that we ignore, but PICT resources do not) for (;;) { $raf->Read($buff, 12) == 12 or return 0; @hdr = unpack('x2n5', $buff); $op = pop @hdr; # check for PICT version 1 format if ($op eq 0x1101) { $vers = 1; undef $extended; last; } # check for PICT version 2 format if ($op eq 0x0011) { $raf->Read($buff, 28) == 28 or return 0; if ($buff =~ /^\x02\xff\x0c\x00\xff\xff/) { $vers = 2; undef $extended; last; } if ($buff =~ /^\x02\xff\x0c\x00\xff\xfe/) { $vers = 2; $extended = 1; ($hRes, $vRes) = unpack('x8N2', $buff); last; } } return 0 if $tried; $tried = 1; $raf->Seek(512, 0) or return 0; } # make the bounding rect signed foreach (@hdr) { $_ >= 0x8000 and $_ -= 0x10000; } my $w = $hdr[3] - $hdr[1]; my $h = $hdr[2] - $hdr[0]; return 0 unless $w > 0 and $h > 0; SetByteOrder('MM'); if ($extended) { # extended version 2 pictures contain resolution information # and image bounds are in 72-dpi equivalent units $hRes = GetFixed32s(\$buff, 8); $vRes = GetFixed32s(\$buff, 12); return 0 unless $hRes and $vRes; $w = int($w * $hRes / 72 + 0.5); $h = int($h * $vRes / 72 + 0.5); } $exifTool->SetFileType(); $exifTool->FoundTag('ImageWidth', $w); $exifTool->FoundTag('ImageHeight', $h); $exifTool->FoundTag('XResolution', $hRes) if $hRes; $exifTool->FoundTag('YResolution', $vRes) if $vRes; # don't extract image opcodes unless verbose return 1 unless $verbose or $exifTool->Options('Unknown'); $verbose and printf $out "PICT version $vers%s\n", $extended ? ' extended' : ''; my $tagTablePtr = GetTagTable('Image::ExifTool::PICT::Main'); my $success; for (;;) { if ($vers == 1) { $raf->Read($buff, 1) == 1 or last; $op = ord($buff); } else { # must start version 2 opcode on an even byte $raf->Read($buff, 1) if $raf->Tell() & 0x01; $raf->Read($buff, 2) == 2 or last; $op = unpack('n', $buff); } my $tagInfo = $exifTool->GetTagInfo($tagTablePtr, $op); unless ($tagInfo) { my $i; # search for reserved tag info for ($i=0; $i<scalar(@reserved); $i+=2) { next unless $op >= $reserved[$i]; last if $op > $reserved[$i+1]; $tagInfo = $exifTool->GetTagInfo($tagTablePtr, $reserved[$i]); last; } last unless $tagInfo; } if ($op eq 0xff) { $verbose and print $out "End of picture\n"; $success = 1; last; } my $format = $$tagInfo{Format}; unless ($format) { $exifTool->Warn("Missing format for $$tagInfo{Name}"); last; } # replace version number for version-dependent formats $format =~ s/#$/$vers/; my $wid = $vers * 2; $verbose and printf $out "Tag 0x%.${wid}x, ", $op; my $val = ReadPictValue($raf, $$tagInfo{Name}, $format); unless (defined $val) { $exifTool->Warn("Error reading $$tagInfo{Name} information"); last; } if (ref $val eq 'HASH') { # extract JPEG image from CompressedQuickTime imageData if ($$tagInfo{Name} eq 'CompressedQuickTime' and ref $val->{imageDescr} eq 'HASH' and $val->{imageDescr}->{compressor} and $val->{imageDescr}->{compressor} eq 'Photo - JPEG' and ref $val->{imageData} eq 'SCALAR' and $exifTool->ValidateImage($val->{imageData}, 'PreviewImage')) { $exifTool->FoundTag('PreviewImage', $val->{imageData}); } } else { # $exifTool->FoundTag($tagInfo, $val); } } $success or $exifTool->Warn('End of picture not found'); return 1; } 1; # end __END__ =head1 NAME Image::ExifTool::PICT - Read PICT meta information =head1 SYNOPSIS This module is used by Image::ExifTool =head1 DESCRIPTION This module contains routines required by Image::ExifTool to read PICT (Apple Picture) images. =head1 NOTES Extraction of PICT opcodes is experimental, and is only enabled with the Verbose or the Unknown option. =head1 AUTHOR Copyright 2003-2009, Phil Harvey (phil at owl.phy.queensu.ca) This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 REFERENCES =over 4 =item L<http://developer.apple.com/documentation/mac/QuickDraw/QuickDraw-2.html> =item L<http://developer.apple.com/documentation/QuickTime/INMAC/QT/iqImageCompMgr.a.htm> =back =head1 SEE ALSO L<Image::ExifTool::TagNames/PICT Tags>, L<Image::ExifTool(3pm)|Image::ExifTool> =cut
opf-attic/ref
tools/fits/0.5.0/tools/exiftool/perl/lib/Image/ExifTool/PICT.pm
Perl
apache-2.0
34,147
=head1 Artistic License 2.0 Notes The heart of the Artistic license is the idea that artists, people who create things, should be able to have ongoing artistic involvement in their work. The goal of the Artistic 2.0 revision is to make the terms of the original Artistic License clearer and more readable. In some cases we expanded it to make it more legally specific. In some cases we made the language more general so the license may fit better with past and future changes in technology. Legal documents can be considered as just another form of code. You'll see a lot of spaghetti legal code out there, lengthy and obtuse, but it doesn't have to be like that. Readability and maintainability are just as important in legal code as they are in software. But, because legal documents are code, our drafting choices are based on a need to capture a particular legal meaning. These notes are based on comments and questions that came up as we worked on this revision. We hope they will help you understand how to use the new license. To make the comments easier to follow, we use Perl as an example in these notes. =head3 "Original License": We found ourselves repeating "the version of the Artistic License that ships with the Standard Version" far too many times through the license, so we decided to define it in one place. The "original license" identifies the license that the developer used to distribute their code. It also lets the users know that TPF might update the license in the future, and that developers who have distributed under one version of the license can always upgrade to another. This isn't an automatic upgrade. If you distribute a package under the Artistic License 2.0, and want to take advantage of "bug fixes" in version 2.1, you have to include the new version of the license in the package. =head3 Section 1: This section applies to using Perl yourself "as is", or changing it but only using the changed version yourself or inside your organization. The rest of the license does not come into play unless you want to make Perl available to others, in a standard or modified version. =head3 Section 2: You can redistribute unchanged versions of the Perl source code. You can't charge a licensing fee for it, but you can charge for distributing it or for providing support. =head3 Section 3: Fixing a few bugs, tweaking the code to run on your operating system, or applying a security patch from the development mailing list doesn't mean you've created a "Modified Version". =head3 Section 4: You have a few different options if you want to change the code and redistribute it. Whatever option you choose, you must let people know that you've changed the code. In general, we expect that you would do this using a file in the top-level of the distribution noting what's changed and that you will update the documentation anywhere your code works differently from what the documentation says (you would probably want to do this anyway, so the documentation isn't misleading). However, there are other ways to meet the requirements. For instance, you might include a comment in each changed file, or beside each change in the code. Under Section 4(a), you can make any changes you want if you contribute them back under the Artistic License. Under Section 4(b), you can release a proprietary version of the Perl source code, but if you do, don't pretend your code is the real Perl. Don't call it Perl, and don't make it so your users can't use the real Perl on the same machine. This requirement goes back to the idea of artistic control. Under Section 4(c)(i), you can make any changes you want if you release your changes under the Artistic License. Section 4(c)(ii) is what we call the "relicensing" clause. Perl 6 and Parrot won't be dual licensed with the GPL, unlike Perl 5. Since they won't be dual licensed, if you want to use Perl 6 or Parrot under a GPL license, you will doing so under 4(c)(ii). Several other open source and free software licenses also qualify under 4(c)(ii), including the LGPL, MPL, and the Apache license. Note that these are only what have become known as "copyleft" licenses: "freely available" means both free as in speech and free as in beer. =head3 Section 5: If you don't change the code, you can ship it out as compiled code without the source code. Just tell people how to get the source code. =head3 Section 6: When it comes to Modified Versions, whether you're shipping compiled code or source code, the requirements are the same. =head3 Section 7: Example: you can ship Perl on a CD along with other software, or include it in your distribution of Linux. =head3 Section 8: You're totally free to embed Perl inside your software in a way that doesn't allow users to access Perl. On the other hand, if you embed it and users can nevertheless do things like running Perl scripts, then you really are distributing Perl and need make sure that your distribution fits one of the use cases in (1)-(7). =head3 Section 9: When you write code that just runs on Perl, that fact alone does not make the code subject to the Artistic License. It's your code. (This seems pretty obvious, but it's important to say it.) =head3 Section 10: The license offers you some rights. In order to obtain those rights, you need to accept the license. You can reject the license, but if you do, the rights aren't granted to you. =head3 Section 11: You're responsible for your own actions. If you get a copy of Perl from someone who broke the terms of the Artistic License, that doesn't get you off the hookE<mdash>you're still required to comply with the license yourself. There are plenty of places where you can get legal copies of Perl, so it should be pretty easy to get back into compliance. =head3 Section 12: Just being explicit that the license doesn't grant you trademark rights, or rights related to trademark rights. =head3 Section 13: We're not particularly fond of patents, but they're part of the world we live in. So, with a goal of minimizing the likelihood of patent infringement claims, we grant you a patent license. In addition, under our contribution process, each Contributor makes a patent grant for their Contributions directly to you as a User. Both patent license clauses contain a provision that terminates the license(s) of anyone who files a lawsuit claiming that a Package infringes any patent. The termination only applies to Packages that are claimed to be infringements. =head3 Section 14: Disclaimers of warranties and damages, like those you find in other open source and software licenses. =head2 Frequently Asked Questions =head3 What are the major differences between the Artistic 1.0 and Artistic 2.0? Overall, the terms of the Artistic 2.0 are the same as the Artistic 1, though the language has been polished and reorganized to be more readable and more legally precise. The significant additions are sections 4(c)(ii) and 13. =head3 Can I include code from a project licensed under the GPL in a project licensed under the Artistic license? No, you can't include code from a GPL (version 1, 2, or 3) project in an Artistic licensed package. Because the Artistic License (1.0 or 2.0) is a less restrictive license than GPL (1, 2, or 3). That is, if you distributed GPL'd code under the Artistic License, you would be giving away rights that the original author never gave you. The most obvious example of this is the fact that the Artistic License allows proprietary versions, but the GPL does not. This doesn't prevent you from linking to GPL libraries. It only prevents you from absorbing GPL code into a package and distributing that GPL code under an Artistic License. =head3 Can I include code from a project licensed under the Artistic License version 1 in a project licensed under the Artistic License version 2? Yes. The terms of Artistic 2.0 are the same as Artistic 1.0, aside from the added patent clause and relicensing clause. That means Artistic 2.0 is a more restrictive license than Artistic 1.0 (it gives away fewer rights), so any Artistic 1.0 code can be distributed as Artistic 2.0. =cut
autarch/perlweb
docs/foundation/legal/licenses/artistic-2_0-notes.pod
Perl
apache-2.0
8,153
#!/usr/bin/perl require "/perfstat/build/serialize/create/ServiceConfig.pl"; #add create new service $service = Service->new( RRA => "RRA:AVERAGE:0.5:1:288 RRA:AVERAGE:0.5:7:288 RRA:AVERAGE:0.5:30:288 RRA:AVERAGE:0.5:365:288", rrdStep => "300", serviceName => "procs", ); #add metric 0 $obj = Metric->new( rrdIndex => 0, metricName => "totalProcs", friendlyName => "Total Processes", status => "nostatus", rrdDST => GAUGE, rrdHeartbeat => 600, rrdMin => 0, rrdMax => U, hasEvents => 1, warnThreshold => 500, critThreshold => 1000, thresholdUnit => "Number", lowThreshold => "0", highThreshold => "5000", ); $service->addMetric($obj); #add graph 0 $obj = Graph->new( name => "procsActivity", title => "Process Activity", comment => "", imageFormat => "png", width => "500", height => "120", verticalLabel => "Number", upperLimit => "", lowerLimit => "0", rigid => "", base => "1000", unitsExponent => "0", noMinorGrids => "", stepValue => "", gprintFormat => "%8.2lf", metricIndexHash => {}, metricArray => [], ); $obj2 = GraphMetric->new( name => "totalProcs", color => "#000080", lineType => "LINE2", gprintArray => [qw{AVERAGE LAST}], cDefinition => "", ); $obj->addGraphMetric("totalProcs", $obj2); $service->addGraph("procsActivity", $obj); #print out this service print ("Ref: ref($service)\n"); $serviceName = $service->getServiceName(); $RRA = $service->getRRA(); $rrdStep = $service->getRRDStep(); $lastUpdate = $service->getLastUpdate(); print ("serviceName: $serviceName\n"); print ("RRA: $RRA\n"); print ("rrdStep: $rrdStep\n"); print ("Last Update: $lastUpdate\n"); #print out this services metrics $arrayLength = $service->getMetricArrayLength(); print ("metric Array Length = $arrayLength\n\n"); for ($counter=0; $counter < $arrayLength; $counter++) { $metricObject = $service->{metricArray}->[$counter]; $rrdIndex = $metricObject->getRRDIndex(); $rrdDST = $metricObject->getRRDDST(); $rrdHeartbeat = $metricObject->getRRDHeartbeat(); $rrdMin = $metricObject->getRRDMin(); $rrdMax = $metricObject->getRRDMax(); $metricName = $metricObject->getMetricName(); $friendlyName = $metricObject->getFriendlyName(); $status = $metricObject->getStatus(); $hasEvents = $metricObject->getHasEvents(); $warnThreshold = $metricObject->getWarnThreshold(); $critThreshold = $metricObject->getCritThreshold(); $thresholdUnit = $metricObject->getThresholdUnit(); $lowThreshold = $metricObject->getLowThreshold(); $highThreshold = $metricObject->getHighThreshold(); print ("rrdIndex: $rrdIndex\n"); print ("rrdDST: $rrdDST\n"); print ("rrdHeartbeat: $rrdHeartbeat\n"); print ("rrdMin: $rrdMin\n"); print ("rrdMax: $rrdMax\n"); print ("metricName: $metricName\n"); print ("friendlyName: $friendlyName\n"); print ("status: $status\n"); print ("hasEvents: $hasEvents\n"); print ("warnThreshold: $warnThreshold\n"); print ("critThreshold: $critThreshold\n"); print ("threshUnit: $thresholdUnit\n"); print ("lowThreshold: $lowThreshold\n"); print ("highThreshold: $highThreshold\n\n"); } #print out this services graphs $graph = $service->{graphHash}; foreach my $key (keys %{$graph}) { $graphObject = $service->{graphHash}->{$key}; $name = $graphObject->getName(); $title = $graphObject->getTitle(); $comment = $graphObject->getComment(); $imageFormat = $graphObject->getImageFormat(); $width = $graphObject->getWidth(); $height = $graphObject->getHeight(); $verticalLabel = $graphObject->getVerticalLabel(); $upperLimit = $graphObject->getUpperLimit(); $lowerLimit = $graphObject->getLowerLimit(); $rigid = $graphObject->getRigid(); $base = $graphObject->getBase(); $unitsExponent = $graphObject->getUnitsExponent(); $noMinorGrids = $graphObject->getNoMinorGrids(); $stepValue = $graphObject->getStepValue(); $gprintFormat = $graphObject->getGprintFormat(); print ("name: $name\n"); print ("title: $title\n"); print ("comment: $comment\n"); print ("image format: $imageFormat\n"); print ("width: $width\n"); print ("height: $height\n"); print ("vertical label: $verticalLabel\n"); print ("upper limit: $upperLimit\n"); print ("lower limit: $lowerLimit\n"); print ("rigid: $rigid\n"); print ("base: $base\n"); print ("units exponent: $unitsExponent\n"); print ("no minor grids: $noMinorGrids\n"); print ("step value: $stepValue\n"); print ("gprint format: $gprintFormat\n"); print "\n"; # Via MetricArray foreach my $key (@{$graphObject->{metricArray}}) { my $metricName = $key->getName(); my $color = $key->{color}; my $lineType = $key->getLineType(); my $cDefinition = $key->getCdefinition(); print "Graph Metric Name: $metricName\n"; print "Color: $color\n"; print "Line Type: $lineType\n"; print "GPRINT : @{$key->{gprintArray}}\n"; print "CDEF: $cDefinition\n"; print "\n"; } } #Store the service $service->store("$perfhome/etc/configs/Linux/$service->{serviceName}.ser") or die("can't store $service->{serviceName}.ser?\n");
ktenzer/perfstat
misc/serialize/create/Linux/63004/procs.pl
Perl
apache-2.0
6,448
=pod =head1 NAME DERlib - internal OpenSSL DER library =head1 DESCRIPTION OpenSSL contains an internal small DER reading and writing library, as an alternative to the publicly known i2d and d2i functions. It's solely constituted of functions that work as building blocks to create more similar functions to encode and decode larger structures. All these functions have similar function signatures (C<something> will vary depending on what the function will encode): int DER_w_something(WPACKET *pkt, int tag, ...); =begin comment When readers are added, add this: int DER_r_something(PACKET *pkt, int tag, ...); =end comment I<pkt> is the packet context used, and I<tag> should be the context-specific tag value of the element being handled, or -1 if there is no tag number for that element (you may use the convenience macro B<DER_NO_CONTEXT> instead of -1). Any argument following is the C variable that's being encoded or decoded. =head2 DER writers / encoders DER writers are based in L<WPACKET(3)>, a generic packet writing library, so before using any of them, I<pkt> must be initialized using L<WPACKET_init_der(3)> or L<WPACKET_init_null_der(3)> DER writers must be used in reverse order, except for the wrapping functions that implement a constructed element. The latter are easily recognised by their function name including the words C<begin> and C<end>. As an example, we can look at the DSA signature structure, which is defined like this in ASN.1 terms: -- Copied from RFC 3279, section 2.2.2 Dss-Sig-Value ::= SEQUENCE { r INTEGER, s INTEGER } With the DER library, this is the corresponding code, given two OpenSSL B<BIGNUM>s I<r> and I<s>: int ok = ossl_DER_w_begin_sequence(pkt, -1) && ossl_DER_w_bn(pkg, -1, s) && ossl_DER_w_bn(pkg, -1, r) && ossl_DER_w_end_sequence(pkt, -1); As an example of the use of I<tag>, an ASN.1 element like this: v [1] INTEGER OPTIONAL Would be encoded like this: ossl_DER_w_bn(pkt, 1, v) =begin comment =head2 DER readers / decoders TBA =end comment =head1 EXAMPLES A more complex example, encoding the AlgorithmIdentifier with RSASSA-PSS values. As a reminder, the AlgorithmIdentifier is specified like this: -- From RFC 3280, section 4.1.1.2 AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER, parameters ANY DEFINED BY algorithm OPTIONAL } And the RSASSA-PSS OID and parameters are specified like this: -- From RFC 3279, section 3.1 id-RSASSA-PSS OBJECT IDENTIFIER ::= { pkcs-1 10 } RSASSA-PSS-params ::= SEQUENCE { hashAlgorithm [0] HashAlgorithm DEFAULT sha1Identifier, maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT mgf1SHA1Identifier, saltLength [2] INTEGER DEFAULT 20, trailerField [3] INTEGER DEFAULT 1 } The value we want to encode, written in ASN.1 syntax: { algorithm id-RSASSA-PSS, parameters { hashAlgorithm sha256Identifier, maskGenAlgorithm mgf1SHA256Identifier, saltLength 20 -- unnecessarily explicit } } Assuming that we have precompiled constants for C<id-RSASSA-PSS>, C<sha256Identifier> and C<mgf1SHA256Identifier>, the DER writing code looks as follows. This is a complete function to write that specific value: int DER_w_AlgorithmIdentifier_RSASSA_PSS_special(WPACKET *pkt, int tag, RSA *rsa) { return ossl_DER_w_begin_sequence(pkt, tag) && (ossl_DER_w_begin_sequence(pkt, DER_NO_CONTEXT) && ossl_DER_w_ulong(pkt, 2, 20) && ossl_DER_w_precompiled(pkt, 1, der_mgf1SHA256Identifier, sizeof(der_mgf1SHA256Identifier)) && ossl_DER_w_precompiled(pkt, 0, der_sha256Identifier, sizeof(der_sha256Identifier)) && ossl_DER_w_end_sequence(pkt, DER_NO_CONTEXT)) && ossl_DER_w_precompiled(pkt, DER_NO_CONTEXT, der_id_RSASSA_PSS, sizeof(der_id_RSASSA_PSS)) && ossl_DER_w_end_sequence(pkt, tag); } =head1 SEE ALSO L<ossl_DER_w_bn(3)>, L<ossl_DER_w_begin_sequence(3)>, L<ossl_DER_w_precompiled(3)> =head1 COPYRIGHT Copyright 2020 The OpenSSL Project Authors. All Rights Reserved. Licensed under the Apache License 2.0 (the "License"). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at L<https://www.openssl.org/source/license.html>. =cut
jens-maus/amissl
openssl/doc/internal/man7/DERlib.pod
Perl
bsd-3-clause
5,007
#!/usr/bin/perl # 'Copyright 1994, Animorphic Systems. $Revision: 1.3 $ sub dirname { local($name) = @_; $name =~ s/\\/\//g; $name =~ tr/A-Z/a-z/; return $name; } $Delta = do dirname($ENV{'DeltaDir'}); $Directory = "$Delta/vm/prims"; opendir(DIR,$Directory) || die "Can't open vm/prims!\n"; @filenames = readdir(DIR); closedir(DIR); sub generate { local($filename) = @_; local($inside) = 0; open(FILE,"$Directory/$filename") || die "Can't open $filename"; for (<FILE>) { chop; # remove the newline if ($inside) { if (/^[ \t]*\/\/%/) { printf "!\n"; $inside = 0; } else { if (/^[ \t]*\/\/(.*)/) { printf "%s\n", $1; } else { die "Wrong format inside primitive definition"; } } } else { if (/^[ \t]*\/\/%prim/) { $inside = 1; } } } if ($inside) { die "Primitive definition not completed"; } close(FILE) } for (@filenames) { do generate($_) if $_ =~ /[a-zA-Z]+_prims.hpp$/ } printf "!\n"
talksmall/Strongtalk
tools/primDefFilter.pl
Perl
bsd-3-clause
1,053
#------------------------------------------------------------------------------ # File: WriteIPTC.pl # # Description: Write IPTC meta information # # Revisions: 12/15/2004 - P. Harvey Created #------------------------------------------------------------------------------ package Image::ExifTool::IPTC; use strict; # mandatory IPTC tags for each record my %mandatory = ( 1 => { 0 => 4, # EnvelopeRecordVersion }, 2 => { 0 => 4, # ApplicationRecordVersion }, 3 => { 0 => 4, # NewsPhotoVersion }, ); # manufacturer strings for IPTCPictureNumber my %manufacturer = ( 1 => 'Associated Press, USA', 2 => 'Eastman Kodak Co, USA', 3 => 'Hasselblad Electronic Imaging, Sweden', 4 => 'Tecnavia SA, Switzerland', 5 => 'Nikon Corporation, Japan', 6 => 'Coatsworth Communications Inc, Canada', 7 => 'Agence France Presse, France', 8 => 'T/One Inc, USA', 9 => 'Associated Newspapers, UK', 10 => 'Reuters London', 11 => 'Sandia Imaging Systems Inc, USA', 12 => 'Visualize, Spain', ); my %iptcCharsetInv = ( 'UTF8' => "\x1b%G", 'UTF-8' => "\x1b%G" ); # ISO 2022 Character Coding Notes # ------------------------------- # Character set designation: (0x1b I F, or 0x1b I I F) # Initial character 0x1b (ESC) # Intermediate character I: # 0x28 ('(') - G0, 94 chars # 0x29 (')') - G1, 94 chars # 0x2a ('*') - G2, 94 chars # 0x2b ('+') - G3, 94 chars # 0x2c (',') - G1, 96 chars # 0x2d ('-') - G2, 96 chars # 0x2e ('.') - G3, 96 chars # 0x24 I ('$I') - multiple byte graphic sets (I from above) # I 0x20 ('I ') - dynamically redefinable character sets # Final character: # 0x30 - 0x3f = private character set # 0x40 - 0x7f = standardized character set # Character set invocation: # G0 : SI = 0x15 # G1 : SO = 0x14, LS1R = 0x1b 0x7e ('~') # G2 : LS2 = 0x1b 0x6e ('n'), LS2R = 0x1b 0x7d ('}') # G3 : LS3 = 0x1b 0x6f ('o'), LS3R = 0x1b 0x7c ('|') # (the locking shift "R" codes shift into 0x80-0xff space) # Single character invocation: # G2 : SS2 = 0x1b 0x8e (or 0x4e in 7-bit) # G3 : SS3 = 0x1b 0x8f (or 0x4f in 7-bit) # Control chars (designated and invoked) # C0 : 0x1b 0x21 F (0x21 = '!') # C1 : 0x1b 0x22 F (0x22 = '"') # Complete codes (control+graphics, designated and invoked) # 0x1b 0x25 F (0x25 = '%') # 0x1b 0x25 I F # 0x1b 0x25 0x47 ("\x1b%G") - UTF-8 # 0x1b 0x25 0x40 ("\x1b%@") - return to ISO 2022 # ------------------------------- #------------------------------------------------------------------------------ # Inverse print conversion for CodedCharacterSet # Inputs: 0) value sub PrintInvCodedCharset($) { my $val = shift; my $code = $iptcCharsetInv{uc($val)}; unless ($code) { if (($code = $val) =~ s/ESC */\x1b/ig) { # translate ESC chars $code =~ s/, \x1b/\x1b/g; # remove comma separators $code =~ tr/ //d; # remove spaces } else { warn "Bad syntax (use 'UTF8' or 'ESC X Y[, ...]')\n"; } } return $code; } #------------------------------------------------------------------------------ # validate raw values for writing # Inputs: 0) ExifTool object ref, 1) tagInfo hash ref, 2) raw value ref # Returns: error string or undef (and possibly changes value) on success sub CheckIPTC($$$) { my ($et, $tagInfo, $valPtr) = @_; my $format = $$tagInfo{Format} || $$tagInfo{Table}{FORMAT} || ''; if ($format =~ /^int(\d+)/) { my $bytes = int(($1 || 0) / 8); if ($bytes != 1 and $bytes != 2 and $bytes != 4) { return "Can't write $bytes-byte integer"; } my $val = $$valPtr; unless (Image::ExifTool::IsInt($val)) { return 'Not an integer' unless Image::ExifTool::IsHex($val); $val = $$valPtr = hex($val); } my $n; for ($n=0; $n<$bytes; ++$n) { $val >>= 8; } return "Value too large for $bytes-byte format" if $val; } elsif ($format =~ /^(string|digits|undef)\[?(\d+),?(\d*)\]?$/) { my ($fmt, $minlen, $maxlen) = ($1, $2, $3); my $len = length $$valPtr; if ($fmt eq 'digits') { return 'Non-numeric characters in value' unless $$valPtr =~ /^\d*$/; if ($len < $minlen and $len) { # left pad with zeros if necessary $$valPtr = ('0' x ($minlen - $len)) . $$valPtr; $len = $minlen; } } if (defined $minlen and $fmt ne 'string') { # (must truncate strings later, after recoding) $maxlen or $maxlen = $minlen; if ($len < $minlen) { unless ($$et{OPTIONS}{IgnoreMinorErrors}) { return "[Minor] String too short (minlen is $minlen)"; } $$et{CHECK_WARN} = "String too short for IPTC:$$tagInfo{Name} (written anyway)"; } elsif ($len > $maxlen and not $$et{OPTIONS}{IgnoreMinorErrors}) { $$et{CHECK_WARN} = "[Minor] IPTC:$$tagInfo{Name} exceeds length limit (truncated)"; $$valPtr = substr($$valPtr, 0, $maxlen); } } } else { return "Bad IPTC Format ($format)"; } return undef; } #------------------------------------------------------------------------------ # format IPTC data for writing # Inputs: 0) ExifTool object ref, 1) tagInfo pointer, # 2) value reference (changed if necessary), # 3) reference to character set for translation (changed if necessary) # 4) record number, 5) flag set to read value (instead of write) sub FormatIPTC($$$$$;$) { my ($et, $tagInfo, $valPtr, $xlatPtr, $rec, $read) = @_; my $format = $$tagInfo{Format} || $$tagInfo{Table}{FORMAT}; return unless $format; if ($format =~ /^int(\d+)/) { if ($read) { my $len = length($$valPtr); if ($len <= 8) { # limit integer conversion to 8 bytes long my $val = 0; my $i; for ($i=0; $i<$len; ++$i) { $val = $val * 256 + ord(substr($$valPtr, $i, 1)); } $$valPtr = $val; } } else { my $len = int(($1 || 0) / 8); if ($len == 1) { # 1 byte $$valPtr = chr($$valPtr); } elsif ($len == 2) { # 2-byte integer $$valPtr = pack('n', $$valPtr); } else { # 4-byte integer $$valPtr = pack('N', $$valPtr); } } } elsif ($format =~ /^string/) { if ($rec == 1) { if ($$tagInfo{Name} eq 'CodedCharacterSet') { $$xlatPtr = HandleCodedCharset($et, $$valPtr); } } elsif ($$xlatPtr and $rec < 7 and $$valPtr =~ /[\x80-\xff]/) { TranslateCodedString($et, $valPtr, $xlatPtr, $read); } # must check length now (after any string recoding) if (not $read and $format =~ /^string\[(\d+),?(\d*)\]$/) { my ($minlen, $maxlen) = ($1, $2); my $len = length $$valPtr; $maxlen or $maxlen = $minlen; if ($len < $minlen) { if ($et->Warn("String too short for IPTC:$$tagInfo{Name} (padded)", 2)) { $$valPtr .= ' ' x ($minlen - $len); } } elsif ($len > $maxlen) { if ($et->Warn("IPTC:$$tagInfo{Name} exceeds length limit (truncated)", 2)) { $$valPtr = substr($$valPtr, 0, $maxlen); # make sure UTF-8 is still valid if (($$xlatPtr || $et->Options('Charset')) eq 'UTF8') { require Image::ExifTool::XMP; Image::ExifTool::XMP::FixUTF8($valPtr,'.'); } } } } } } #------------------------------------------------------------------------------ # generate IPTC-format date # Inputs: 0) EXIF-format date string (YYYY:mm:dd) or date/time string # Returns: IPTC-format date string (YYYYmmdd), or undef and issue warning on error sub IptcDate($) { my $val = shift; unless ($val =~ s{^.*(\d{4})[-:/.]?(\d{2})[-:/.]?(\d{2}).*}{$1$2$3}s) { warn "Invalid date format (use YYYY:mm:dd)\n"; undef $val; } return $val; } #------------------------------------------------------------------------------ # generate IPTC-format time # Inputs: 0) EXIF-format time string (HH:MM:SS[+/-HH:MM]) or date/time string # Returns: IPTC-format time string (HHMMSS+HHMM), or undef and issue warning on error sub IptcTime($) { my $val = shift; if ($val =~ /(.*?)\b(\d{1,2})(:?)(\d{2})(:?)(\d{2})(\S*)\s*$/s and ($3 or not $5)) { $val = sprintf("%.2d%.2d%.2d",$2,$4,$6); my ($date, $tz) = ($1, $7); if ($tz =~ /([+-]\d{1,2}):?(\d{2})/) { $tz = sprintf("%+.2d%.2d",$1,$2); } elsif ($tz =~ /Z/i) { $tz = '+0000'; # UTC } else { # use local system timezone by default my (@tm, $time); if ($date and $date =~ /^(\d{4}):(\d{2}):(\d{2})\s*$/ and eval { require Time::Local }) { # we were given a date too, so determine the local timezone # offset at the specified date/time my @d = ($3,$2-1,$1); $val =~ /(\d{2})(\d{2})(\d{2})/; @tm = ($3,$2,$1,@d); $time = Image::ExifTool::TimeLocal(@tm); } else { # it is difficult to get the proper local timezone offset for this # time because the date tag is written separately. (The offset may be # different on a different date due to daylight savings time.) In this # case the best we can do easily is to use the current timezone offset. $time = time; @tm = localtime($time); } ($tz = Image::ExifTool::TimeZoneString(\@tm, $time)) =~ tr/://d; } $val .= $tz; } else { warn "Invalid time format (use HH:MM:SS[+/-HH:MM])\n"; undef $val; # time format error } return $val; } #------------------------------------------------------------------------------ # Inverse print conversion for IPTC date or time value # Inputs: 0) ExifTool ref, 1) IPTC date or 'now' # Returns: IPTC date sub InverseDateOrTime($$) { my ($et, $val) = @_; return $et->TimeNow() if lc($val) eq 'now'; return $val; } #------------------------------------------------------------------------------ # Convert picture number # Inputs: 0) value # Returns: Converted value sub ConvertPictureNumber($) { my $val = shift; if ($val eq "\0" x 16) { $val = 'Unknown'; } elsif (length $val >= 16) { my @vals = unpack('nNA8n', $val); $val = $vals[0]; my $manu = $manufacturer{$val}; $val .= " ($manu)" if $manu; $val .= ', equip ' . $vals[1]; $vals[2] =~ s/(\d{4})(\d{2})(\d{2})/$1:$2:$3/; $val .= ", $vals[2], no. $vals[3]"; } else { $val = '<format error>' } return $val; } #------------------------------------------------------------------------------ # Inverse picture number conversion # Inputs: 0) value # Returns: Converted value (or undef on error) sub InvConvertPictureNumber($) { my $val = shift; $val =~ s/\(.*\)//g; # remove manufacturer description $val =~ tr/://d; # remove date separators $val =~ tr/0-9/ /c; # turn remaining non-numbers to spaces my @vals = split ' ', $val; if (@vals >= 4) { $val = pack('nNA8n', @vals); } elsif ($val =~ /unknown/i) { $val = "\0" x 16; } else { undef $val; } return $val; } #------------------------------------------------------------------------------ # Write IPTC data record # Inputs: 0) ExifTool object ref, 1) source dirInfo ref, 2) tag table ref # Returns: IPTC data block (may be empty if no IPTC data) # Notes: Increments ExifTool CHANGED flag for each tag changed sub DoWriteIPTC($$$) { my ($et, $dirInfo, $tagTablePtr) = @_; my $verbose = $et->Options('Verbose'); my $out = $et->Options('TextOut'); # avoid editing IPTC directory unless necessary: # - improves speed # - avoids changing current MD5 digest unnecessarily # - avoids adding mandatory tags unless some other IPTC is changed unless (exists $$et{EDIT_DIRS}{$$dirInfo{DirName}} or # standard IPTC tags in other locations should be edited too (eg. AFCP_IPTC) ($tagTablePtr eq \%Image::ExifTool::IPTC::Main and exists $$et{EDIT_DIRS}{IPTC})) { print $out "$$et{INDENT} [nothing changed]\n" if $verbose; return undef; } my $dataPt = $$dirInfo{DataPt}; unless ($dataPt) { my $emptyData = ''; $dataPt = \$emptyData; } my $start = $$dirInfo{DirStart} || 0; my $dirLen = $$dirInfo{DirLen}; my ($tagInfo, %iptcInfo, $tag); # start by assuming default IPTC encoding my $xlat = $et->Options('CharsetIPTC'); undef $xlat if $xlat eq $et->Options('Charset'); # make sure our dataLen is defined (note: allow zero length directory) unless (defined $dirLen) { my $dataLen = $$dirInfo{DataLen}; $dataLen = length($$dataPt) unless defined $dataLen; $dirLen = $dataLen - $start; } # quick check for improperly byte-swapped IPTC if ($dirLen >= 4 and substr($$dataPt, $start, 1) ne "\x1c" and substr($$dataPt, $start + 3, 1) eq "\x1c") { $et->Warn('IPTC data was improperly byte-swapped'); my $newData = pack('N*', unpack('V*', substr($$dataPt, $start, $dirLen) . "\0\0\0")); $dataPt = \$newData; $start = 0; # NOTE: MUST NOT access $dirInfo DataPt, DirStart or DataLen after this! } # generate lookup so we can find the record numbers my %recordNum; foreach $tag (Image::ExifTool::TagTableKeys($tagTablePtr)) { $tagInfo = $$tagTablePtr{$tag}; $$tagInfo{SubDirectory} or next; my $table = $$tagInfo{SubDirectory}{TagTable} or next; my $subTablePtr = Image::ExifTool::GetTagTable($table); $recordNum{$subTablePtr} = $tag; } # loop through new values and accumulate all IPTC information # into lists based on their IPTC record type foreach $tagInfo ($et->GetNewTagInfoList()) { my $table = $$tagInfo{Table}; my $record = $recordNum{$table}; # ignore tags we aren't writing to this directory next unless defined $record; $iptcInfo{$record} = [] unless defined $iptcInfo{$record}; push @{$iptcInfo{$record}}, $tagInfo; } # get sorted list of records used. Might as well be organized and # write our records in order of record number first, then tag number my @recordList = sort { $a <=> $b } keys %iptcInfo; my ($record, %set); foreach $record (@recordList) { # sort tagInfo lists by tagID @{$iptcInfo{$record}} = sort { $$a{TagID} <=> $$b{TagID} } @{$iptcInfo{$record}}; # build hash of all tagIDs to set foreach $tagInfo (@{$iptcInfo{$record}}) { $set{$record}->{$$tagInfo{TagID}} = $tagInfo; } } # run through the old IPTC data, inserting our records in # sequence and deleting existing records where necessary # (the IPTC specification states that records must occur in # numerical order, but tags within records need not be ordered) my $pos = $start; my $tail = $pos; # old data written up to this point my $dirEnd = $start + $dirLen; my $newData = ''; my $lastRec = -1; my $lastRecPos = 0; my $allMandatory = 0; my %foundRec; # found flags: 0x01-existed before, 0x02-deleted, 0x04-created my $addNow; for (;;$tail=$pos) { # get next IPTC record from input directory my ($id, $rec, $tag, $len, $valuePtr); if ($pos + 5 <= $dirEnd) { my $buff = substr($$dataPt, $pos, 5); ($id, $rec, $tag, $len) = unpack("CCCn", $buff); if ($id == 0x1c) { if ($rec < $lastRec) { if ($rec == 0) { return undef if $et->Warn("IPTC record 0 encountered, subsequent records ignored", 2); undef $rec; $pos = $dirEnd; $len = 0; } else { return undef if $et->Warn("IPTC doesn't conform to spec: Records out of sequence", 2); } } # handle extended IPTC entry if necessary $pos += 5; # step to after field header if ($len & 0x8000) { my $n = $len & 0x7fff; # get num bytes in length field if ($pos + $n <= $dirEnd and $n <= 8) { # determine length (a big-endian, variable sized int) for ($len = 0; $n; ++$pos, --$n) { $len = $len * 256 + ord(substr($$dataPt, $pos, 1)); } } else { $len = $dirEnd; # invalid length } } $valuePtr = $pos; $pos += $len; # step $pos to next entry # make sure we don't go past the end of data # (this can only happen if original data is bad) $pos = $dirEnd if $pos > $dirEnd; } else { undef $rec; } } # write out all our records that come before this one my $writeRec = (not defined $rec or $rec != $lastRec); if ($writeRec or $addNow) { for (;;) { my $newRec = $recordList[0]; if ($addNow) { $tagInfo = $addNow; } elsif (not defined $newRec or $newRec != $lastRec) { # handle mandatory tags in last record unless it was empty if (length $newData > $lastRecPos) { if ($allMandatory > 1) { # entire lastRec contained mandatory tags, and at least one tag # was deleted, so delete entire record unless we specifically # added a mandatory tag my $num = 0; foreach (keys %{$foundRec{$lastRec}}) { my $code = $foundRec{$lastRec}->{$_}; $num = 0, last if $code & 0x04; ++$num if ($code & 0x03) == 0x01; } if ($num) { $newData = substr($newData, 0, $lastRecPos); $verbose > 1 and print $out " - $num mandatory tags\n"; } } elsif ($mandatory{$lastRec} and $tagTablePtr eq \%Image::ExifTool::IPTC::Main) { # add required mandatory tags my $mandatory = $mandatory{$lastRec}; my ($mandTag, $subTablePtr); foreach $mandTag (sort { $a <=> $b } keys %$mandatory) { next if $foundRec{$lastRec}->{$mandTag}; unless ($subTablePtr) { $tagInfo = $$tagTablePtr{$lastRec}; $tagInfo and $$tagInfo{SubDirectory} or warn("WriteIPTC: Internal error 1\n"), next; $$tagInfo{SubDirectory}{TagTable} or next; $subTablePtr = Image::ExifTool::GetTagTable($$tagInfo{SubDirectory}{TagTable}); } $tagInfo = $$subTablePtr{$mandTag} or warn("WriteIPTC: Internal error 2\n"), next; my $value = $$mandatory{$mandTag}; $et->VerboseValue("+ IPTC:$$tagInfo{Name}", $value, ' (mandatory)'); # apply necessary format conversions FormatIPTC($et, $tagInfo, \$value, \$xlat, $lastRec); $len = length $value; # generate our new entry my $entry = pack("CCCn", 0x1c, $lastRec, $mandTag, length($value)); $newData .= $entry . $value; # add entry to new IPTC data # (don't mark as changed if just mandatory tags changed) # ++$$et{CHANGED}; } } } last unless defined $newRec; $lastRec = $newRec; $lastRecPos = length $newData; $allMandatory = 1; } unless ($addNow) { # compare current entry with entry next in line to write out # (write out our tags in numerical order even though # this isn't required by the IPTC spec) last if defined $rec and $rec <= $newRec; $tagInfo = ${$iptcInfo{$newRec}}[0]; } my $newTag = $$tagInfo{TagID}; my $nvHash = $et->GetNewValueHash($tagInfo); # only add new values if... my ($doSet, @values); my $found = $foundRec{$newRec}->{$newTag} || 0; if ($found & 0x02) { # ...tag existed before and was deleted (unless we already added it) $doSet = 1 unless $found & 0x04; } elsif ($$tagInfo{List}) { # ...tag is List and it existed before or we are creating it $doSet = 1 if $found ? not $$nvHash{CreateOnly} : $$nvHash{IsCreating}; } else { # ...tag didn't exist before and we are creating it $doSet = 1 if not $found and $$nvHash{IsCreating}; } if ($doSet) { @values = $et->GetNewValue($nvHash); @values and $foundRec{$newRec}->{$newTag} = $found | 0x04; # write tags for each value in list my $value; foreach $value (@values) { $et->VerboseValue("+ $$dirInfo{DirName}:$$tagInfo{Name}", $value); # reset allMandatory flag if a non-mandatory tag is written if ($allMandatory) { my $mandatory = $mandatory{$newRec}; $allMandatory = 0 unless $mandatory and $$mandatory{$newTag}; } # apply necessary format conversions FormatIPTC($et, $tagInfo, \$value, \$xlat, $newRec); # (note: IPTC string values are NOT null terminated) $len = length $value; # generate our new entry my $entry = pack("CCC", 0x1c, $newRec, $newTag); if ($len <= 0x7fff) { $entry .= pack("n", $len); } else { # extended dataset tag $entry .= pack("nN", 0x8004, $len); } $newData .= $entry . $value; # add entry to new IPTC data ++$$et{CHANGED}; } } # continue on with regular programming if done adding tag now if ($addNow) { undef $addNow; next if $writeRec; last; } # remove this tagID from the sorted write list shift @{$iptcInfo{$newRec}}; shift @recordList unless @{$iptcInfo{$newRec}}; } if ($writeRec) { # all done if no more records to write last unless defined $rec; # update last record variables $lastRec = $rec; $lastRecPos = length $newData; $allMandatory = 1; } } # set flag indicating we found this tag $foundRec{$rec}->{$tag} = ($foundRec{$rec}->{$tag} || 0) || 0x01; # write out this record unless we are setting it with a new value $tagInfo = $set{$rec}->{$tag}; if ($tagInfo) { my $nvHash = $et->GetNewValueHash($tagInfo); $len = $pos - $valuePtr; my $val = substr($$dataPt, $valuePtr, $len); # remove null terminator if it exists (written by braindead software like Picasa 2.0) $val =~ s/\0+$// if $$tagInfo{Format} and $$tagInfo{Format} =~ /^string/; my $oldXlat = $xlat; FormatIPTC($et, $tagInfo, \$val, \$xlat, $rec, 1); if ($et->IsOverwriting($nvHash, $val)) { $xlat = $oldXlat; # don't change translation (not writing this value) $et->VerboseValue("- $$dirInfo{DirName}:$$tagInfo{Name}", $val); ++$$et{CHANGED}; # set deleted flag to indicate we found and deleted this tag $foundRec{$rec}->{$tag} |= 0x02; # increment allMandatory flag to indicate a tag was removed $allMandatory and ++$allMandatory; # write this tag now if overwriting an existing value if ($$nvHash{Value} and @{$$nvHash{Value}} and @recordList and $recordList[0] == $rec and not $foundRec{$rec}->{$tag} & 0x04) { $addNow = $tagInfo; } next; } } elsif ($rec == 1 and $tag == 90) { # handle CodedCharacterSet tag my $val = substr($$dataPt, $valuePtr, $pos - $valuePtr); $xlat = HandleCodedCharset($et, $val); } # reset allMandatory flag if a non-mandatory tag is written if ($allMandatory) { my $mandatory = $mandatory{$rec}; unless ($mandatory and $$mandatory{$tag}) { $allMandatory = 0; } } # write out the record $newData .= substr($$dataPt, $tail, $pos-$tail); } # make sure the rest of the data is zero if ($tail < $dirEnd) { my $pad = substr($$dataPt, $tail, $dirEnd-$tail); if ($pad =~ /[^\0]/) { return undef if $et->Warn('Unrecognized data in IPTC padding', 2); } } return $newData; } #------------------------------------------------------------------------------ # Write IPTC data record and calculate NewIPTCDigest # Inputs: 0) ExifTool object ref, 1) source dirInfo ref, 2) tag table ref # Returns: IPTC data block (may be empty if no IPTC data) # Notes: Increments ExifTool CHANGED flag for each tag changed sub WriteIPTC($$$) { my ($et, $dirInfo, $tagTablePtr) = @_; $et or return 1; # allow dummy access to autoload this package my $newData = DoWriteIPTC($et, $dirInfo, $tagTablePtr); # calculate standard IPTC digests only if we are writing or deleting # Photoshop:IPTCDigest with a value of 'new' or 'old' while ($Image::ExifTool::Photoshop::iptcDigestInfo) { my $nvHash = $$et{NEW_VALUE}{$Image::ExifTool::Photoshop::iptcDigestInfo}; last unless defined $nvHash; last unless IsStandardIPTC($et->MetadataPath()); my @values = $et->GetNewValue($nvHash); push @values, @{$$nvHash{DelValue}} if $$nvHash{DelValue}; my $new = grep /^new$/, @values; my $old = grep /^old$/, @values; last unless $new or $old; unless (eval { require Digest::MD5 }) { $et->Warn('Digest::MD5 must be installed to calculate IPTC digest'); last; } my $dataPt; if ($new) { if (defined $newData) { $dataPt = \$newData; } else { $dataPt = $$dirInfo{DataPt}; if ($$dirInfo{DirStart} or length($$dataPt) != $$dirInfo{DirLen}) { my $buff = substr($$dataPt, $$dirInfo{DirStart}, $$dirInfo{DirLen}); $dataPt = \$buff; } } # set NewIPTCDigest data member unless IPTC is being deleted $$et{NewIPTCDigest} = Digest::MD5::md5($$dataPt) if length $$dataPt; } if ($old) { if ($new and not defined $newData) { $$et{OldIPTCDigest} = $$et{NewIPTCDigest}; } elsif ($$dirInfo{DataPt}) { #(may be undef if creating new IPTC) $dataPt = $$dirInfo{DataPt}; if ($$dirInfo{DirStart} or length($$dataPt) != $$dirInfo{DirLen}) { my $buff = substr($$dataPt, $$dirInfo{DirStart}, $$dirInfo{DirLen}); $dataPt = \$buff; } $$et{OldIPTCDigest} = Digest::MD5::md5($$dataPt) if length $$dataPt; } } last; } # set changed if ForceWrite tag was set to "IPTC" ++$$et{CHANGED} if defined $newData and length $newData and $$et{FORCE_WRITE}{IPTC}; return $newData; } 1; # end __END__ =head1 NAME Image::ExifTool::WriteIPTC.pl - Write IPTC meta information =head1 SYNOPSIS This file is autoloaded by Image::ExifTool::IPTC. =head1 DESCRIPTION This file contains routines to write IPTC metadata, plus a few other seldom-used routines. =head1 AUTHOR Copyright 2003-2020, Phil Harvey (philharvey66 at gmail.com) This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 SEE ALSO L<Image::ExifTool::IPTC(3pm)|Image::ExifTool::IPTC>, L<Image::ExifTool(3pm)|Image::ExifTool> =cut
mkjanke/Focus-Points
focuspoints.lrdevplugin/bin/exiftool/lib/Image/ExifTool/WriteIPTC.pl
Perl
apache-2.0
30,306
=head1 cron-lib.pl Functions for listing, creating and managing Unix users' cron jobs. foreign_require("cron", "cron-lib.pl"); @jobs = cron::list_cron_jobs(); $job = { 'user' => 'root', 'active' => 1, 'command' => 'ls -l >/dev/null', 'special' => 'hourly' }; cron::create_cron_job($job); =cut BEGIN { push(@INC, ".."); }; use WebminCore; &init_config(); %access = &get_module_acl(); $env_support = $config{'vixie_cron'}; if ($module_info{'usermin'}) { $single_user = $remote_user; &switch_to_remote_user(); &create_user_config_dirs(); $range_cmd = "$user_module_config_directory/range.pl"; $hourly_only = 0; } else { $range_cmd = "$module_config_directory/range.pl"; $hourly_only = $access{'hourly'} == 0 ? 0 : $access{'hourly'} == 1 ? 1 : $config{'hourly_only'}; } $temp_delete_cmd = "$module_config_directory/tempdelete.pl"; $cron_temp_file = &transname(); use Time::Local; =head2 list_cron_jobs Returns a lists of structures of all cron jobs, each of which is a hash reference with the following keys : =item user - Unix user the job runs as. =item command - The full command to be run. =item active - Set to 0 if the job is commented out, 1 if active. =item mins - Minute or comma-separated list of minutes the job will run, or * for all. =item hours - Hour or comma-separated list of hours the job will run, or * for all. =item days - Day or comma-separated list of days of the month the job will run, or * for all. =item month - Month number or comma-separated list of months (started from 1) the job will run, or * for all. =item weekday - Day of the week or comma-separated list of days (where 0 is sunday) the job will run, or * for all =cut sub list_cron_jobs { local (@rv, $lnum, $f); if (scalar(@cron_jobs_cache)) { return @cron_jobs_cache; } # read the master crontab file if ($config{'system_crontab'}) { $lnum = 0; &open_readfile(TAB, $config{'system_crontab'}); while(<TAB>) { # Comment line in Fedora 13 next if (/^#+\s+\*\s+\*\s+\*\s+\*\s+\*\s+(user-name\s+)?command\s+to\s+be\s+executed/); if (/^(#+)?[\s\&]*(-)?\s*([0-9\-\*\/,]+)\s+([0-9\-\*\/,]+)\s+([0-9\-\*\/,]+)\s+(([0-9\-\*\/]+|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec|,)+)\s+(([0-9\-\*\/]+|sun|mon|tue|wed|thu|fri|sat|,)+)\s+(\S+)\s+(.*)/i) { # A normal h m s d w time push(@rv, { 'file' => $config{'system_crontab'}, 'line' => $lnum, 'type' => 1, 'nolog' => $2, 'active' => !$1, 'mins' => $3, 'hours' => $4, 'days' => $5, 'months' => $6, 'weekdays' => $8, 'user' => $10, 'command' => $11, 'index' => scalar(@rv) }); if ($rv[$#rv]->{'user'} =~ /^\//) { # missing the user, as in redhat 7 ! $rv[$#rv]->{'command'} = $rv[$#rv]->{'user'}. ' '.$rv[$#rv]->{'command'}; $rv[$#rv]->{'user'} = 'root'; } &fix_names($rv[$#rv]); } elsif (/^(#+)?\s*@([a-z]+)\s+(\S+)\s+(.*)/i) { # An @ time push(@rv, { 'file' => $config{'system_crontab'}, 'line' => $lnum, 'type' => 1, 'active' => !$1, 'special' => $2, 'user' => $3, 'command' => $4, 'index' => scalar(@rv) }); } $lnum++; } close(TAB); } # read package-specific cron files opendir(DIR, &translate_filename($config{'cronfiles_dir'})); while($f = readdir(DIR)) { next if ($f =~ /^\./); $lnum = 0; &open_readfile(TAB, "$config{'cronfiles_dir'}/$f"); while(<TAB>) { if (/^(#+)?[\s\&]*(-)?\s*([0-9\-\*\/,]+)\s+([0-9\-\*\/,]+)\s+([0-9\-\*\/,]+)\s+(([0-9\-\*\/]+|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec|,)+)\s+(([0-9\-\*\/]+|sun|mon|tue|wed|thu|fri|sat|,)+)\s+(\S+)\s+(.*)/i) { push(@rv, { 'file' => "$config{'cronfiles_dir'}/$f", 'line' => $lnum, 'type' => 2, 'active' => !$1, 'nolog' => $2, 'mins' => $3, 'hours' => $4, 'days' => $5, 'months' => $6, 'weekdays' => $8, 'user' => $10, 'command' => $11, 'index' => scalar(@rv) }); &fix_names($rv[$#rv]); } elsif (/^(#+)?\s*@([a-z]+)\s+(\S+)\s+(.*)/i) { push(@rv, { 'file' => "$config{'cronfiles_dir'}/$f", 'line' => $lnum, 'type' => 2, 'active' => !$1, 'special' => $2, 'user' => $3, 'command' => $4, 'index' => scalar(@rv) }); } $lnum++; } close(TAB); } closedir(DIR); # Read a single user's crontab file if ($config{'single_file'}) { &open_readfile(TAB, $config{'single_file'}); $lnum = 0; while(<TAB>) { if (/^(#+)?[\s\&]*(-)?\s*([0-9\-\*\/,]+)\s+([0-9\-\*\/,]+)\s+([0-9\-\*\/,]+)\s+(([0-9\-\*\/]+|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec|,)+)\s+(([0-9\-\*\/]+|sun|mon|tue|wed|thu|fri|sat|,)+)\s+(.*)/i) { # A normal m h d m wd time push(@rv, { 'file' => $config{'single_file'}, 'line' => $lnum, 'type' => 3, 'active' => !$1, 'nolog' => $2, 'mins' => $3, 'hours' => $4, 'days' => $5, 'months' => $6, 'weekdays' => $8, 'user' => "NONE", 'command' => $10, 'index' => scalar(@rv) }); &fix_names($rv[$#rv]); } elsif (/^(#+)?\s*([a-zA-Z0-9\_]+)\s*=\s*'([^']*)'/ || /^(#+)?\s*([a-zA-Z0-9\_]+)\s*=\s*"([^']*)"/ || /^(#+)?\s*([a-zA-Z0-9\_]+)\s*=\s*(\S+)/) { # An environment variable push(@rv, { 'file' => $config{'single_file'}, 'line' => $lnum, 'active' => !$1, 'name' => $2, 'value' => $3, 'user' => "NONE", 'index' => scalar(@rv) }); } $lnum++; } close(TAB); } # read per-user cron files local $fcron = ($config{'cron_dir'} =~ /\/fcron$/); local @users; if ($single_user) { @users = ( $single_user ); } else { opendir(DIR, &translate_filename($config{'cron_dir'})); @users = grep { !/^\./ } readdir(DIR); closedir(DIR); } foreach $f (@users) { next if (!(@uinfo = getpwnam($f))); $lnum = 0; if ($single_user) { &open_execute_command(TAB, $config{'cron_user_get_command'}, 1); } elsif ($fcron) { &open_execute_command(TAB, &user_sub($config{'cron_get_command'}, $f), 1); } else { &open_readfile(TAB, "$config{'cron_dir'}/$f"); } while(<TAB>) { if (/^(#+)?[\s\&]*(-)?\s*([0-9\-\*\/,]+)\s+([0-9\-\*\/,]+)\s+([0-9\-\*\/,]+)\s+(([0-9\-\*\/]+|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec|,)+)\s+(([0-9\-\*\/]+|sun|mon|tue|wed|thu|fri|sat|,)+)\s+(.*)/i) { # A normal m h d m wd time push(@rv, { 'file' => "$config{'cron_dir'}/$f", 'line' => $lnum, 'type' => 0, 'active' => !$1, 'nolog' => $2, 'mins' => $3, 'hours' => $4, 'days' => $5, 'months' => $6, 'weekdays' => $8, 'user' => $f, 'command' => $10, 'index' => scalar(@rv) }); $rv[$#rv]->{'file'} =~ s/\s+\|$//; &fix_names($rv[$#rv]); } elsif (/^(#+)?\s*@([a-z]+)\s+(.*)/i) { # An @ time push(@rv, { 'file' => "$config{'cron_dir'}/$f", 'line' => $lnum, 'type' => 0, 'active' => !$1, 'special' => $2, 'user' => $f, 'command' => $3, 'index' => scalar(@rv) }); } elsif (/^(#+)?\s*([a-zA-Z0-9\_]+)\s*=\s*'([^']*)'/ || /^(#+)?\s*([a-zA-Z0-9\_]+)\s*=\s*"([^']*)"/ || /^(#+)?\s*([a-zA-Z0-9\_]+)\s*=\s*(\S+)/) { # An environment variable push(@rv, { 'file' => "$config{'cron_dir'}/$f", 'line' => $lnum, 'active' => !$1, 'name' => $2, 'value' => $3, 'user' => $f, 'index' => scalar(@rv) }); } $lnum++; } close(TAB); } closedir(DIR); @cron_jobs_cache = @rv; return @cron_jobs_cache; } =head2 cron_job_line(&job) Internal function to generate a crontab format line for a cron job. =cut sub cron_job_line { local @c; push(@c, "#") if (!$_[0]->{'active'}); if ($_[0]->{'name'}) { push(@c, $_[0]->{'name'}); push(@c, "="); push(@c, $_[0]->{'value'} =~ /'/ ? "\"$_[0]->{'value'}\"" : $_[0]->{'value'} =~ /"/ ? "'$_[0]->{'value'}'" : $_[0]->{'value'} !~ /^\S+$/ ? "\"$_[0]->{'value'}\"" : $_[0]->{'value'}); } else { if ($_[0]->{'special'}) { push(@c, ($_[0]->{'nolog'} ? '-' : '').'@'.$_[0]->{'special'}); } else { push(@c, ($_[0]->{'nolog'} ? '-' : '').$_[0]->{'mins'}, $_[0]->{'hours'}, $_[0]->{'days'}, $_[0]->{'months'}, $_[0]->{'weekdays'}); } push(@c, $_[0]->{'user'}) if ($_[0]->{'type'} != 0 && $_[0]->{'type'} != 3); push(@c, $_[0]->{'command'}); } return join(" ", @c); } =head2 copy_cron_temp(&job) Copies a job's user's current cron configuration to the temp file. For internal use only. =cut sub copy_cron_temp { local $fcron = ($config{'cron_dir'} =~ /\/fcron$/); unlink($cron_temp_file); if ($single_user) { &execute_command($config{'cron_user_get_command'}, undef, $cron_temp_file, undef); } elsif ($fcron) { &execute_command(&user_sub($config{'cron_get_command'},$_[0]->{'user'}), undef, $cron_temp_file, undef); } else { system("cp ".&translate_filename("$config{'cron_dir'}/$_[0]->{'user'}"). " $cron_temp_file 2>/dev/null"); } } =head2 create_cron_job(&job) Add a Cron job to a user's file. The job parameter must be a hash reference in the same format as returned by list_cron_jobs. =cut sub create_cron_job { &check_cron_config_or_error(); &list_cron_jobs(); # init cache if ($config{'add_file'}) { # Add to a specific file, typically something like /etc/cron.d/webmin $_[0]->{'type'} = 1; local $lref = &read_file_lines($config{'add_file'}); push(@$lref, &cron_job_line($_[0])); &flush_file_lines($config{'add_file'}); } elsif ($config{'single_file'} && !$config{'cron_dir'}) { # Add to the single file $_[0]->{'type'} = 3; local $lref = &read_file_lines($config{'single_file'}); push(@$lref, &cron_job_line($_[0])); &flush_file_lines($config{'single_file'}); } else { # Add to the specified user's crontab &copy_cron_temp($_[0]); local $lref = &read_file_lines($cron_temp_file); $_[0]->{'line'} = scalar(@$lref); push(@$lref, &cron_job_line($_[0])); &flush_file_lines($cron_temp_file); &set_ownership_permissions($_[0]->{'user'}, undef, undef, $cron_temp_file); &copy_crontab($_[0]->{'user'}); $_[0]->{'file'} = "$config{'cron_dir'}/$_[0]->{'user'}"; $_[0]->{'index'} = scalar(@cron_jobs_cache); push(@cron_jobs_cache, $_[0]); } } =head2 insert_cron_job(&job) Add a Cron job at the top of the user's file. The job parameter must be a hash reference in the same format as returned by list_cron_jobs. =cut sub insert_cron_job { &check_cron_config_or_error(); &list_cron_jobs(); # init cache if ($config{'single_file'} && !$config{'cron_dir'}) { # Insert into single file $_[0]->{'type'} = 3; local $lref = &read_file_lines($config{'single_file'}); splice(@$lref, 0, 0, &cron_job_line($_[0])); &flush_file_lines($config{'single_file'}); } else { # Insert into the user's crontab &copy_cron_temp($_[0]); local $lref = &read_file_lines($cron_temp_file); $_[0]->{'line'} = 0; splice(@$lref, 0, 0, &cron_job_line($_[0])); &flush_file_lines(); system("chown $_[0]->{'user'} $cron_temp_file"); &copy_crontab($_[0]->{'user'}); $_[0]->{'file'} = "$config{'cron_dir'}/$_[0]->{'user'}"; $_[0]->{'index'} = scalar(@cron_jobs_cache); &renumber($_[0]->{'file'}, $_[0]->{'line'}, 1); push(@cron_jobs_cache, $_[0]); } } =head2 renumber(file, line, offset) All jobs in this file whose line is at or after the given one will be incremented by the offset. For internal use. =cut sub renumber { local $j; foreach $j (@cron_jobs_cache) { if ($j->{'line'} >= $_[1] && $j->{'file'} eq $_[0]) { $j->{'line'} += $_[2]; } } } =head2 renumber_index(index, offset) Internal function to change the index of all cron jobs in the cache after some index by a given offset. For internal use. =cut sub renumber_index { local $j; foreach $j (@cron_jobs_cache) { if ($j->{'index'} >= $_[0]) { $j->{'index'} += $_[1]; } } } =head2 change_cron_job(&job) Updates the given cron job, which must be a hash ref returned by list_cron_jobs and modified with a new active flag, command or schedule. =cut sub change_cron_job { if ($_[0]->{'type'} == 0) { &copy_cron_temp($_[0]); &replace_file_line($cron_temp_file, $_[0]->{'line'}, &cron_job_line($_[0])."\n"); &copy_crontab($_[0]->{'user'}); } else { &replace_file_line($_[0]->{'file'}, $_[0]->{'line'}, &cron_job_line($_[0])."\n"); } } =head2 delete_cron_job(&job) Removes the cron job defined by the given hash ref, as returned by list_cron_jobs. =cut sub delete_cron_job { if ($_[0]->{'type'} == 0) { &copy_cron_temp($_[0]); &replace_file_line($cron_temp_file, $_[0]->{'line'}); &copy_crontab($_[0]->{'user'}); } else { &replace_file_line($_[0]->{'file'}, $_[0]->{'line'}); } @cron_jobs_cache = grep { $_ ne $_[0] } @cron_jobs_cache; &renumber($_[0]->{'file'}, $_[0]->{'line'}, -1); &renumber_index($_[0]->{'index'}, -1); } =head2 read_crontab(user) Return an array containing the lines of the cron table for some user. For internal use mainly. =cut sub read_crontab { local(@tab); &open_readfile(TAB, "$config{cron_dir}/$_[0]"); @tab = <TAB>; close(TAB); if (@tab >= 3 && $tab[0] =~ /DO NOT EDIT/ && $tab[1] =~ /^\s*#/ && $tab[2] =~ /^\s*#/) { @tab = @tab[3..$#tab]; } return @tab; } =head2 copy_crontab(user) Copy the cron temp file to that for this user. For internal use only. =cut sub copy_crontab { if (&is_readonly_mode()) { # Do nothing return undef; } local($pwd); if (&read_file_contents($cron_temp_file) =~ /\S/) { local $temp = &transname(); local $rv; if ($config{'cron_edit_command'}) { # fake being an editor # XXX does not work in translated command mode! local $notemp = &transname(); &open_tempfile(NO, ">$notemp"); &print_tempfile(NO, "No\n"); &print_tempfile(NO, "N\n"); &print_tempfile(NO, "no\n"); &close_tempfile(NO); $ENV{"VISUAL"} = $ENV{"EDITOR"} = "$module_root_directory/cron_editor.pl"; $ENV{"CRON_EDITOR_COPY"} = $cron_temp_file; system("chown $_[0] $cron_temp_file"); local $oldpwd = &get_current_dir(); chdir("/"); if ($single_user) { $rv = system($config{'cron_user_edit_command'}. " >$temp 2>&1 <$notemp"); } else { $rv = system( &user_sub($config{'cron_edit_command'},$_[0]). " >$temp 2>&1 <$notemp"); } unlink($notemp); chdir($oldpwd); } else { # use the cron copy command if ($single_user) { $rv = &execute_command( $config{'cron_user_copy_command'}, $cron_temp_file, $temp, $temp); } else { $rv = &execute_command( &user_sub($config{'cron_copy_command'}, $_[0]), $cron_temp_file, $temp, $temp); } } local $out = &read_file_contents($temp); unlink($temp); if ($rv || $out =~ /error/i) { local $cronin = &read_file_contents($cron_temp_file); &error(&text('ecopy', "<pre>$out</pre>", "<pre>$cronin</pre>")); } } else { # No more cron jobs left, so just delete if ($single_user) { &execute_command($config{'cron_user_delete_command'}); } else { &execute_command(&user_sub( $config{'cron_delete_command'}, $_[0])); } } unlink($cron_temp_file); } =head2 parse_job(job-line) Parse a crontab line into an array containing: active, mins, hrs, days, mons, weekdays, command =cut sub parse_job { local($job, $active) = ($_[0], 1); if ($job =~ /^#+\s*(.*)$/) { $active = 0; $job = $1; } $job =~ /^\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.*)$/; return ($active, $1, $2, $3, $4, $5, $6); } =head2 user_sub(command, user) Replace the string 'USER' in the command with the user name. For internal use only. =cut sub user_sub { local($tmp); $tmp = $_[0]; $tmp =~ s/USER/$_[1]/g; return $tmp; } =head2 list_allowed Returns a list of all Unix usernames who are allowed to use Cron. =cut sub list_allowed { local(@rv, $_); &open_readfile(ALLOW, $config{cron_allow_file}); while(<ALLOW>) { next if (/^\s*#/); chop; push(@rv, $_) if (/\S/); } close(ALLOW); return @rv; } =head2 list_denied Return a list of all Unix usernames who are not allowed to use Cron. =cut sub list_denied { local(@rv, $_); &open_readfile(DENY, $config{cron_deny_file}); while(<DENY>) { next if (/^\s*#/); chop; push(@rv, $_) if (/\S/); } close(DENY); return @rv; } =head2 save_allowed(user, user, ...) Save the list of allowed Unix usernames. =cut sub save_allowed { local($_); &open_tempfile(ALLOW, ">$config{cron_allow_file}"); foreach (@_) { &print_tempfile(ALLOW, $_,"\n"); } &close_tempfile(ALLOW); chmod(0444, $config{cron_allow_file}); } =head2 save_denied(user, user, ...) Save the list of denied Unix usernames. =cut sub save_denied { local($_); &open_tempfile(DENY, "> $config{cron_deny_file}"); foreach (@_) { &print_tempfile(DENY, $_,"\n"); } &close_tempfile(DENY); chmod(0444, $config{cron_deny_file}); } =head2 read_envs(user) Returns an array of "name value" strings containing the environment settings from the crontab for some user =cut sub read_envs { local(@tab, @rv, $_); @tab = &read_crontab($_[0]); foreach (@tab) { chop; s/#.*$//g; if (/^\s*(\S+)\s*=\s*(.*)$/) { push(@rv, "$1 $2"); } } return @rv; } =head2 save_envs(user, [name, value]*) Updates the cron file for some user with the given list of environment variables. All others in the file are removed. =cut sub save_envs { local($i, @tab, $line); @tab = &read_crontab($_[0]); open(TAB, ">$cron_temp_file"); for($i=1; $i<@_; $i+=2) { print TAB "$_[$i]=$_[$i+1]\n"; } foreach (@tab) { chop($line = $_); $line =~ s/#.*$//g; if ($line !~ /^\s*(\S+)\s*=\s*(.*)$/) { print TAB $_; } } close(TAB); &copy_crontab($_[0]); } =head2 expand_run_parts(directory) Internal function to convert a directory like /etc/cron.hourly into a list of scripts in that directory. =cut sub expand_run_parts { local $dir = $_[0]; $dir = "$config{'run_parts_dir'}/$dir" if ($config{'run_parts_dir'} && $dir !~ /^\//); opendir(DIR, &translate_filename($dir)); local @rv = readdir(DIR); closedir(DIR); @rv = grep { !/^\./ } @rv; @rv = map { $dir."/".$_ } @rv; return @rv; } =head2 is_run_parts(command) Returns the dir if some cron job runs a list of commands in some directory, like /etc/cron.hourly. Returns undef otherwise. =cut sub is_run_parts { local ($cmd) = @_; local $rp = $config{'run_parts'}; $cmd =~ s/\s*#.*$//; return $rp && $cmd =~ /$rp(.*)\s+(\-\-\S+\s+)*([a-z0-9\.\-\/_]+)(\s*\))?$/i ? $3 : undef; } =head2 can_edit_user(&access, user) Returns 1 if the Webmin user whose permissions are defined by the access hash ref can manage cron jobs for a given Unix user. =cut sub can_edit_user { local %umap; map { $umap{$_}++; } split(/\s+/, $_[0]->{'users'}) if ($_[0]->{'mode'} == 1 || $_[0]->{'mode'} == 2); if ($_[0]->{'mode'} == 1 && !$umap{$_[1]} || $_[0]->{'mode'} == 2 && $umap{$_[1]}) { return 0; } elsif ($_[0]->{'mode'} == 3) { return $remote_user eq $_[1]; } elsif ($_[0]->{'mode'} == 4) { local @u = getpwnam($_[1]); return (!$_[0]->{'uidmin'} || $u[2] >= $_[0]->{'uidmin'}) && (!$_[0]->{'uidmax'} || $u[2] <= $_[0]->{'uidmax'}); } elsif ($_[0]->{'mode'} == 5) { local @u = getpwnam($_[1]); return $u[3] == $_[0]->{'users'}; } else { return 1; } } =head2 list_cron_specials() Returns a list of the names of special cron times, prefixed by an @ in crontab =cut sub list_cron_specials { return ('hourly', 'daily', 'weekly', 'monthly', 'yearly', 'reboot'); } =head2 get_times_input(&job, [nospecial], [width-in-cols], [message]) Returns HTML for selecting the schedule for a cron job, defined by the first parameter which must be a hash ref returned by list_cron_jobs. Suitable for use inside a ui_table_start/end =cut sub get_times_input { return &theme_get_times_input(@_) if (defined(&theme_get_times_input)); my ($job, $nospecial, $width, $msg) = @_; $width ||= 2; # Javascript to disable and enable fields my $rv = <<EOF; <script> function enable_cron_fields(name, form, ena) { var els = form.elements[name]; els.disabled = !ena; for(i=0; i<els.length; i++) { els[i].disabled = !ena; } change_special_mode(form, 0); } function change_special_mode(form, special) { form.special_def[0].checked = special; form.special_def[1].checked = !special; } </script> EOF if ($config{'vixie_cron'} && (!$nospecial || $job->{'special'})) { # Allow selection of special @ times my $sp = $job->{'special'} eq 'midnight' ? 'daily' : $job->{'special'} eq 'annually' ? 'yearly' : $job->{'special'}; my $specialsel = &ui_select("special", $sp, [ map { [ $_, $text{'edit_special_'.$_} ] } &list_cron_specials() ], 1, 0, 0, 0, "onChange='change_special_mode(form, 1)'"); $rv .= &ui_table_row($msg, &ui_radio("special_def", $job->{'special'} ? 1 : 0, [ [ 1, $text{'edit_special1'}." ".$specialsel ], [ 0, $text{'edit_special0'} ] ]), $msg ? $width-1 : $width); } # Section for time selections my $table = &ui_columns_start([ $text{'edit_mins'}, $text{'edit_hours'}, $text{'edit_days'}, $text{'edit_months'}, $text{'edit_weekdays'} ], 100); my @mins = (0..59); my @hours = (0..23); my @days = (1..31); my @months = map { $text{"month_$_"}."=".$_ } (1 .. 12); my @weekdays = map { $text{"day_$_"}."=".$_ } (0 .. 6); my %arrmap = ( 'mins' => \@mins, 'hours' => \@hours, 'days' => \@days, 'months' => \@months, 'weekdays' => \@weekdays ); my @cols; foreach my $arr ("mins", "hours", "days", "months", "weekdays") { # Find out which ones are being used my %inuse; my $min = ($arr =~ /days|months/ ? 1 : 0); my @arrlist = @{$arrmap{$arr}}; my $max = $min+scalar(@arrlist)-1; foreach my $w (split(/,/ , $job->{$arr})) { if ($w eq "*") { # all values for($j=$min; $j<=$max; $j++) { $inuse{$j}++; } } elsif ($w =~ /^\*\/(\d+)$/) { # only every Nth for($j=$min; $j<=$max; $j+=$1) { $inuse{$j}++; } } elsif ($w =~ /^(\d+)-(\d+)\/(\d+)$/) { # only every Nth of some range for($j=$1; $j<=$2; $j+=$3) { $inuse{int($j)}++; } } elsif ($w =~ /^(\d+)-(\d+)$/) { # all of some range for($j=$1; $j<=$2; $j++) { $inuse{int($j)}++; } } else { # One value $inuse{int($w)}++; } } if ($job->{$arr} eq "*") { %inuse = ( ); } # Output selection list my $dis = $arr eq "mins" && $hourly_only; my $col = &ui_radio( "all_$arr", $job->{$arr} eq "*" || $job->{$arr} eq "" ? 1 : 0, [ [ 1, $text{'edit_all'}."<br>", "onClick='enable_cron_fields(\"$arr\", form, 0)'" ], [ 0, $text{'edit_selected'}."<br>", "onClick='enable_cron_fields(\"$arr\", form, 1)'" ] ], $dis); $col .= "<table> <tr>\n"; for(my $j=0; $j<@arrlist; $j+=($arr eq "mins" && $hourly_only ? 60 : 12)) { my $jj = $j+($arr eq "mins" && $hourly_only ? 59 : 11); if ($jj >= @arrlist) { $jj = @arrlist - 1; } my @sec = @arrlist[$j .. $jj]; my @opts; foreach my $v (@sec) { if ($v =~ /^(.*)=(.*)$/) { push(@opts, [ $2, $1 ]); } else { push(@opts, [ $v, $v ]); } } my $dis = $job->{$arr} eq "*" || $job->{$arr} eq ""; $col .= "<td valign=top>". &ui_select($arr, [ keys %inuse ], \@opts, @sec > 12 ? ($arr eq "mins" && $hourly_only ? 1 : 12) : scalar(@sec), $arr eq "mins" && $hourly_only ? 0 : 1, 0, $dis). "</td>\n"; } $col .= "</tr></table>\n"; push(@cols, $col); } $table .= &ui_columns_row(\@cols, [ "valign=top", "valign=top", "valign=top", "valign=top", "valign=top" ]); $table .= &ui_columns_end(); $table .= $text{'edit_ctrl'}; $rv .= &ui_table_row(undef, $table, $width); return $rv; } =head2 show_times_input(&job, [nospecial]) Print HTML for inputs for selecting the schedule for a cron job, defined by the first parameter which must be a hash ref returned by list_cron_jobs. This must be used inside a <table>, as the HTML starts and ends with <tr> tags. =cut sub show_times_input { return &theme_show_times_input(@_) if (defined(&theme_show_times_input)); local $job = $_[0]; if ($config{'vixie_cron'} && (!$_[1] || $_[0]->{'special'})) { # Allow selection of special @ times print "<tr $cb> <td colspan=6>\n"; printf "<input type=radio name=special_def value=1 %s> %s\n", $job->{'special'} ? "checked" : "", $text{'edit_special1'}; print "<select name=special onChange='change_special_mode(form, 1)'>\n"; local $s; local $sp = $job->{'special'} eq 'midnight' ? 'daily' : $job->{'special'} eq 'annually' ? 'yearly' : $job->{'special'}; foreach $s ('hourly', 'daily', 'weekly', 'monthly', 'yearly', 'reboot'){ printf "<option value=%s %s>%s</option>\n", $s, $sp eq $s ? "selected" : "", $text{'edit_special_'.$s}; } print "</select>\n"; printf "<input type=radio name=special_def value=0 %s> %s\n", $job->{'special'} ? "" : "checked", $text{'edit_special0'}; print "</td></tr>\n"; } # Javascript to disable and enable fields print <<EOF; <script> function enable_cron_fields(name, form, ena) { var els = form.elements[name]; els.disabled = !ena; for(i=0; i<els.length; i++) { els[i].disabled = !ena; } change_special_mode(form, 0); } function change_special_mode(form, special) { form.special_def[0].checked = special; form.special_def[1].checked = !special; } </script> EOF print "<tr $tb>\n"; print "<td><b>$text{'edit_mins'}</b></td> <td><b>$text{'edit_hours'}</b></td> ", "<td><b>$text{'edit_days'}</b></td> <td><b>$text{'edit_months'}</b></td>", "<td><b>$text{'edit_weekdays'}</b></td> </tr> <tr $cb>\n"; local @mins = (0..59); local @hours = (0..23); local @days = (1..31); local @months = map { $text{"month_$_"}."=".$_ } (1 .. 12); local @weekdays = map { $text{"day_$_"}."=".$_ } (0 .. 6); foreach $arr ("mins", "hours", "days", "months", "weekdays") { # Find out which ones are being used local %inuse; local $min = ($arr =~ /days|months/ ? 1 : 0); local $max = $min+scalar(@$arr)-1; foreach $w (split(/,/ , $job->{$arr})) { if ($w eq "*") { # all values for($j=$min; $j<=$max; $j++) { $inuse{$j}++; } } elsif ($w =~ /^\*\/(\d+)$/) { # only every Nth for($j=$min; $j<=$max; $j+=$1) { $inuse{$j}++; } } elsif ($w =~ /^(\d+)-(\d+)\/(\d+)$/) { # only every Nth of some range for($j=$1; $j<=$2; $j+=$3) { $inuse{int($j)}++; } } elsif ($w =~ /^(\d+)-(\d+)$/) { # all of some range for($j=$1; $j<=$2; $j++) { $inuse{int($j)}++; } } else { # One value $inuse{int($w)}++; } } if ($job->{$arr} eq "*") { undef(%inuse); } # Output selection list print "<td valign=top>\n"; printf "<input type=radio name=all_$arr value=1 %s %s %s> %s<br>\n", $arr eq "mins" && $hourly_only ? "disabled" : "", $job->{$arr} eq "*" || $job->{$arr} eq "" ? "checked" : "", "onClick='enable_cron_fields(\"$arr\", form, 0)'", $text{'edit_all'}; printf "<input type=radio name=all_$arr value=0 %s %s> %s<br>\n", $job->{$arr} eq "*" || $job->{$arr} eq "" ? "" : "checked", "onClick='enable_cron_fields(\"$arr\", form, 1)'", $text{'edit_selected'}; print "<table> <tr>\n"; for($j=0; $j<@$arr; $j+=($arr eq "mins" && $hourly_only ? 60 : 12)) { $jj = $j+($arr eq "mins" && $hourly_only ? 59 : 11); if ($jj >= @$arr) { $jj = @$arr - 1; } @sec = @$arr[$j .. $jj]; printf "<td valign=top><select %s size=%d name=$arr %s %s>\n", $arr eq "mins" && $hourly_only ? "" : "multiple", @sec > 12 ? ($arr eq "mins" && $hourly_only ? 1 : 12) : scalar(@sec), $job->{$arr} eq "*" || $job->{$arr} eq "" ? "disabled" : "", "onChange='change_special_mode(form, 0)'"; foreach $v (@sec) { if ($v =~ /^(.*)=(.*)$/) { $disp = $1; $code = $2; } else { $disp = $code = $v; } printf "<option value=\"$code\" %s>$disp</option>\n", $inuse{$code} ? "selected" : ""; } print "</select></td>\n"; } print "</tr></table></td>\n"; } print "</tr> <tr $cb> <td colspan=5>$text{'edit_ctrl'}</td> </tr>\n"; } =head2 parse_times_input(&job, &in) Parses inputs from the form generated by show_times_input, and updates a cron job hash ref. The in parameter must be a hash ref as generated by the ReadParse function. =cut sub parse_times_input { local $job = $_[0]; local %in = %{$_[1]}; local @pers = ("mins", "hours", "days", "months", "weekdays"); local $arr; if ($in{'special_def'}) { # Job time is a special period foreach $arr (@pers) { delete($job->{$arr}); } $job->{'special'} = $in{'special'}; } else { # User selection of times foreach $arr (@pers) { if ($in{"all_$arr"}) { # All mins/hrs/etc.. chosen $job->{$arr} = "*"; } elsif (defined($in{$arr})) { # Need to work out and simplify ranges selected local (@range, @newrange, $i); @range = split(/\0/, $in{$arr}); @range = sort { $a <=> $b } @range; local $start = -1; for($i=0; $i<@range; $i++) { if ($i && $range[$i]-1 == $range[$i-1]) { # ok.. looks like a range if ($start < 0) { $start = $i-1; } } elsif ($start < 0) { # Not in a range at all push(@newrange, $range[$i]); } else { # End of the range.. add it $newrange[@newrange - 1] = "$range[$start]-".$range[$i-1]; push(@newrange, $range[$i]); $start = -1; } } if ($start >= 0) { # Reached the end while in a range $newrange[@newrange - 1] = "$range[$start]-".$range[$i-1]; } $job->{$arr} = join(',' , @newrange); } else { &error(&text('save_enone', $text{"edit_$arr"})); } } delete($job->{'special'}); } } =head2 show_range_input(&job) Given a cron job, prints fields for selecting it's run date range. =cut sub show_range_input { local ($job) = @_; local $has_start = $job->{'start'}; local $rng; $rng = &text('range_start', &ui_date_input( $job->{'start'}->[0], $job->{'start'}->[1], $job->{'start'}->[2], "range_start_day", "range_start_month", "range_start_year"))."\n". &date_chooser_button( "range_start_day", "range_start_month", "range_start_year")."\n". &text('range_end', &ui_date_input( $job->{'end'}->[0], $job->{'end'}->[1], $job->{'end'}->[2], "range_end_day", "range_end_month", "range_end_year"))."\n". &date_chooser_button( "range_end_day", "range_end_month", "range_end_year")."\n"; print &ui_oneradio("range_def", 1, $text{'range_all'}, !$has_start), "<br>\n"; print &ui_oneradio("range_def", 0, $rng, $has_start),"\n"; } =head2 parse_range_input(&job, &in) Updates the job object with the specified date range. May call &error for invalid inputs. =cut sub parse_range_input { local ($job, $in) = @_; if ($in->{'range_def'}) { # No range used delete($job->{'start'}); delete($job->{'end'}); } else { # Validate and store range foreach my $r ("start", "end") { eval { timelocal(0, 0, 0, $in->{'range_'.$r.'_day'}, $in->{'range_'.$r.'_month'}-1, $in->{'range_'.$r.'_year'}-1900) }; if ($@) { &error($text{'range_e'.$r}." ".$@); } $job->{$r} = [ $in->{'range_'.$r.'_day'}, $in->{'range_'.$r.'_month'}, $in->{'range_'.$r.'_year'} ]; } } } @cron_month = ( 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec' ); @cron_weekday = ( 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ); =head2 fix_names(&cron) Convert day and month names to numbers. For internal use when parsing the crontab file. =cut sub fix_names { local ($m, $w); local @mts = split(/,/, $_[0]->{'months'}); foreach $m (@mts) { local $mi = &indexof(lc($m), @cron_month); $m = $mi+1 if ($mi >= 0); } $_[0]->{'months'} = join(",", @mts); local @wds = split(/,/, $_[0]->{'weekdays'}); foreach $w (@wds) { local $di = &indexof(lc($w), @cron_weekday); $w = $di if ($di >= 0); $w = 0 if ($w == 7); } $_[0]->{'weekdays'} = join(",", @wds); } =head2 create_wrapper(wrapper-path, module, script) Creates a wrapper script which calls a script in some module's directory with the proper webmin environment variables set. This should always be used when setting up a cron job, instead of attempting to run a command in the module directory directly. The parameters are : =item wrapper-path - Full path to the wrapper to create, like /etc/webmin/yourmodule/foo.pl =item module - Module containing the real script to call. =item script - Program within that module for the wrapper to run. =cut sub create_wrapper { local $perl_path = &get_perl_path(); &open_tempfile(CMD, ">$_[0]"); &print_tempfile(CMD, <<EOF #!$perl_path open(CONF, "$config_directory/miniserv.conf") || die "Failed to open $config_directory/miniserv.conf : \$!"; while(<CONF>) { \$root = \$1 if (/^root=(.*)/); } close(CONF); \$root || die "No root= line found in $config_directory/miniserv.conf"; \$ENV{'PERLLIB'} = "\$root"; \$ENV{'WEBMIN_CONFIG'} = "$ENV{'WEBMIN_CONFIG'}"; \$ENV{'WEBMIN_VAR'} = "$ENV{'WEBMIN_VAR'}"; EOF ); if ($gconfig{'os_type'} eq 'windows') { # On windows, we need to chdir to the drive first, and use system &print_tempfile(CMD, "if (\$root =~ /^([a-z]:)/i) {\n"); &print_tempfile(CMD, " chdir(\"\$1\");\n"); &print_tempfile(CMD, " }\n"); &print_tempfile(CMD, "chdir(\"\$root/$_[1]\");\n"); &print_tempfile(CMD, "exit(system(\"\$root/$_[1]/$_[2]\", \@ARGV));\n"); } else { # Can use exec on Unix systems if ($_[1]) { &print_tempfile(CMD, "chdir(\"\$root/$_[1]\");\n"); &print_tempfile(CMD, "exec(\"\$root/$_[1]/$_[2]\", \@ARGV) || die \"Failed to run \$root/$_[1]/$_[2] : \$!\";\n"); } else { &print_tempfile(CMD, "chdir(\"\$root\");\n"); &print_tempfile(CMD, "exec(\"\$root/$_[2]\", \@ARGV) || die \"Failed to run \$root/$_[2] : \$!\";\n"); } } &close_tempfile(CMD); chmod(0755, $_[0]); } =head2 cron_file(&job) Returns the file that a cron job is in, or will be in when it is created based on the username. =cut sub cron_file { return $_[0]->{'file'} || $config{'add_file'} || "$config{'cron_dir'}/$_[0]->{'user'}"; } =head2 when_text(&job, [upper-case-first]) Returns a human-readable text string describing when a cron job is run. =cut sub when_text { local $pfx = $_[1] ? "uc" : ""; if ($_[0]->{'interval'}) { return &text($pfx.'when_interval', $_[0]->{'interval'}); } elsif ($_[0]->{'special'}) { $pfx = $_[1] ? "" : "lc"; return $text{$pfx.'edit_special_'.$_[0]->{'special'}}; } elsif ($_[0]->{'mins'} eq '*' && $_[0]->{'hours'} eq '*' && $_[0]->{'days'} eq '*' && $_[0]->{'months'} eq '*' && $_[0]->{'weekdays'} eq '*') { return $text{$pfx.'when_min'}; } elsif ($_[0]->{'mins'} =~ /^\d+$/ && $_[0]->{'hours'} eq '*' && $_[0]->{'days'} eq '*' && $_[0]->{'months'} eq '*' && $_[0]->{'weekdays'} eq '*') { return &text($pfx.'when_hour', $_[0]->{'mins'}); } elsif ($_[0]->{'mins'} =~ /^\d+$/ && $_[0]->{'hours'} =~ /^\d+$/ && $_[0]->{'days'} eq '*' && $_[0]->{'months'} eq '*' && $_[0]->{'weekdays'} eq '*') { return &text($pfx.'when_day', sprintf("%2.2d", $_[0]->{'mins'}), $_[0]->{'hours'}); } elsif ($_[0]->{'mins'} =~ /^\d+$/ && $_[0]->{'hours'} =~ /^\d+$/ && $_[0]->{'days'} =~ /^\d+$/ && $_[0]->{'months'} eq '*' && $_[0]->{'weekdays'} eq '*') { return &text($pfx.'when_month', sprintf("%2.2d", $_[0]->{'mins'}), $_[0]->{'hours'}, $_[0]->{'days'}); } elsif ($_[0]->{'mins'} =~ /^\d+$/ && $_[0]->{'hours'} =~ /^\d+$/ && $_[0]->{'days'} eq '*' && $_[0]->{'months'} eq '*' && $_[0]->{'weekdays'} =~ /^\d+$/) { return &text($pfx.'when_weekday', sprintf("%2.2d", $_[0]->{'mins'}), $_[0]->{'hours'}, $text{"day_".$_[0]->{'weekdays'}}); } else { return &text($pfx.'when_cron', join(" ", $_[0]->{'mins'}, $_[0]->{'hours'}, $_[0]->{'days'}, $_[0]->{'months'}, $_[0]->{'weekdays'})); } } =head2 can_use_cron(user) Returns 1 if some user is allowed to use cron, based on cron.allow and cron.deny files. =cut sub can_use_cron { local ($user) = @_; defined(getpwnam($user)) || return 0; # User does not exist local $err; if (-r $config{cron_allow_file}) { local @allowed = &list_allowed(); if (&indexof($user, @allowed) < 0 && &indexof("all", @allowed) < 0) { $err = 1; } } elsif (-r $config{cron_deny_file}) { local @denied = &list_denied(); if (&indexof($user, @denied) >= 0 || &indexof("all", @denied) >= 0) { $err = 1; } } elsif ($config{cron_deny_all} == 0) { $err = 1; } elsif ($config{cron_deny_all} == 1) { if ($in{user} ne "root") { $err = 1; } } return !$err; } =head2 swap_cron_jobs(&job1, &job2) Swaps two Cron jobs, which must be in the same file, identified by their hash references as returned by list_cron_jobs. =cut sub swap_cron_jobs { if ($_[0]->{'type'} == 0) { &copy_cron_temp($_[0]); local $lref = &read_file_lines($cron_temp_file); ($lref->[$_[0]->{'line'}], $lref->[$_[1]->{'line'}]) = ($lref->[$_[1]->{'line'}], $lref->[$_[0]->{'line'}]); &flush_file_lines(); &copy_crontab($_[0]->{'user'}); } else { local $lref = &read_file_lines($_[0]->{'file'}); ($lref->[$_[0]->{'line'}], $lref->[$_[1]->{'line'}]) = ($lref->[$_[1]->{'line'}], $lref->[$_[0]->{'line'}]); &flush_file_lines(); } } =head2 find_cron_process(&job, [&procs]) Finds the running process that was launched from a cron job. The parameters are: =item job - A cron job hash reference =item procs - An optional array reference of running process hash refs =cut sub find_cron_process { local @procs; if ($_[1]) { @procs = @{$_[1]}; } else { &foreign_require("proc", "proc-lib.pl"); @procs = &proc::list_processes(); } local $rpd = &is_run_parts($_[0]->{'command'}); local @exp = $rpd ? &expand_run_parts($rpd) : (); local $cmd = $exp[0] || $_[0]->{'command'}; $cmd =~ s/^\s*\[.*\]\s+\&\&\s+//; $cmd =~ s/^\s*\[.*\]\s+\|\|\s+//; while($cmd =~ s/(\d*)(<|>)((\/\S+)|&\d+)\s*$//) { } $cmd =~ s/^\((.*)\)\s*$/$1/; $cmd =~ s/\s+$//; if ($config{'match_mode'} == 1) { $cmd =~ s/\s.*$//; } ($proc) = grep { $_->{'args'} =~ /\Q$cmd\E/ && (!$config{'match_user'} || $_->{'user'} eq $_[0]->{'user'}) } @procs; if (!$proc && $cmd =~ /^$config_directory\/(.*\.pl)(.*)$/) { # Must be a Webmin wrapper $cmd = "$root_directory/$1$2"; ($proc) = grep { $_->{'args'} =~ /\Q$cmd\E/ && (!$config{'match_user'} || $_->{'user'} eq $_[0]->{'user'}) } @procs; } return $proc; } =head2 find_cron_job(command, [&jobs], [user]) Returns the cron job object that runs some command (perhaps with redirection) =cut sub find_cron_job { my ($cmd, $jobs, $user) = @_; if (!$jobs) { $jobs = [ &list_cron_jobs() ]; } $user ||= "root"; my @rv = grep { $_->{'user'} eq $user && $_->{'command'} =~ /(^|[ \|\&;\/])\Q$cmd\E($|[ \|\&><;])/ } @$jobs; return wantarray ? @rv : $rv[0]; } =head2 extract_input(command) Given a line formatted like I<command%input>, returns the command and input parts, taking any escaping into account. =cut sub extract_input { local ($cmd) = @_; $cmd =~ s/\\%/\0/g; local ($cmd, $input) = split(/\%/, $cmd, 2); $cmd =~ s/\0/\\%/g; $input =~ s/\0/\\%/g; return ($cmd, $input); } =head2 convert_range(&job) Given a cron job that uses range.pl, work out the date range and update the job object command. Mainly for internal use. =cut sub convert_range { local ($job) = @_; local ($cmd, $input) = &extract_input($job->{'command'}); if ($cmd =~ /^\Q$range_cmd\E\s+(\d+)\-(\d+)\-(\d+)\s+(\d+)\-(\d+)\-(\d+)\s+(.*)$/) { # Looks like a range command $job->{'start'} = [ $1, $2, $3 ]; $job->{'end'} = [ $4, $5, $6 ]; $job->{'command'} = $7; $job->{'command'} =~ s/\\(.)/$1/g; if ($input) { $job->{'command'} .= '%'.$input; } return 1; } return 0; } =head2 unconvert_range(&job) Give a cron job with start and end fields, updates the command to wrap it in range.pl with those dates as parameters. =cut sub unconvert_range { local ($job) = @_; if ($job->{'start'}) { # Need to add range command local ($cmd, $input) = &extract_input($job->{'command'}); $job->{'command'} = $range_cmd." ".join("-", @{$job->{'start'}})." ". join("-", @{$job->{'end'}})." ". quotemeta($cmd); if ($input) { $job->{'command'} .= '%'.$input; } delete($job->{'start'}); delete($job->{'end'}); &copy_source_dest("$module_root_directory/range.pl", $range_cmd); &set_ownership_permissions(undef, undef, 0755, $range_cmd); return 1; } return 0; } =head2 convert_comment(&job) Given a cron job with a # comment after the command, sets the comment field =cut sub convert_comment { local ($job) = @_; if ($job->{'command'} =~ /^(.*\S)\s*#([^#]*)$/) { $job->{'command'} = $1; $job->{'comment'} = $2; return 1; } return 0; } =head2 unconvert_comment(&job) Adds an comment back to the command in a cron job, based on the comment field of the given hash reference. =cut sub unconvert_comment { local ($job) = @_; if ($job->{'comment'} =~ /\S/) { $job->{'command'} .= " #".$job->{'comment'}; return 1; } return 0; } =head2 check_cron_config Returns an error message if the cron config doesn't look valid, or some needed command is missing. =cut sub check_cron_config { # Check for single file and getter command if ($config{'single_file'} && !-r $config{'single_file'}) { return &text('index_esingle', "<tt>$config{'single_file'}</tt>"); } if ($config{'cron_get_command'} =~ /^(\S+)/ && !&has_command("$1")) { return &text('index_ecmd', "<tt>$1</tt>"); } # Check for directory local $fcron = ($config{'cron_dir'} =~ /\/fcron$/); if (!$single_user && !$config{'single_file'} && !$fcron && !-d $config{'cron_dir'}) { return &text('index_ecrondir', "<tt>$config{'cron_dir'}</tt>"); } return undef; } =head2 check_cron_config_or_error Calls check_cron_config, and then error if any problems were detected. =cut sub check_cron_config_or_error { local $err = &check_cron_config(); if ($err) { &error(&text('index_econfigcheck', $err)); } } =head2 cleanup_temp_files Called from cron to delete old files in the Webmin /tmp directory =cut sub cleanup_temp_files { # Don't run if disabled if (!$gconfig{'tempdelete_days'}) { print STDERR "Temp file clearing is disabled\n"; return; } if ($gconfig{'tempdir'} && !$gconfig{'tempdirdelete'}) { print STDERR "Temp file clearing is not done for the custom directory $gconfig{'tempdir'}\n"; return; } local $tempdir = &transname(); $tempdir =~ s/\/([^\/]+)$//; if (!$tempdir || $tempdir eq "/") { $tempdir = "/tmp/.webmin"; } local $cutoff = time() - $gconfig{'tempdelete_days'}*24*60*60; opendir(DIR, $tempdir); foreach my $f (readdir(DIR)) { next if ($f eq "." || $f eq ".."); local @st = lstat("$tempdir/$f"); if ($st[9] < $cutoff) { &unlink_file("$tempdir/$f"); } } closedir(DIR); } 1;
rcuvgd/Webmin22.01.2016
cron/cron-lib.pl
Perl
bsd-3-clause
42,244
#!/usr/bin/perl # The MIT License # Copyright (c) 2014 Genome Research Ltd. # Author: Rob Davies <rmd+sam@sanger.ac.uk> # 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. # Import references into a cram reference cache from fasta files. # See below __END__ for POD documentation. use strict; use warnings; use Digest::MD5; use Getopt::Long; use File::Find; use File::Temp qw(tempfile); use File::Spec::Functions; use File::Path 'make_path'; use IO::Handle; $| = 1; # Directory where the cache will be built my $root_dir; # Number of subdirectories to make below $root_dir # Each subdir will eat up two hex digits of the file MD5 my $subdirs = 2; # Directory tree to search when using the -find option my $find = ''; # How much data to read before spilling to a file my $max_acc = 256 * 1024 * 1024; my $usage = "Usage: $0 -root <dir> [-subdirs <n>] input1.fasta ...\n $0 -root <dir> [-subdirs <n>] -find <dir>\n"; # Deal with options GetOptions("root=s" => \$root_dir, "subdirs=s" => \$subdirs, "find=s" => \$find) || die $usage; unless ($root_dir && $subdirs =~ /^\d+$/) { die $usage; } if ($subdirs >= 16) { die "$0: Error: -subdirs should be less than 15.\n"; } # Regexp to convert a hex MD5 to a list of $subdirs subdirectory names, the # remainder making the filename in the leaf directory my $dest_regexp = "(..)" x $subdirs . "(" . ".." x (16 - $subdirs) . ")"; my $dest_re = qr/$dest_regexp/; # Ensure $root_dir exists unless (-e $root_dir) { make_path($root_dir); } if ($find) { # Find mode - search a directory tree for anything that looks like a # fasta file. Any that are found will be put into the new cache, if # they are not already there. find({ wanted => sub { find_files($File::Find::name, $root_dir, $dest_re, $max_acc); }, no_chdir => 1, }, $find); } elsif (@ARGV) { # If a list of files was given on the command line, go through them # and try to add each one. foreach my $name (@ARGV) { open(my $fh, '<', $name) || die "Couldn't open $name: $!\n"; process_file($name, $fh, $root_dir, $dest_re, $max_acc); close($fh) || die "Error closing $name: $!\n"; } } else { # Otherwise read from STDIN process_file('STDIN', \*STDIN, $root_dir, $dest_re, $max_acc); } exit; sub find_files { my ($name, $root_dir, $dest_re, $max_acc) = @_; # See if $name is a candidate file my $fh; return if ($name =~ /~$/); # Ignore backup files return unless (-f $name && -r _); # Ignore non-regular and unreadable files # Inspect the first two lines of the candidate my $buffer; open($fh, '<', $name) || die "Couldn't open $name: $!\n"; read($fh, $buffer, 8192); # Should be enough to find the header & sequence close($fh) || die "Error closing $name: $!\n"; my ($l1, $l2) = split(/\n/, $buffer); # Check for fasta-like content return unless ($l1 && $l1 =~ /^>\S+/); return unless ($l2 && $l2 =~ /^[ACGTMRWSYKVHDBNacgtmrwsykvhdbn]+$/); # Looks like a fasta file, so process it open($fh, '<', $name) || die "Couldn't open $name: $!\n"; process_file($name, $fh, $root_dir, $dest_re, $max_acc); close($fh) || die "Error closing $name: $!\n"; } sub process_file { my ($name, $in_fh, $root_dir, $dest_re, $max_acc) = @_; # Process the fasta file $in_fh. Each entry in the file is read, and # the MD5 calculated as described in the SAM specification (i.e. # all uppercased with whitespace stripped out). The MD5 is then # split using $dest_re to convert it into the path name for the entry # in the cache. If the path is not already present, the entry (in # uppercased and stripped form) is saved into the cache. # Entries shorter that $max_acc will be kept in memory. For fasta files # with lots of short entries this can save a lot of unnecessary writing # if the data is already in the cache. Anything longer # gets written out to a file to keep memory consumption under control. # The temporary files have to be made in $root_dir, as the final # destination is not known until the entry has been completely read. my $id; # Name of current fasta entry my $ctx; # MD5 context my $acc = ''; # The accumulated sequence my $tmpfile; # Temporary file name my $tmpfh; # Temporary file handle my $extra = 1024; # Extra space to pre-allocate to account for reading # 1 line past $max_acc vec($acc, $max_acc + $extra, 8) = 1; # Pre-allocate some space $acc = ''; # Use an eval block so any stray temporary file can be cleaned up before # exiting. eval { print "Reading $name ...\n"; for (;;) { # Error catching form of while (<>) {...} undef($!); last if (eof($in_fh)); # Needed if last line isn't terminated unless (defined($_ = readline($in_fh))) { die "Error reading $name: $!" if $!; last; # EOF } if (/^>(\S+)/) { # Found a fasta header if ($ctx) { # Finish previous entry, if there is one finish_entry($id, $ctx, \$acc, $tmpfh, $tmpfile, $root_dir, $dest_re); undef($tmpfile); $acc = ''; } $id = $1; $ctx = Digest::MD5->new(); } else { unless ($id) { die "Found sequence with no header\n"; } # Read some sequence chomp; s/\s+//g; if ($_) { $_ = uc($_); $acc .= $_; $ctx->add($_); if (length($acc) > $max_acc) { # Spill long sequences out to a temporary file in # $root_dir. unless ($tmpfile) { ($tmpfh, $tmpfile) = tempfile(DIR => $root_dir, SUFFIX => '.tmp'); } print $tmpfh $acc || die "Error writing to $tmpfile: $!\n"; $acc = ''; } } } } if ($ctx) { # Finish off the last entry finish_entry($id, $ctx, \$acc, $tmpfh, $tmpfile, $root_dir, $dest_re); undef($tmpfile); } }; my $err = $@; if ($tmpfile) { unlink($tmpfile); } if ($err) { die $err; } } sub finish_entry { my ($id, $ctx, $acc_ref, $tmpfh, $tmpfile, $root_dir, $dest_re) = @_; # Finish writing an entry my $digest = $ctx->hexdigest; # Get the destination directory and filename my @segs = $digest =~ /$dest_re/; my $dest_dir = (@segs > 1 ? catdir($root_dir, @segs[0..($#segs - 1)]) : $root_dir); my $dest = catfile($dest_dir, $segs[-1]); # Make the destination dir if necessary unless (-e $dest_dir) { make_path($dest_dir); } if (-e $dest) { # If the file is already present, there's nothing to do apart from # remove the temporary file if it was made. print "Already exists: $digest $id\n"; if ($tmpfile) { close($tmpfh) || die "Error closing $tmpfile: $!\n"; unlink($tmpfile) || die "Couldn't remove $tmpfile: $!\n"; } } else { # Need to add the data to the cache. unless ($tmpfile) { # If the data hasn't been written already, it needs to be done # now. Write to a temp file in $dest_dir so if it goes wrong # we won't leave a file with the right name but half-written # content. ($tmpfh, $tmpfile) = tempfile(DIR => $dest_dir, SUFFIX => '.tmp'); } # Assert that the $tmpfile is now set unless ($tmpfile) { die "Error: Didn't make a temp file"; } eval { # Flush out any remaining data if ($$acc_ref) { print $tmpfh $$acc_ref || die "Error writing to $tmpfile: $!\n"; } # Paranoid file close $tmpfh->flush() || die "Error flushing to $tmpfile: $!\n"; $tmpfh->sync() || die "Error syncing $tmpfile: $!\n"; close($tmpfh) || die "Error writing to $tmpfile: $!\n"; }; if ($@) { # Attempt to clean up if writing failed my $save = $@; unlink($tmpfile) || warn "Couldn't remove $tmpfile: $!"; die $save; } # Finished writing, and everything is flushed as far as possible # so rename the temp file print "$dest $id\n"; rename($tmpfile, $dest) || die "Error moving $tmpfile to $dest: $!\n"; } } __END__ =head1 NAME seq_cache_populate.pl =head1 SYNOPSIS seq_cache_populate.pl -root <dir> [-subdirs <n>] input1.fasta ... seq_cache_populate.pl -root <dir> [-subdirs <n>] -find <dir> =head1 DESCRIPTION Import references into a cram reference cache from fasta files. When run with a list of fasta files, this program reads the files and stores the sequences within it in the reference cache under directory <dir>. The sequences in the cache are stored with names based on the MD5 checksum of the sequence. By default, sequences are stored in a hierarchy two directories deep, to keep the number of items in a single directory to a reasonable number. This depth can be chaged using the -subdirs option. If the -find option is used, the program will scan the given directory tree. Any files that appear to be fasta (by looking for a first line starting with '>' followed by somthing that looks like DNA sequence) will be read and added to the reference cache. The traversal will ignore symbolic links. Samtools/htslib can be made to use the cache by appropriate setting of the REF_PATH environment varaiable. For example, if seq_cache_populate was run using options '-root /tmp/ref_cache -subdirs 2', setting REF_PATH to '/tmp/ref_cache/%2s/%2s/%s' should allow samtools to find the references that it stored. =head1 AUTHOR Rob Davies. =cut
ENCODE-DCC/chip-seq-pipeline
dnanexus/shell/resources/usr/local/bin/samtools-1.0/bin/seq_cache_populate.pl
Perl
mit
10,785
package DDG::GoodieRole::NumberStyle; # ABSTRACT: An object representing a particular numerical notation. use strict; use warnings; use Moo; use Math::BigFloat; has [qw(id decimal thousands)] => ( is => 'ro', ); has exponential => ( is => 'ro', default => sub { 'e' }, ); has number_regex => ( is => 'lazy', ); sub _build_number_regex { my $self = shift; my ($decimal, $thousands, $exponential) = ($self->decimal, $self->thousands, $self->exponential); return qr/-?[\d_ \Q$decimal\E\Q$thousands\E]+(?:\Q$exponential\E-?\d+)?/i; } sub understands { my ($self, $number) = @_; my ($decimal, $thousands) = ($self->decimal, $self->thousands); # How do we know if a number is reasonable for this style? # This assumes the exponentials are not included to give better answers. return ( # The number must contain only things we understand: numerals and separators for this style. $number =~ /^-?(|\d|_| |\Q$thousands\E|\Q$decimal\E)+$/ && ( # The number is not required to contain thousands separators $number !~ /\Q$thousands\E/ || ( # But if the number does contain thousands separators, they must delimit exactly 3 numerals. $number !~ /\Q$thousands\E\d{1,2}\b/ && $number !~ /\Q$thousands\E\d{4,}/ # And cannot follow a leading zero && $number !~ /^0\Q$thousands\E/ )) && ( # The number is not required to include decimal separators $number !~ /\Q$decimal\E/ # But if one is included, it cannot be followed by another separator, whether decimal or thousands. || $number !~ /\Q$decimal\E(?:.*)?(?:\Q$decimal\E|\Q$thousands\E)/ )) ? 1 : 0; } sub precision_of { my ($self, $number_text) = @_; my $decimal = $self->decimal; return ($number_text =~ /\Q$decimal\E(\d+)/) ? length($1) : 0; } sub for_computation { my ($self, $number_text) = @_; my ($decimal, $thousands, $exponential) = ($self->decimal, $self->thousands, $self->exponential); $number_text =~ s/[ _]//g; # Remove spaces and underscores as visuals. $number_text =~ s/\Q$thousands\E//g; # Remove thousands seps, since they are just visual. $number_text =~ s/\Q$decimal\E/./g; # Make sure decimal mark is something perl knows how to use. if ($number_text =~ s/^([\d$decimal$thousands]+)\Q$exponential\E(-?[\d$decimal$thousands]+)$/$1e$2/ig) { # Convert to perl style exponentials and then make into human-style floats. $number_text = Math::BigFloat->new($number_text)->bstr(); } return $number_text; } sub for_display { my ($self, $number_text) = @_; my ($decimal, $thousands, $exponential) = ($self->decimal, $self->thousands, $self->exponential); $number_text =~ s/[ _]//g; # Remove spaces and underscores as visuals. if ($number_text =~ /(.*)\Q$exponential\E([+-]?\d+)/i) { $number_text = $self->for_display($1) . ' * 10^' . $self->for_display(int $2); } else { $number_text = reverse $number_text; $number_text =~ s/\./$decimal/g; # Perl decimal mark to whatever we need. $number_text =~ s/(\d{3})(?=\d)(?!\d*\Q$decimal\E)/$1$thousands/g; $number_text = reverse $number_text; } return $number_text; } # The display version with HTML added: # - superscripted exponents sub with_html { my ($self, $number_text) = @_; return $self->_add_html_exponents($number_text); } sub _add_html_exponents { my ($self, $string) = @_; return $string if ($string !~ /\^/ or $string =~ /^\^|\^$/); # Give back the same thing if we won't deal with it properly. my @chars = split //, $string; my $number_re = $self->number_regex; my ($start_tag, $end_tag) = ('<sup>', '</sup>'); my ($newly_up, $in_exp_number, $in_exp_parens, %power_parens); my ($parens_count, $number_up) = (0, 0); # because of associativity and power-to-power, we need to scan nearly the whole thing for my $index (1 .. $#chars) { my $this_char = $chars[$index]; if ($this_char =~ $number_re or ($newly_up && $this_char eq '-')) { if ($newly_up) { $in_exp_number = 1; $newly_up = 0; } } elsif ($this_char eq '(') { $parens_count += 1; $in_exp_number = 0; if ($newly_up) { $in_exp_parens += 1; $power_parens{$parens_count} = 1; $newly_up = 0; } } elsif ($this_char eq '^') { $chars[$index - 1] =~ s/$end_tag$//; # Added too soon! $number_up += 1; $newly_up = 1; $chars[$index] = $start_tag; # Replace ^ with the tag. } elsif ($in_exp_number) { $in_exp_number = 0; $number_up -= 1; $chars[$index] = $end_tag . $chars[$index]; } elsif ($number_up && !$in_exp_parens) { # Must have ended another term or more $chars[$index] = ($end_tag x $number_up) . $chars[$index]; $number_up -= 1; } elsif ($this_char eq ')') { # We just closed a set of parens, see if it closes one of our things if ($in_exp_parens && $power_parens{$parens_count}) { $chars[$index] .= $end_tag; delete $power_parens{$parens_count}; $in_exp_parens -= 1; $number_up -= 1; } $parens_count -= 1; } } my $final = join('', @chars); # We may not have added enough closing tags, because we can't "see" the end. my $up_count = () = $final =~ /$start_tag/g; my $down_count = () = $final =~ /$end_tag/g; # We'll assume we're just supposed to append them now $final .= $end_tag x ($up_count - $down_count); return $final; } 1;
lights0123/zeroclickinfo-goodies
lib/DDG/GoodieRole/NumberStyle.pm
Perl
apache-2.0
5,998
#!/usr/bin/perl # Script to generate a Refresh header HTTP redirect print "Status: 200 ok\r\n"; print "Refresh: 0; url=resources/redirect-target.html#1\r\n"; print "Content-type: text/html\r\n"; print "\r\n"; print <<HERE_DOC_END <html> <head> <title>200 Refresh Redirect</title> <script> if (window.testRunner) { testRunner.clearBackForwardList(); testRunner.waitUntilDone(); } </script> <body>This page is a 200 refresh redirect on a 0 second delay.</body> </html> HERE_DOC_END
nwjs/chromium.src
third_party/blink/web_tests/http/tests/history/redirect-200-refresh-0-seconds.pl
Perl
bsd-3-clause
491
package CGI::Push; use if $] >= 5.019, 'deprecate'; $CGI::Push::VERSION='4.22'; use CGI; use CGI::Util 'rearrange'; @ISA = ('CGI'); $CGI::DefaultClass = 'CGI::Push'; # add do_push() and push_delay() to exported tags push(@{$CGI::EXPORT_TAGS{':standard'}},'do_push','push_delay'); sub do_push { my ($self,@p) = CGI::self_or_default(@_); # unbuffer output $| = 1; srand; my ($random) = sprintf("%08.0f",rand()*1E8); my ($boundary) = "----=_NeXtPaRt$random"; my (@header); my ($type,$callback,$delay,$last_page,$cookie,$target,$expires,$nph,@other) = rearrange([TYPE,NEXT_PAGE,DELAY,LAST_PAGE,[COOKIE,COOKIES],TARGET,EXPIRES,NPH],@p); $type = 'text/html' unless $type; $callback = \&simple_counter unless $callback && ref($callback) eq 'CODE'; $delay = 1 unless defined($delay); $self->push_delay($delay); $nph = 1 unless defined($nph); my(@o); foreach (@other) { push(@o,split("=")); } push(@o,'-Target'=>$target) if defined($target); push(@o,'-Cookie'=>$cookie) if defined($cookie); push(@o,'-Type'=>"multipart/x-mixed-replace;boundary=\"$boundary\""); push(@o,'-Server'=>"CGI.pm Push Module") if $nph; push(@o,'-Status'=>'200 OK'); push(@o,'-nph'=>1) if $nph; print $self->header(@o); $boundary = "$CGI::CRLF--$boundary"; print "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY.${boundary}$CGI::CRLF"; my (@contents) = &$callback($self,++$COUNTER); # now we enter a little loop while (1) { print "Content-type: ${type}$CGI::CRLF$CGI::CRLF" unless $type =~ /^dynamic|heterogeneous$/i; print @contents; @contents = &$callback($self,++$COUNTER); if ((@contents) && defined($contents[0])) { print "${boundary}$CGI::CRLF"; do_sleep($self->push_delay()) if $self->push_delay(); } else { if ($last_page && ref($last_page) eq 'CODE') { print "${boundary}$CGI::CRLF"; do_sleep($self->push_delay()) if $self->push_delay(); print "Content-type: ${type}$CGI::CRLF$CGI::CRLF" unless $type =~ /^dynamic|heterogeneous$/i; print &$last_page($self,$COUNTER); } print "${boundary}--$CGI::CRLF"; last; } } print "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY.$CGI::CRLF"; } sub simple_counter { my ($self,$count) = @_; return $self->start_html("CGI::Push Default Counter"), $self->h1("CGI::Push Default Counter"), "This page has been updated ",$self->strong($count)," times.", $self->hr(), $self->a({'-href'=>'http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html'},'CGI.pm home page'), $self->end_html; } sub do_sleep { my $delay = shift; if ( ($delay >= 1) && ($delay!~/\./) ){ sleep($delay); } else { select(undef,undef,undef,$delay); return $delay; } } sub push_delay { my ($self,$delay) = CGI::self_or_default(@_); return defined($delay) ? $self->{'.delay'} = $delay : $self->{'.delay'}; } 1; =head1 NAME CGI::Push - Simple Interface to Server Push =head1 SYNOPSIS use strict; use warnings; use CGI::Push qw(:standard); do_push( -next_page => \&next_page, -last_page => \&last_page, -delay => 0.5 ); sub next_page { my($q,$counter) = @_; return undef if $counter >= 10; .... } sub last_page { my($q,$counter) = @_; return ... } =head1 DESCRIPTION CGI::Push is a subclass of the CGI object created by CGI.pm. It is specialized for server push operations, which allow you to create animated pages whose content changes at regular intervals. You provide CGI::Push with a pointer to a subroutine that will draw one page. Every time your subroutine is called, it generates a new page. The contents of the page will be transmitted to the browser in such a way that it will replace what was there beforehand. The technique will work with HTML pages as well as with graphics files, allowing you to create animated GIFs. Only Netscape Navigator supports server push. Internet Explorer browsers do not. =head1 USING CGI::Push CGI::Push adds one new method to the standard CGI suite, do_push(). When you call this method, you pass it a reference to a subroutine that is responsible for drawing each new page, an interval delay, and an optional subroutine for drawing the last page. Other optional parameters include most of those recognized by the CGI header() method. You may call do_push() in the object oriented manner or not, as you prefer: use CGI::Push; $q = CGI::Push->new; $q->do_push(-next_page=>\&draw_a_page); -or- use CGI::Push qw(:standard); do_push(-next_page=>\&draw_a_page); Parameters are as follows: =over 4 =item -next_page do_push(-next_page=>\&my_draw_routine); This required parameter points to a reference to a subroutine responsible for drawing each new page. The subroutine should expect two parameters consisting of the CGI object and a counter indicating the number of times the subroutine has been called. It should return the contents of the page as an B<array> of one or more items to print. It can return a false value (or an empty array) in order to abort the redrawing loop and print out the final page (if any) sub my_draw_routine { my($q,$counter) = @_; return undef if $counter > 100; ... } You are of course free to refer to create and use global variables within your draw routine in order to achieve special effects. =item -last_page This optional parameter points to a reference to the subroutine responsible for drawing the last page of the series. It is called after the -next_page routine returns a false value. The subroutine itself should have exactly the same calling conventions as the -next_page routine. =item -type This optional parameter indicates the content type of each page. It defaults to "text/html". Normally the module assumes that each page is of a homogeneous MIME type. However if you provide either of the magic values "heterogeneous" or "dynamic" (the latter provided for the convenience of those who hate long parameter names), you can specify the MIME type -- and other header fields -- on a per-page basis. See "heterogeneous pages" for more details. =item -delay This indicates the delay, in seconds, between frames. Smaller delays refresh the page faster. Fractional values are allowed. B<If not specified, -delay will default to 1 second> =item -cookie, -target, -expires, -nph These have the same meaning as the like-named parameters in CGI::header(). If not specified, -nph will default to 1 (as needed for many servers, see below). =back =head2 Heterogeneous Pages Ordinarily all pages displayed by CGI::Push share a common MIME type. However by providing a value of "heterogeneous" or "dynamic" in the do_push() -type parameter, you can specify the MIME type of each page on a case-by-case basis. If you use this option, you will be responsible for producing the HTTP header for each page. Simply modify your draw routine to look like this: sub my_draw_routine { my($q,$counter) = @_; return header('text/html'), # note we're producing the header here .... } You can add any header fields that you like, but some (cookies and status fields included) may not be interpreted by the browser. One interesting effect is to display a series of pages, then, after the last page, to redirect the browser to a new URL. Because redirect() does b<not> work, the easiest way is with a -refresh header field, as shown below: sub my_draw_routine { my($q,$counter) = @_; return undef if $counter > 10; return header('text/html'), # note we're producing the header here ... } sub my_last_page { return header(-refresh=>'5; URL=http://somewhere.else/finished.html', -type=>'text/html'), ... } =head2 Changing the Page Delay on the Fly If you would like to control the delay between pages on a page-by-page basis, call push_delay() from within your draw routine. push_delay() takes a single numeric argument representing the number of seconds you wish to delay after the current page is displayed and before displaying the next one. The delay may be fractional. Without parameters, push_delay() just returns the current delay. =head1 INSTALLING CGI::Push SCRIPTS Server push scripts must be installed as no-parsed-header (NPH) scripts in order to work correctly on many servers. On Unix systems, this is most often accomplished by prefixing the script's name with "nph-". Recognition of NPH scripts happens automatically with WebSTAR and Microsoft IIS. Users of other servers should see their documentation for help. Apache web server from version 1.3b2 on does not need server push scripts installed as NPH scripts: the -nph parameter to do_push() may be set to a false value to disable the extra headers needed by an NPH script. =head1 AUTHOR INFORMATION The CGI.pm distribution is copyright 1995-2007, Lincoln D. Stein. It is distributed under GPL and the Artistic License 2.0. It is currently maintained by Lee Johnson with help from many contributors. Address bug reports and comments to: https://github.com/leejo/CGI.pm/issues The original bug tracker can be found at: https://rt.cpan.org/Public/Dist/Display.html?Queue=CGI.pm When sending bug reports, please provide the version of CGI.pm, the version of Perl, the name and version of your Web server, and the name and version of the operating system you are using. If the problem is even remotely browser dependent, please provide information about the affected browsers as well. Copyright 1995-1998, Lincoln D. Stein. All rights reserved. =head1 BUGS This section intentionally left blank. =head1 SEE ALSO L<CGI::Carp>, L<CGI> =cut
rosiro/wasarabi
local/lib/perl5/CGI/Push.pm
Perl
mit
10,086
# 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 debian/tzdata/europe. Olson data version 2008c # # Do not edit this file directly. # package DateTime::TimeZone::Europe::Zurich; use strict; use Class::Singleton; use DateTime::TimeZone; use DateTime::TimeZone::OlsonDB; @DateTime::TimeZone::Europe::Zurich::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' ); my $spans = [ [ DateTime::TimeZone::NEG_INFINITY, 58307729152, DateTime::TimeZone::NEG_INFINITY, 58307731200, 2048, 0, 'LMT' ], [ 58307729152, 59750436616, 58307730936, 59750438400, 1784, 0, 'BMT' ], [ 59750436616, 61215346800, 59750440216, 61215350400, 3600, 0, 'CET' ], [ 61215346800, 61220440800, 61215354000, 61220448000, 7200, 1, 'CEST' ], [ 61220440800, 61231165200, 61220444400, 61231168800, 3600, 0, 'CET' ], [ 61231165200, 61244460000, 61231172400, 61244467200, 7200, 1, 'CEST' ], [ 61244460000, 61262614800, 61244463600, 61262618400, 3600, 0, 'CET' ], [ 61262614800, 61275909600, 61262622000, 61275916800, 7200, 1, 'CEST' ], [ 61275909600, 62482834800, 61275913200, 62482838400, 3600, 0, 'CET' ], [ 62482834800, 62490358800, 62482838400, 62490362400, 3600, 0, 'CET' ], [ 62490358800, 62506083600, 62490366000, 62506090800, 7200, 1, 'CEST' ], [ 62506083600, 62521808400, 62506087200, 62521812000, 3600, 0, 'CET' ], [ 62521808400, 62537533200, 62521815600, 62537540400, 7200, 1, 'CEST' ], [ 62537533200, 62553258000, 62537536800, 62553261600, 3600, 0, 'CET' ], [ 62553258000, 62568982800, 62553265200, 62568990000, 7200, 1, 'CEST' ], [ 62568982800, 62584707600, 62568986400, 62584711200, 3600, 0, 'CET' ], [ 62584707600, 62601037200, 62584714800, 62601044400, 7200, 1, 'CEST' ], [ 62601037200, 62616762000, 62601040800, 62616765600, 3600, 0, 'CET' ], [ 62616762000, 62632486800, 62616769200, 62632494000, 7200, 1, 'CEST' ], [ 62632486800, 62648211600, 62632490400, 62648215200, 3600, 0, 'CET' ], [ 62648211600, 62663936400, 62648218800, 62663943600, 7200, 1, 'CEST' ], [ 62663936400, 62679661200, 62663940000, 62679664800, 3600, 0, 'CET' ], [ 62679661200, 62695386000, 62679668400, 62695393200, 7200, 1, 'CEST' ], [ 62695386000, 62711110800, 62695389600, 62711114400, 3600, 0, 'CET' ], [ 62711110800, 62726835600, 62711118000, 62726842800, 7200, 1, 'CEST' ], [ 62726835600, 62742560400, 62726839200, 62742564000, 3600, 0, 'CET' ], [ 62742560400, 62758285200, 62742567600, 62758292400, 7200, 1, 'CEST' ], [ 62758285200, 62774010000, 62758288800, 62774013600, 3600, 0, 'CET' ], [ 62774010000, 62790339600, 62774017200, 62790346800, 7200, 1, 'CEST' ], [ 62790339600, 62806064400, 62790343200, 62806068000, 3600, 0, 'CET' ], [ 62806064400, 62821789200, 62806071600, 62821796400, 7200, 1, 'CEST' ], [ 62821789200, 62837514000, 62821792800, 62837517600, 3600, 0, 'CET' ], [ 62837514000, 62853238800, 62837521200, 62853246000, 7200, 1, 'CEST' ], [ 62853238800, 62868963600, 62853242400, 62868967200, 3600, 0, 'CET' ], [ 62868963600, 62884688400, 62868970800, 62884695600, 7200, 1, 'CEST' ], [ 62884688400, 62900413200, 62884692000, 62900416800, 3600, 0, 'CET' ], [ 62900413200, 62916138000, 62900420400, 62916145200, 7200, 1, 'CEST' ], [ 62916138000, 62931862800, 62916141600, 62931866400, 3600, 0, 'CET' ], [ 62931862800, 62947587600, 62931870000, 62947594800, 7200, 1, 'CEST' ], [ 62947587600, 62963917200, 62947591200, 62963920800, 3600, 0, 'CET' ], [ 62963917200, 62982061200, 62963924400, 62982068400, 7200, 1, 'CEST' ], [ 62982061200, 62995366800, 62982064800, 62995370400, 3600, 0, 'CET' ], [ 62995366800, 63013510800, 62995374000, 63013518000, 7200, 1, 'CEST' ], [ 63013510800, 63026816400, 63013514400, 63026820000, 3600, 0, 'CET' ], [ 63026816400, 63044960400, 63026823600, 63044967600, 7200, 1, 'CEST' ], [ 63044960400, 63058266000, 63044964000, 63058269600, 3600, 0, 'CET' ], [ 63058266000, 63077014800, 63058273200, 63077022000, 7200, 1, 'CEST' ], [ 63077014800, 63089715600, 63077018400, 63089719200, 3600, 0, 'CET' ], [ 63089715600, 63108464400, 63089722800, 63108471600, 7200, 1, 'CEST' ], [ 63108464400, 63121165200, 63108468000, 63121168800, 3600, 0, 'CET' ], [ 63121165200, 63139914000, 63121172400, 63139921200, 7200, 1, 'CEST' ], [ 63139914000, 63153219600, 63139917600, 63153223200, 3600, 0, 'CET' ], [ 63153219600, 63171363600, 63153226800, 63171370800, 7200, 1, 'CEST' ], [ 63171363600, 63184669200, 63171367200, 63184672800, 3600, 0, 'CET' ], [ 63184669200, 63202813200, 63184676400, 63202820400, 7200, 1, 'CEST' ], [ 63202813200, 63216118800, 63202816800, 63216122400, 3600, 0, 'CET' ], [ 63216118800, 63234867600, 63216126000, 63234874800, 7200, 1, 'CEST' ], [ 63234867600, 63247568400, 63234871200, 63247572000, 3600, 0, 'CET' ], [ 63247568400, 63266317200, 63247575600, 63266324400, 7200, 1, 'CEST' ], [ 63266317200, 63279018000, 63266320800, 63279021600, 3600, 0, 'CET' ], [ 63279018000, 63297766800, 63279025200, 63297774000, 7200, 1, 'CEST' ], [ 63297766800, 63310467600, 63297770400, 63310471200, 3600, 0, 'CET' ], [ 63310467600, 63329216400, 63310474800, 63329223600, 7200, 1, 'CEST' ], [ 63329216400, 63342522000, 63329220000, 63342525600, 3600, 0, 'CET' ], [ 63342522000, 63360666000, 63342529200, 63360673200, 7200, 1, 'CEST' ], [ 63360666000, 63373971600, 63360669600, 63373975200, 3600, 0, 'CET' ], [ 63373971600, 63392115600, 63373978800, 63392122800, 7200, 1, 'CEST' ], [ 63392115600, 63405421200, 63392119200, 63405424800, 3600, 0, 'CET' ], [ 63405421200, 63424170000, 63405428400, 63424177200, 7200, 1, 'CEST' ], [ 63424170000, 63436870800, 63424173600, 63436874400, 3600, 0, 'CET' ], [ 63436870800, 63455619600, 63436878000, 63455626800, 7200, 1, 'CEST' ], [ 63455619600, 63468320400, 63455623200, 63468324000, 3600, 0, 'CET' ], [ 63468320400, 63487069200, 63468327600, 63487076400, 7200, 1, 'CEST' ], [ 63487069200, 63500374800, 63487072800, 63500378400, 3600, 0, 'CET' ], [ 63500374800, 63518518800, 63500382000, 63518526000, 7200, 1, 'CEST' ], [ 63518518800, 63531824400, 63518522400, 63531828000, 3600, 0, 'CET' ], [ 63531824400, 63549968400, 63531831600, 63549975600, 7200, 1, 'CEST' ], [ 63549968400, 63563274000, 63549972000, 63563277600, 3600, 0, 'CET' ], [ 63563274000, 63581418000, 63563281200, 63581425200, 7200, 1, 'CEST' ], [ 63581418000, 63594723600, 63581421600, 63594727200, 3600, 0, 'CET' ], [ 63594723600, 63613472400, 63594730800, 63613479600, 7200, 1, 'CEST' ], [ 63613472400, 63626173200, 63613476000, 63626176800, 3600, 0, 'CET' ], [ 63626173200, 63644922000, 63626180400, 63644929200, 7200, 1, 'CEST' ], [ 63644922000, 63657622800, 63644925600, 63657626400, 3600, 0, 'CET' ], [ 63657622800, 63676371600, 63657630000, 63676378800, 7200, 1, 'CEST' ], [ 63676371600, 63689677200, 63676375200, 63689680800, 3600, 0, 'CET' ], [ 63689677200, 63707821200, 63689684400, 63707828400, 7200, 1, 'CEST' ], ]; sub olson_version { '2008c' } sub has_dst_changes { 42 } sub _max_year { 2018 } sub _new_instance { return shift->_init( @_, spans => $spans ); } sub _last_offset { 3600 } my $last_observance = bless( { 'format' => 'CE%sT', 'gmtoff' => '1:00', 'local_start_datetime' => bless( { 'formatter' => undef, 'local_rd_days' => 723181, 'local_rd_secs' => 0, 'offset_modifier' => 0, 'rd_nanosecs' => 0, 'tz' => bless( { 'name' => 'floating', 'offset' => 0 }, 'DateTime::TimeZone::Floating' ), 'utc_rd_days' => 723181, 'utc_rd_secs' => 0, 'utc_year' => 1982 }, 'DateTime' ), 'offset_from_std' => 0, 'offset_from_utc' => 3600, 'until' => [], 'utc_start_datetime' => bless( { 'formatter' => undef, 'local_rd_days' => 723180, 'local_rd_secs' => 82800, 'offset_modifier' => 0, 'rd_nanosecs' => 0, 'tz' => bless( { 'name' => 'floating', 'offset' => 0 }, 'DateTime::TimeZone::Floating' ), 'utc_rd_days' => 723180, 'utc_rd_secs' => 82800, 'utc_year' => 1981 }, 'DateTime' ) }, 'DateTime::TimeZone::OlsonDB::Observance' ) ; sub _last_observance { $last_observance } my $rules = [ bless( { 'at' => '1:00u', 'from' => '1996', 'in' => 'Oct', 'letter' => '', 'name' => 'EU', 'offset_from_std' => 0, 'on' => 'lastSun', 'save' => '0', 'to' => 'max', 'type' => undef }, 'DateTime::TimeZone::OlsonDB::Rule' ), bless( { 'at' => '1:00u', 'from' => '1981', 'in' => 'Mar', 'letter' => 'S', 'name' => 'EU', 'offset_from_std' => 3600, 'on' => 'lastSun', 'save' => '1:00', 'to' => 'max', 'type' => undef }, 'DateTime::TimeZone::OlsonDB::Rule' ) ] ; sub _rules { $rules } 1;
carlgao/lenga
images/lenny64-peon/usr/share/perl5/DateTime/TimeZone/Europe/Zurich.pm
Perl
mit
9,351
package Lojban::Valsi; use warnings; use strict; use overload '<=>' => 'karbi', 'cmp' => 'karbi', '""' => 'valsi'; use Carp; use Lojban::Vlatai (':lerpoi', '@klesi'); use Lojban::Vlasisku ('getGismu', 'getValsiByRafsi', ':stodi'); our $VERSION = v2.0; our @CARP_NOT = ('Lojban::Vlasisku', 'Lojban::Vlatai', 'Lojban::Vlatid'); my @scalarAttr = ('valsi', 'selmaho', 'ralvla', 'djuvla', 'selvla', 'notci', 'klesi', 'termre', 'xuvladra'); my @arrayAttr = ('rafsi', 'krarafsi', 'veljvo'); sub cnino { my $class = shift; my %selkai = (valsi => shift); my %userStuff = @_; foreach (@scalarAttr) { $selkai{$_} = $userStuff{$_} if defined $userStuff{$_} && $_ ne 'xuvladra' && ($_ ne 'klesi' || grep { $_ eq $userStuff{klesi} } @klesi) } foreach (@arrayAttr) { $selkai{$_} = [ @{$userStuff{$_}} ] if defined $userStuff{$_} && @{$userStuff{$_}} } bless { %selkai }, $class; } sub cminiho { my($class, $entry) = @_; my %data = (); # What's the best way to determine if an entry is from gimste or ma'oste? if (substr($entry, 10, 2) !~ /^ [[:upper:]]$/) { $data{klesi} = $entry =~ /^ $gism$V / ? 'gismu' : 'cmavo'; foreach my $sec (['valsi', 1, 5], ['rafsi', 7, 12], ['ralvla', 20, 20], ['djuvla', 41, 20], ['selvla', 62, 96], ['notci', 169, -1]) { last if $sec->[1] >= length $entry; ($data{$sec->[0]} = substr $entry, $sec->[1], $sec->[2]) =~ s/^\s+|\s+$//g; $data{$sec->[0]} = [ split /\s+/, $data{$sec->[0]} ] if $sec->[0] eq 'rafsi'; } } else { $data{klesi} = 'cmavo'; foreach my $sec (['valsi', 0, 11], ['selmaho', 11, 5], ['ralvla', 20, 42], ['selvla', 62, 106], ['notci', 168, -1]) { last if $sec->[1] >= length $entry; ($data{$sec->[0]} = substr $entry, $sec->[1], $sec->[2]) =~ s/^\s+|\s+$//g; } } bless { %data }, $class; } my @tabFields = qw< valsi selmaho rafsi ralvla djuvla selvla notci klesi krarafsi veljvo termre >; sub catniho { my($class, $entry) = @_; my %data = (); my $i = 0; foreach (split /\t/, $entry) { next if $_ eq ''; last if $i >= @tabFields; ($data{$tabFields[$i]} = $_) =~ s/^\s+|\s+$//g; } continue { $i++ } if (!exists $data{valsi}) { carp "lo cartu cmima be secau lo valsi cu sumti la'o py. Lojban::Valsi::catniho .py."; return undef; } foreach (@arrayAttr) { $data{$_} = [ split ' ', $data{$_} ] if exists $data{$_} } return bless { %data }, $class; } sub valsi { $_[0]->{valsi} } sub selmaho { $_[0]->{selmaho} } sub rafsi { exists $self->{rafsi} && defined $self->{rafsi} ? @{$self->{rafsi}} : () } sub ralvla { $_[0]->{ralvla} } sub djuvla { $_[0]->{djuvla} } sub selvla { $_[0]->{selvla} } sub notci { $_[0]->{notci} } sub klesi { my $self = shift; $self->{klesi} = Lojban::Vlatai::vlalei $self->valsi if !exists $self->{klesi}; return $self->{klesi}; } sub krarafsi { my $self = shift; $self->{krarafsi} = $self->klesi eq 'lujvo' ? [ Lojban::Vlatai::jvokatna $self->valsi ] : [] if !exists $self->{krarafsi}; return @{$self->{krarafsi}}; } sub veljvo { my $self = shift; $self->{veljvo} = [ map { scalar(/^$gism$V?$/o ? getGismu($_ . (/$V$/ ? '' : '.'), VLASISKU_ANCHORED) : getValsiByRafsi($_, VLASISKU_ANCHORED | VLASISKU_LITERAL)) # If the user wants to know what {rafsi} doesn't have a {valsi}, ey can just # check the corresponding index in the krarafsi. } $self->krarafsi ] if !exists $self->{veljvo}; return @{$self->{veljvo}}; } sub termre { my $self = shift; if (!exists $self->{termre}) { my @rafsi = $self->krarafsi; if (@rafsi) { $self->{termre} = Lojban::Vlatai::jvomre $self->valsi, @rafsi } else { $self->{termre} = undef } } return $self->{termre}; } sub xuvladra { my $self = shift; if (!exists $self->{xuvladra}) { my $vlalei = Lojban::Vlatai::vlalei $self->valsi; $self->{xuvladra} = defined($vlalei) && (exists $self->{klesi} ? $self->{klesi} eq $vlalei : ($self->{klesi} = $vlalei) && 1); } return $self->{xuvladra}; } sub cmuselmaho { my $selmaho = $_[0]->selmaho; $selmaho =~ s/\*?\d*[[:lower:]]*$// if defined $selmaho; return $selmaho; } sub fadni { Lojban::Vlatai::fadgau $_[0]->valsi } sub xugismu { defined $_[0]->klesi && $_[0]->klesi eq 'gismu' } sub xucmavo { defined $_[0]->klesi && $_[0]->klesi eq 'cmavo' } sub xulujmaho { defined $_[0]->klesi && $_[0]->klesi eq "lujma'o" } sub xucmene { defined $_[0]->klesi && $_[0]->klesi eq 'cmene' } sub xulujvo { defined $_[0]->klesi && $_[0]->klesi eq 'lujvo' } sub xufuhivla { defined $_[0]->klesi && $_[0]->klesi eq "fu'ivla" } sub xubrivla { $_[0]->xugismu || $_[0]->xulujvo || $_[0]->xufuhivla } sub xusuzmaho { $_[0]->xucmavo || $_[0]->xulujmaho } sub fukpi { my $self = shift; my %selkai = (); foreach (@scalarAttr) { $selkai{$_} = $self->{$_} if exists $self->{$_} } foreach (@arrayAttr) { $selkai{$_} = [ @{$self->{$_}} ] if exists $self->{$_} } bless { %selkai }, ref $self; } sub karbi { shift unless ref $_[0]; # in case of ``karbi Lojban::Valsi $pa, $re'' my($pa, $re) = ($_[0]->fadni, (ref $_[1] ? $_[1]->fadni : Lojban::Vlatai::fadgau $_[1])); return $_[2] ? $re cmp $pa : $pa cmp $re; } sub cusku { my $self = shift; my $out = shift || select; select((select($out), local $~ = 'VLACISKA', local $: .= '/')[0]); foreach (qw< valsi klesi selmaho rafsi krarafsi veljvo termre ralvla djuvla selvla notci >) { # Should `xuvladra' also be included? next if !exists $self->{$_}; my $value = $self->{$_}; next if !defined $value || $value eq '' || ref $value eq 'ARRAY' && !@$value; (my $label = uc) =~ tr/H/h/; my $text = ref $value eq 'ARRAY' ? join ' ', @$value : $value; write $out; format VLACISKA = @<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< "$label:", $text ~~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< $text . } print $out "\n"; } sub xrejmina { shift unless ref $_[0]; # in case of ``xrejmina Lojban::Valsi $pa, $re'' my($pa, $re) = @_; if ($pa->valsi ne $re->valsi) { carp "lo naldunli valsi po'u zo $pa .e zo $re cu sumti la'o py. Lojban::Valsi::xrejmina .py."; return undef; } my %mixre = (); foreach (qw<valsi selmaho ralvla djuvla selvla notci klesi termre xuvladra>) { my($a, $b) = map { !defined || $_ eq '' ? undef : $_ } ($pa->$_, $re->$_); next if !defined $a && !defined $b; if (!defined $a) { $mixre{$_} = $b } elsif (!defined $b) { $mixre{$_} = $a } elsif ($a eq $b) { $mixre{$_} = $a } elsif ($_ ne 'klesi' && $_ ne 'termre' && $_ ne 'xuvladra') # There's probably a better way to do this: { $mixre{$_} = "$a --- $b" } } my $prev = undef; $mixre{rafsi} = [ grep { (!defined $prev or $prev ne $_) and ($prev = $_ or 1) } sort(@{$pa->rafsi}, @{$re->rafsi}) ]; for (qw< krarafsi veljvo >) { my @a = @{$pa->$_}; my @b = @{$re->$_}; # Must... resist... urge... to... use... Perl 5.10-specific... operator... $mixre{$_} = [ @a ] if @a == @b && !map { $a[$_] eq $b[$_] ? () : 1 } 0..$#a; } $pa->SUPER::new(%mixre); } sub girxre { shift unless ref $_[0]; my @mixre; my $prev; for (sort @_) { if (!defined $prev) { $prev = $_ } elsif ($prev->valsi eq $_->valsi) { $prev = xrejmina($prev, $_) } else {push @mixre, $prev; $prev = $_; } } push @mixre, $prev if defined $prev; return @mixre; } 1; __END__ Member variables of `Valsi': - valsi - the word itself - selmaho - {selma'o} ({ma'ostecmi} only) - rafsi - array of {rafsi} ({gimstecmi} only) - ralvla - keyword - djuvla - hint ({gimstecmi} only) - selvla - definition - notci - notes - klesi - type of word ({gismu}, {cmavo}, etc.) - krarafsi - {rafsi} used to form a {lujvo} or {lujvo cmene} - veljvo - array of the components of the source {tanru} (generated by the class as Lojban::Valsi objects, but there's nothing stopping the user from supplying strings instead) - termre - {lujvo} score (also applies to {lujvo cmene}) - xuvladra - Boolean representing whether the word is morphologically correct Various design notes to work into the new documentation: - The (non-entry) constructor takes a hash that specifies values for arbitrary attributes (except those that should only be calculated, e.g., normalized form and base {selma'o}). - Comparisons are done using normalized forms. - {cmene} are only recognized as {lujvo cmene} if a set of {krarafsi} was defined for them at creation time. =pod =head1 NAME Lojban::Valsi - class for standard Lojban words =head1 SYNOPSIS use Lojban::Valsi; $valsi = cminiho Lojban::Valsi $entry; print "$valsi:\n"; $valsi->printEntry(); @porsi = sort @liste; use Lojban::Vlasisku; @danfu = Lojban::Valsi::girxre getGismu($x), getCmavo($x); =head1 DESCRIPTION Lojban::Valsi is a class used to manipulate entries from the official Lojban I<gismu> & I<cmavo> lists. As its objects can only be constructed from lines taken from said lists, you are most likely to encounter them as the return values of Lojban::Vlasisku functions. Also as a result of this, the class can currently only be used to represent I<gismu>, I<cmavo>, and compound I<cmavo>; I<lujvo>, I<fu'ivla>, and I<cmene> should not be attempted without rewriting the module. Note that, when an object of this class is created, the only things it knows about the associated I<valsi> are what was contained in the string used to construct it; e.g., if a C<Lojban::Valsi> is made from a I<cmavo> entry taken from the I<gismu> list, the object will not know the I<cmavo>'s I<selma'o>. One way to solve this is to create an object for both the I<cmavo> list entry and the I<gismu> list entry and then merge them with the C<xrejmina> method. =head1 CONSTRUCTOR =over =item cminiho STRING The single constructor for the Lojban::Valsi class takes as its argument a string containing one (1) line from either the official I<gismu> list or the official I<cmavo> list (excluding the first line of each, of course) or a line from elsewhere that is formatted identically to the entries in the appropriate list. If an improperly formatted string is supplied, the results are undefined. =back =head1 INSTANCE METHODS =over =item djuvla Returns the hint word for the invocant or false if there is none. =item isCmavo Returns true if the invocant is a I<cmavo> or compound I<cmavo>, false otherwise. =item isCompoundCmavo Returns true if the invocant is a compound I<cmavo>, false otherwise. This is tested by seeing whether the I<selma'o> contains an asterisk. =item isGismu Returns true if the invocant is a I<gismu>, false otherwise. =item notci Returns the notes for the invocant or false if there are none. =item printEntry [FILE] Prints a neatly-formatted dictionary entry for the invocant to the given filehandle or to the currently selected filehandle if none is specified. =item rafsi Returns the three-letter I<rafsi> of the invocant as an array of strings. =item ralvla Returns the keyword or gloss for the invocant. =item selmaho Returns the I<selma'o> of the invocant or false if there is none. =item selvla Returns the definition of the invocant. =item klesi Returns the string C<"gismu"> if the invocant is a I<gismu> or C<"cmavo"> if the invocant is a I<cmavo>. =item valsi Returns the actual word that the invocant represents. =back =head1 CLASS METHODS Note that these functions are not class methods in the strictest sense; though they can be invoked as C<karbi Lojban::Valsi $pa, $re>, using them as instance methods (e.g., C<< $pa->karbi($re) >>) will have the same effect, and they can even be used as non-OO subroutines (C<Lojban::Valsi::karbi($pa, $re)>). How you invoke them is pretty much up to you. =over =item girxre LIST This method sorts a list of Lojban::Valsi objects, calls C<xrejmina> to merge together any with the same I<valsi>, and returns the resulting list. =item karbi VALSI, VALSI This method lexically compares the I<valsi> of the objects passed to it and returns -1 if the first I<valsi> comes after the second, 1 if the first comes before the second, or 0 if they are equal. All letters are made lowercase, apostrophes are converted to 'h's, and periods & commas are removed before comparison. A string may be supplied as the second argument instead of a Lojban::Valsi object. =item xrejmina VALSI, VALSI This method combines the data for two Lojban::Valsi objects into a new object. The objects must have the same I<valsi>; if they do not, a warning is printed and C<undef> is returned. Each field of the objects (other than the I<valsi> and I<rafsi>) is merged as follows: If the field only exists in one object but not the other, the extant value is used. If the objects have the same value for the field, that value is used. If the objects have different values, then, due to the lack of a better algorithm, those values are concatenated together with C<" --- "> and used as the new value for the field. The I<rafsi> of the objects are merged into a single list, with any duplicates removed. =back =head1 OVERLOADED OPERATORS In order to make using the Lojban::Valsi class a little easier, three operators have been overloaded for it. The C<< <=> >> and C<cmp> operators are mapped to C<karbi> so that comparisons & sorting of Lojban::Valsi objects can be accomplished easily, and "stringification" is mapped to the C<valsi> method so that any Lojban::Valsi object used as a string will be replaced by its I<valsi>. =head1 SEE ALSO L<sisku(1)>, Lojban::Vlasisku, Lojban::Vlatai I<The Complete Lojban Language> by John Woldemar Cowan L<http://www.lojban.org/> =head1 AUTHOR John T. "kamymecraijun." Wodder II <minimiscience@gmail.com> =head1 LICENSE Feel free to do whatever the I<bais.> you want with this. =cut
jwodder/jbobaf
perl/Lojban/Valsi.pm
Perl
mit
13,679
#!/usr/bin/perl use strict; use Test::More 'no_plan'; # tests => 10; BEGIN { use lib '../../../'; #TEST 1 use_ok('GAL::Parser::annovar_exonic'); } my $path = $0; $path =~ s/[^\/]+$//; $path ||= '.'; chdir($path); my $parser = GAL::Parser::annovar_exonic->new(file => '../data/NA12878.annovar_input_short.exonic_variant_function'); # TEST 2 isa_ok($parser, 'GAL::Parser::annovar_exonic'); while (my $feature = $parser->next_feature_hash) { print $parser->to_gff3($feature) . "\n"; } # TEST 3 ok($parser->get_features, '$parser->get_features'); ################################################################################ ################################# Ways to Test ################################# ################################################################################ __END__ # Various other ways to say "ok" ok($this eq $that, $test_name); is ($this, $that, $test_name); isnt($this, $that, $test_name); # Rather than print STDERR "# here's what went wrong\n" diag("here's what went wrong"); like ($this, qr/that/, $test_name); unlike($this, qr/that/, $test_name); cmp_ok($this, '==', $that, $test_name); is_deeply($complex_structure1, $complex_structure2, $test_name); can_ok($module, @methods); isa_ok($object, $class); pass($test_name); fail($test_name); BAIL_OUT($why);
4ureliek/TEanalysis
Lib/GAL/t/devel_scripts/parser_annovar_exonic.pl
Perl
mit
1,324
package Aspk::FileCharIterator; use Aspk::Debug; sub new { my ($class, $file)= @_; # dbgm $class $file; my $self={}; bless $self, $class; open my $fh, "<", $file or die "can't open file $file"; local $/; binmode $fh; $self->prop(content, <$fh>); # $self->prop(index) = 0; return $self; } sub get { my ($self, $pattern) = @_; # dbgm $pattern; my $len=0; my $str=$self->prop(content); if (defined($pattern)){ if ($str =~ /^($pattern)/) { $len = length($1); } } else { $len=1; } $self->prop(content, substr($str, $len)); return substr($str,0,$len); } # Get or set a property of the object sub prop { my ($self, $name, $value) = @_; # print "In prop. name: $name, value: $value\n"; # dbgl $name $value; if (defined($value)) { $self->{"_$name"} = $value; return $self; } else { return $self->{"_$name"}; } } 1;
astropeak/aspk-code-base
perl/Aspk/FileCharIterator.pm
Perl
mit
974
# -*- perl -*- # !!! DO NOT EDIT !!! # This file was automatically generated. package Net::Amazon::Validate::ItemSearch::jp::MusicLabel; use 5.006; use strict; use warnings; sub new { my ($class , %options) = @_; my $self = { '_default' => 'Music', %options, }; push @{$self->{_options}}, 'Classical'; push @{$self->{_options}}, 'Music'; bless $self, $class; } sub user_or_default { my ($self, $user) = @_; if (defined $user && length($user) > 0) { return $self->find_match($user); } return $self->default(); } sub default { my ($self) = @_; return $self->{_default}; } sub find_match { my ($self, $value) = @_; for (@{$self->{_options}}) { return $_ if lc($_) eq lc($value); } die "$value is not a valid value for jp::MusicLabel!\n"; } 1; __END__ =head1 NAME Net::Amazon::Validate::ItemSearch::jp::MusicLabel; =head1 DESCRIPTION The default value is Music, unless mode is specified. The list of available values are: Classical Music =cut
carlgao/lenga
images/lenny64-peon/usr/share/perl5/Net/Amazon/Validate/ItemSearch/jp/MusicLabel.pm
Perl
mit
1,064
package Plucene::Index::SegmentsTermEnum; =head1 NAME Plucene::Index::SegmentsTermEnum =head1 METHODS =head2 new / term / doc_freq / next as per TermEnum =cut # This only appears to be used with doing wildcard searches. use strict; use warnings; use Tie::Array::Sorted; use Plucene::Index::SegmentMergeInfo; sub term { $_[0]->{term} } sub doc_freq { $_[0]->{doc_freq} } sub new { my ($class, $readers, $starts, $t) = @_; tie my @queue, "Tie::Array::Sorted"; for my $i (0 .. $#{$readers}) { my $reader = $readers->[$i]; my $term_enum = $reader->terms($t); my $smi = Plucene::Index::SegmentMergeInfo->new($starts->[$i], $term_enum, $reader); if (!$t ? $smi->next : $term_enum->term) { # ??? push @queue, $smi; } } my $self = bless { queue => \@queue }, $class; if ($t and @queue) { my $top = $queue[0]; $self->{term} = $top->term_enum->term; $self->{doc_freq} = $top->term_enum->doc_freq; } return $self; } sub next { my $self = shift; my $top = $self->{queue}[0]; if (!$top) { undef $self->{term}; return; } $self->{term} = $top->term; $self->{doc_freq} = 0; while ($top && $self->{term}->eq($top->term)) { $self->{doc_freq} += $top->term_enum->doc_freq; # This might look funny, but it's right. The pop takes $top off # the queue, and when it has ->next called on it, its comparison # value changes; the queue is tied as a Tie::Array::Sorted, so # when it gets added back on, it may be put somewhere else. pop @{ $self->{queue} }; if ($top->next) { unshift @{ $self->{queue} }, $top; } $top = $self->{queue}[0]; } return 1; } 1;
carlgao/lenga
images/lenny64-peon/usr/share/perl5/Plucene/Index/SegmentsTermEnum.pm
Perl
mit
1,638
# File: SQLite.pm # # Purpose: SQLite backend for storing and retreiving quotegrabs. # SPDX-FileCopyrightText: 2021 Pragmatic Software <pragma78@gmail.com> # SPDX-License-Identifier: MIT package PBot::Plugin::Quotegrabs::Storage::SQLite; use PBot::Imports; use DBI; use Carp qw(shortmess); sub new { if (ref($_[1]) eq 'HASH') { Carp::croak("Options to " . __FILE__ . " should be key/value pairs, not hash reference"); } my ($class, %conf) = @_; my $self = bless {}, $class; $self->initialize(%conf); return $self; } sub initialize { my ($self, %conf) = @_; $self->{pbot} = delete $conf{pbot} // Carp::croak("Missing pbot reference in " . __FILE__); $self->{filename} = delete $conf{filename}; } sub begin { my $self = shift; $self->{pbot}->{logger}->log("Opening quotegrabs SQLite database: $self->{filename}\n"); $self->{dbh} = DBI->connect("dbi:SQLite:dbname=$self->{filename}", "", "", {RaiseError => 1, PrintError => 0, sqlite_unicode => 1}) or die $DBI::errstr; eval { $self->{dbh}->do(<< 'SQL'); CREATE TABLE IF NOT EXISTS Quotegrabs ( id INTEGER PRIMARY KEY, nick TEXT, channel TEXT, grabbed_by TEXT, text TEXT, timestamp NUMERIC ) SQL }; $self->{pbot}->{logger}->log($@) if $@; } sub end { my $self = shift; $self->{pbot}->{logger}->log("Closing quotegrabs SQLite database\n"); if (exists $self->{dbh} and defined $self->{dbh}) { $self->{dbh}->disconnect(); delete $self->{dbh}; } } sub add_quotegrab { my ($self, $quotegrab) = @_; my $id = eval { my $sth = $self->{dbh}->prepare('INSERT INTO Quotegrabs VALUES (?, ?, ?, ?, ?, ?)'); $sth->bind_param(1, undef); $sth->bind_param(2, $quotegrab->{nick}); $sth->bind_param(3, $quotegrab->{channel}); $sth->bind_param(4, $quotegrab->{grabbed_by}); $sth->bind_param(5, $quotegrab->{text}); $sth->bind_param(6, $quotegrab->{timestamp}); $sth->execute(); return $self->{dbh}->sqlite_last_insert_rowid(); }; $self->{pbot}->{logger}->log($@) if $@; return $id; } sub get_quotegrab { my ($self, $id) = @_; my $quotegrab = eval { my $sth = $self->{dbh}->prepare('SELECT * FROM Quotegrabs WHERE id == ?'); $sth->bind_param(1, $id); $sth->execute(); return $sth->fetchrow_hashref(); }; $self->{pbot}->{logger}->log($@) if $@; return $quotegrab; } sub get_random_quotegrab { my ($self, $nick, $channel, $text) = @_; $nick =~ s/\.?\*\??/%/g if defined $nick; $channel =~ s/\.?\*\??/%/g if defined $channel; $text =~ s/\.?\*\??/%/g if defined $text; $nick =~ s/\./_/g if defined $nick; $channel =~ s/\./_/g if defined $channel; $text =~ s/\./_/g if defined $text; my $quotegrab = eval { my $sql = 'SELECT * FROM Quotegrabs '; my @params; my $where = 'WHERE '; my $and = ''; if (defined $nick) { $sql .= $where . 'nick LIKE ? '; push @params, "$nick"; $where = ''; $and = 'AND '; } if (defined $channel) { $sql .= $where . $and . 'channel LIKE ? '; push @params, $channel; $where = ''; $and = 'AND '; } if (defined $text) { $sql .= $where . $and . 'text LIKE ? '; push @params, "%$text%"; } $sql .= 'ORDER BY RANDOM() LIMIT 1'; my $sth = $self->{dbh}->prepare($sql); $sth->execute(@params); return $sth->fetchrow_hashref(); }; $self->{pbot}->{logger}->log($@) if $@; return $quotegrab; } sub get_all_quotegrabs { my $self = shift; my $quotegrabs = eval { my $sth = $self->{dbh}->prepare('SELECT * from Quotegrabs'); $sth->execute(); return $sth->fetchall_arrayref({}); }; $self->{pbot}->{logger}->log($@) if $@; return $quotegrabs; } sub delete_quotegrab { my ($self, $id) = @_; eval { my $sth = $self->{dbh}->prepare('DELETE FROM Quotegrabs WHERE id == ?'); $sth->bind_param(1, $id); $sth->execute(); }; $self->{pbot}->{logger}->log($@) if $@; } 1;
pragma-/pbot
lib/PBot/Plugin/Quotegrabs/Storage/SQLite.pm
Perl
mit
4,289
#!/usr/bin/perl -w package ERDBLoad; use strict; use Tracer; use PageBuilder; use ERDB; use Stats; =head1 ERDB Table Load Utility Object =head2 Introduction This object is designed to assist with creating the load file for an ERDB data relation. The user constructs the object by specifying an ERDB object and a relation name. This create the load file for the relevant relation. The client then passes in data lines which are written to a file, and calls L</Finish> to close the file and get the statistics. This module makes use of the internal ERDB method C<_IsPrimary>. =cut # =head2 Public Methods =head3 new my $erload = ERDBLoad->new($erdb, $relationName, $directory, $loadOnly, $ignore); Begin loading an ERDB relation. =over 4 =item erdb ERDB object representing the target database. =item relationName Name of the relation being loaded. =item directory Name of the directory to use for the load files, WITHOUT a trailing slash. =item loadOnly TRUE if the data is to be loaded from an existing file, FALSE if a file is to be created. =item ignore TRUE if the data is to be discarded. This is used to save time when only a subset of the tables need to be loaded: the data for the ignored tables is simply discarded. =back =cut sub new { # Get the parameters. my ($class, $erdb, $relationName, $directory, $loadOnly, $ignore) = @_; # Validate the directory name. if (! -d $directory) { Confess("Load directory \"$directory\" not found."); } # Determine the name for this relation's load file. my $fileName = "$directory/$relationName.dtx"; # Declare the file handle variable. my $fileHandle; # Determine whether or not this is a simply keyed relation. For a simply keyed # relation, we can determine at run time if it is pre-sorted, and if so, skip # the sort step. my $sortString = $erdb->SortNeeded($relationName); # Get all of the key specifiers in the sort string. my @specs = grep { $_ =~ /-k\S+/ } split /\s+/, $sortString; # We are pre-sortable if the key is a single, non-numeric field at the beginning. If # we are pre-sortable, we'll check each incoming key and skip the sort step if the # keys are already in the correct order. my $preSortable = (scalar(@specs) == 1 && $specs[0] eq "-k1,1"); # Check to see if this is a load-only, ignore, or a generate-and-load. if ($ignore) { Trace("Relation $relationName will be ignored.") if T(2); $fileHandle = ""; } elsif ($loadOnly) { Trace("Relation $relationName will be loaded from $fileName.") if T(2); $fileHandle = ""; } else { # Compute the file namefor this relation. We will build a file on # disk and then sort it into the real file when we're done. my $fileString = ">$fileName.tmp"; # Open the output file and remember its handle. $fileHandle = Open(undef, $fileString); Trace("Relation $relationName load file created.") if T(2); } # Create the $erload object. my $retVal = { dbh => $erdb, fh => $fileHandle, fileName => $fileName, relName => $relationName, fileSize => 0, lineCount => 0, stats => Stats->new(), presorted => $preSortable, ignore => ($ignore ? 1 : 0), sortString => $sortString, presorted => $preSortable, lastKey => "" }; # Bless and return it. bless $retVal, $class; return $retVal; } =head3 Ignore my $flag = $erload->Ignore; Return TRUE if we are ignoring this table, else FALSE. =cut #: Return Type $; sub Ignore { # Get the parameters. my ($self) = @_; # Return the result. return $self->{ignore}; } =head3 Put my = $erload->Put($field1, $field2, ..., $fieldN); Write a line of data to the load file. This may also cause the load file to be closed and data read into the table. =over 4 =item field1, field2, ..., fieldN List of field values to be put into the data line. The field values must be in the order determined shown in the documentation for the table. Internal tabs and new-lines will automatically be escaped before the data line is formatted. =back =cut #: Return Type ; sub Put { # Get the ERDBLoad instance and the field list. my ($self, @rawFields) = @_; # Only proceed if we're not ignoring. if (! $self->{ignore}) { # Convert the hash-string fields to their digested value. $self->{dbh}->DigestFields($self->{relName}, \@rawFields); # Insure the field values are okay. my $truncates = $self->{dbh}->VerifyFields($self->{relName}, \@rawFields); # Run through the list of field values, escaping them. my @fields = map { Tracer::Escape($_) } @rawFields; # Form a data line from the fields. my $line = join("\t", @fields) . "\n"; # Write the new record to the load file. my $fh = $self->{fh}; print $fh $line; # Determine how long this will make the load file. my $lineLength = length $line; # Check to see if we're still pre-sorted. if ($self->{presorted}) { if ($fields[0] lt $self->{lastKey}) { # This key is out of order, so we're not pre-sorded any more. $self->{presorted} = 0; } else { # We're still pre-sorted, so save this key. $self->{lastKey} = $fields[0]; } } # Update the statistics. $self->{fileSize} += $lineLength; $self->{lineCount} ++; $self->Add("lineOut"); if ($truncates > 0) { $self->Add("truncated", $truncates); } } } =head3 Add my = $stats->Add($statName, $value); Increment the specified statistic. =over 4 =item statName Name of the statistic to increment. =item value (optional) Value by which to increment it. If omitted, C<1> is assumed. =back =cut #: Return Type ; sub Add { # Get the parameters. my ($self, $statName, $value) = @_; # Fix the value. if (! defined $value) { $value = 1; } # Increment the statistic. $self->{stats}->Add($statName, $value); } =head3 Finish my $stats = $erload->Finish(); Finish loading the table. This closes and sorts the load file. =over 4 =item RETURN Returns a statistics object describing what happened during the load and containing any error messages. =back =cut sub Finish { # Get this object instance. my ($self) = @_; if ($self->{fh}) { # Close the load file. close $self->{fh}; # Get the ERDB object. my $erdb = $self->{dbh}; # Get the output file name. my $fileName = $self->{fileName}; # Do we need a sort? if ($self->{presorted}) { # No, so just rename the file. Trace("$fileName is pre-sorted.") if T(3); unlink $fileName; rename "$fileName.tmp", $fileName; } else { # Get the sort command for this relation. my $sortCommand = $erdb->SortNeeded($self->{relName}); Trace("Sorting into $fileName with command: $sortCommand") if T(3); # Set up a timer. my $start = time(); # Execute the sort command and save the error output. my @messages = `$sortCommand 2>&1 1>$fileName <$fileName.tmp`; # Record the time spent $self->{stats}->Add(sortTime => (time() - $start)); # If there was no error, delete the temp file. if (! scalar(@messages)) { unlink "$fileName.tmp"; } else { # Here there was an error. Confess("Error messages from $sortCommand:\n" . join("\n", @messages)); } } # Tell the user we're done. Trace("Load file $fileName created.") if T(3); } # Return the statistics object. return $self->{stats}; } =head3 FinishAndLoad my $stats = $erload->FinishAndLoad(); Finish the load and load the table, returning the statistics. =cut sub FinishAndLoad { # Get the parameters. my ($self) = @_; # Finish the load file. my $retVal = $self->Finish(); # Load the table. my $newStats = $self->LoadTable(); # Accumulate the stats. $retVal->Accumulate($newStats); # Return the result. return $retVal; } =head3 RelName my $name = $erload->RelName; Name of the relation being loaded by this object. =cut sub RelName { # Get the object instance. my ($self) = @_; # Return the relation name. return $self->{relName}; } =head3 LoadTable my $stats = $erload->LoadTable(); Load the database table from the load file and return a statistics object. =cut sub LoadTable { # Get the parameters. my ($self) = @_; # Get the database object, the file name, and the relation name. my $erdb = $self->{dbh}; my $fileName = $self->{fileName}; my $relName = $self->{relName}; # Load the table. The third parameter indicates this is a drop and reload. my $retVal = $erdb->LoadTable($fileName, $relName, truncate => 1); # Return the result. return $retVal; } 1;
kbase/kb_seed
lib/ERDBLoad.pm
Perl
mit
9,410
#!/usr/bin/perl use strict; use warnings; use Digest::CRC qw(); use Getopt::Long; # Subroutine prototypes sub SYNC (); sub type2UCD_GUI(); sub Version1_MAP(); sub RNG_REQ(); sub RNG_RSP_GUI(); sub UCC_REQ(); sub UCC_RSP(); sub DSD_RSP(); sub DCC_REQ_GUI(); sub DCC_RSP_GUI(); sub DCC_ACK_GUI(); sub type29UCD_GUI(); sub INIT_RNG_REQ(); sub MDD_GUI(); sub B_INIT_RNG_REQ(); sub type35UCD_GUI(); sub request_minislots(); sub request_bytes(); sub random_bits; my $debug = 0; my $pcap_file = ""; my $packet_length; my $packet_value; my $pcap_header; my $packet_timestamp = "0000000000000000"; my $frame_number = 1; my $last_frame = 0; my $frame_type; my $write_all_flag = ''; my @all_frame_data = (); my @command_tlvs; my @command_subtlvs; my $clear_screen = 1; $pcap_header = "D4C3B2A1020004000000000000000000000004008F000000"; ################################################################################################# # START OF MAIN ################################################################################################# # Read potential command-line parameters my $result = GetOptions( 'pcap=s' => \$pcap_file, #Provide pcap file on command-line so user isn't prompted 'all' => \$write_all_flag, #Write out all TLVs/sub TLVs ); sub usage { print "\nUsage: $0 [--pcap=<filename>] [--all]\n\n"; print " --pcap = <filename>\n"; print " Provide pcap file without being prompted by application\n"; print " --all\n"; print " Write out all TLVs/sub TLVs\n"; exit(1); } if ($clear_screen && (!$write_all_flag)) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } if (!$pcap_file) { print "\n Pcap filename to be saved: "; $pcap_file = <>; } open PCAP_FILE, '>' . $pcap_file; binmode(PCAP_FILE); print PCAP_FILE pack "H*", $pcap_header; while (($last_frame != 1) && (!$write_all_flag)) { # check $write_all_flag to save another nesting of a simple if statement @command_tlvs = (); if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following packet types can be generated:\n\n"; print " 1) SYNC 14) REG-ACK 29) Type 29 UCD 44) REG-REQ-MP 59) DTP-ACK (N/A) \n"; print " 2) Type 2 UCD 15) DSA-REQ 30) INIT-RNG-REQ 45) REG-RSP-MP 60) DTP-INFO (N/A) \n"; print " 3a) Version 1 MAP 16) DSC-RSP 31) TST-REQ (N/A) 46) EM-REQ (N/A) \n"; print " 3b) Version 5 MAP (N/A) 17) DSA-ACK 32) DCD (N/A) 47) EM-RSP (N/A) \n"; print " 3c) Version 5 P-MAP (N/A) 18) DSC-REQ 33) MDD (N/A) 48) CM-STATUS-ACK (N/A) a) Request Frame (minislots) \n"; print " 4) RNG-REQ 19) DSC-RSP 34) B-INIT-RNG-REQ 49) OFDM Chan Descr (N/A) b) Request Frame (bytes) \n"; print " 5) RNG-RSP 20) DSC-ACK 35) Type 35 UCD 50) DPD (N/A) c) O-INIT-RNG-REQ (N/A) \n"; print " 6) REG-REQ 21) DSD-REQ 36) DBC-REQ 51) Type 51 UCD (N/A) \n"; print " 7) REG-RSP 22) DSD-RSP 37) DBC-RSP 52) ODS-REQ (N/A) \n"; print " 8) UCC-REQ 23) DCC-REQ 38) DBC-ACK 53) ODS-RSP (N/A) \n"; print " 9) UCC-RSP 24) DCC-RSP 39) DPV-REQ (N/A) 54) OPT-REQ (N/A) \n"; print " 10) TRI-TCD (N/A) 25) DCC-ACK 40) DPV-RSP (N/A) 55) OPT-RSP (N/A) \n"; print " 11) TRI-TSI (N/A) 26) DCI-REQ (N/A) 41) CM-STATUS (N/A) 56) OPT-ACK (N/A) \n"; print " 12) BPKM-REQ 27) DCI-RSP (N/A) 42) CM-CTRL-REQ (N/A) 57) DTP-REQ (N/A) \n"; print " 13) BPKM-RSP 28) UP-DIS (N/A) 43) CM-CTRL-RSP (N/A) 58) DTP-RSP (N/A) \n"; print "\n Frame " . $frame_number . " - Choose packet type which will be generated: "; $frame_type = <>; chomp $frame_type; if ($frame_type eq "1") { #No TLVs needed } elsif ($frame_type eq "2") { @command_tlvs = type2UCD_GUI(); } elsif ($frame_type eq "3a") { #No TLVs needed } elsif ($frame_type eq "4") { #No TLVs needed } elsif ($frame_type eq "5") { @command_tlvs = RNG_RSP_GUI(); } elsif ($frame_type eq "6") { # Add Annex C TLVs (REG_REQ) @command_tlvs = add_annex_c_tlvs_GUI(); } elsif ($frame_type eq "7") { # Add Annex C TLVs (REG_RSP) @command_tlvs = add_annex_c_tlvs_GUI(); } elsif ($frame_type eq "8") { #No TLVs needed } elsif ($frame_type eq "9") { #No TLVs needed } elsif ($frame_type eq "12") { # Add bpkm attributes (BPKM_REQ) @command_tlvs = add_bpkm_attributes_GUI() } elsif ($frame_type eq "13") { # Add bpkm attributes (BPKM_RSP) @command_tlvs = add_bpkm_attributes_GUI() } elsif ($frame_type eq "14") { # Add Annex C TLVs (REG_ACK) @command_tlvs = add_annex_c_tlvs_GUI(); } elsif ($frame_type eq "15") { # Add Annex C TLVs (DSA_REQ) @command_tlvs = add_annex_c_tlvs_GUI(); } elsif ($frame_type eq "16") { # Add Annex C TLVs (DSA_RSP) @command_tlvs = add_annex_c_tlvs_GUI(); } elsif ($frame_type eq "17") { # Add Annex C TLVs (DSA_ACK) @command_tlvs = add_annex_c_tlvs_GUI(); } elsif ($frame_type eq "18") { # Add Annex C TLVs (DSC_REQ) @command_tlvs = add_annex_c_tlvs_GUI(); } elsif ($frame_type eq "19") { # Add Annex C TLVs (DSC_RSP) @command_tlvs = add_annex_c_tlvs_GUI(); } elsif ($frame_type eq "20") { # Add Annex C TLVs (DSC_ACK) @command_tlvs = add_annex_c_tlvs_GUI(); } elsif ($frame_type eq "21") { # Add Annex C TLVs (DSD_REQ) @command_tlvs = add_annex_c_tlvs_GUI(); } elsif ($frame_type eq "22") { #No TLVs needed } elsif ($frame_type eq "23") { @command_tlvs = DCC_REQ_GUI(); } elsif ($frame_type eq "24") { @command_tlvs = DCC_RSP_GUI(); } elsif ($frame_type eq "25") { @command_tlvs = DCC_ACK_GUI(); } elsif ($frame_type eq "29") { @command_tlvs = type29UCD_GUI(); } elsif ($frame_type eq "30") { #No TLVs needed } elsif ($frame_type eq "33") { @command_tlvs = MDD_GUI(); } elsif ($frame_type eq "34") { #No TLVs needed } elsif ($frame_type eq "35") { @command_tlvs = type35UCD_GUI(); } elsif ($frame_type eq "36") { # Add Annex C TLVs (DBC_REQ) @command_tlvs = add_annex_c_tlvs_GUI(); } elsif ($frame_type eq "37") { # Add Annex C TLVs (DBC_RSP) @command_tlvs = add_annex_c_tlvs_GUI(); } elsif ($frame_type eq "38") { # Add Annex C TLVs (DBC_ACK) @command_tlvs = add_annex_c_tlvs_GUI(); } elsif ($frame_type eq "44") { # Add Annex C TLVs (REG_REQ_MP) @command_tlvs = add_annex_c_tlvs_GUI(); } elsif ($frame_type eq "45") { # Add Annex C TLVs (REG_RSP_MP) @command_tlvs = add_annex_c_tlvs_GUI(); } elsif ($frame_type eq "a") { #No TLVs needed } elsif ($frame_type eq "b") { #No TLVs needed } else { print "\n This is not a valid option ($frame_type). Calling EXIT... \n\n"; exit; } #Save the Frame type and any TLVs associated with it push @all_frame_data, [$frame_type]; foreach my $test_tlv (@command_tlvs) { push @{$all_frame_data[$frame_number-1]}, $test_tlv; } printf "\n Is this last Frame in the PCAP capture file? (Choose: 1 for YES / 0 for NO) "; $last_frame = <>; $frame_number++; } if ($write_all_flag) { @all_frame_data = ([1], [2, [1], [2], [3], [4, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]], [5, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14]], [6], [7], [15], [16], [18], [19]], ["3a"], [4], [5, [1], [2], [3], [4], [5], [6], [7]], [6, [1], [2], [3], [4, [1], [2], [3], [4], [5], [6], [7]], [5, [40], [48]], [45, [1], [2]]], [7, [1], [2], [3], [4, [1], [2], [3], [4], [5], [6], [7]], [5, [40], [48]], [45, [1], [2]]], [8], [9], [12, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [127]], [13, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [127]], [14, [1], [2], [3], [4, [1], [2], [3], [4], [5], [6], [7]], [5, [40], [48]], [45, [1], [2]]], [15, [1], [2], [3], [4, [1], [2], [3], [4], [5], [6], [7]], [5, [40], [48]], [45, [1], [2]]], [16, [1], [2], [3], [4, [1], [2], [3], [4], [5], [6], [7]], [5, [40], [48]], [45, [1], [2]]], [17, [1], [2], [3], [4, [1], [2], [3], [4], [5], [6], [7]], [5, [40], [48]], [45, [1], [2]]], [18, [1], [2], [3], [4, [1], [2], [3], [4], [5], [6], [7]], [5, [40], [48]], [45, [1], [2]]], [19, [1], [2], [3], [4, [1], [2], [3], [4], [5], [6], [7]], [5, [40], [48]], [45, [1], [2]]], [20, [1], [2], [3], [4, [1], [2], [3], [4], [5], [6], [7]], [5, [40], [48]], [45, [1], [2]]], [21, [1], [2], [3], [4, [1], [2], [3], [4], [5], [6], [7]], [5, [40], [48]], [45, [1], [2]]], [22], [23, [1], [2, [1], [2], [3], [4], [5], [6], [7]], [3], [4], [6], [7, [1], [2], [5]], [8], [27], [31]], [24, [1, [1], [2]], [27], [31]], [25, [27], [31]], [29, [1], [2], [3], [5, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18]], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19]], [30], [33, [1, [1], [2], [3], [4], [5], [6], [7]], [2, [1], [2]], [3], [4, [1], [2], [3]], [5, [1], [2]], [6], [7, [1], [2], [3], [4]], [8]], [34], [35, [1], [2], [3], [5, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18]], [6], [7], [8], [9], [10], [11], [12], [13], [15], [16], [17], [18], [19], [20], [21], [22]], [36, [1], [2], [3], [4, [1], [2], [3], [4], [5], [6], [7]], [5, [40], [48]], [45, [1], [2]]], [37, [1], [2], [3], [4, [1], [2], [3], [4], [5], [6], [7]], [5, [40], [48]], [45, [1], [2]]], [38, [1], [2], [3], [4, [1], [2], [3], [4], [5], [6], [7]], [5, [40], [48]], [45, [1], [2]]], [44, [1], [2], [3], [4, [1], [2], [3], [4], [5], [6], [7]], [5, [40], [48]], [45, [1], [2]]], [45, [1], [2], [3], [4, [1], [2], [3], [4], [5], [6], [7]], [5, [40], [48]], [45, [1], [2]]], ["a"], ["b"]); } printf "\n Your packets were stored in file: " . $pcap_file . "\n\n"; my $frame_count = 0; if ($debug) { printf "You requested the following data:\n"; foreach (@all_frame_data) { print "Frame type: $all_frame_data[$frame_count][0]\n"; my $tlv_count = 1; while (exists($all_frame_data[$frame_count][$tlv_count][0])) { print " TLV ($tlv_count): $all_frame_data[$frame_count][$tlv_count][0]\n"; my $subtlv_count = 1; while (exists($all_frame_data[$frame_count][$tlv_count][$subtlv_count][0])) { print " SubTLV ($subtlv_count): $all_frame_data[$frame_count][$tlv_count][$subtlv_count][0]\n"; $subtlv_count++; } $tlv_count++; } $frame_count++; } } $frame_count = 0; foreach (@all_frame_data) { $frame_type = $all_frame_data[$frame_count][0]; if ($frame_type eq "1") { ($packet_value, $packet_length) = SYNC(); } elsif ($frame_type eq "2") { ($packet_value, $packet_length) = type2UCD($frame_count); } elsif ($frame_type eq "3a") { ($packet_value, $packet_length) = Version1_MAP(); } elsif ($frame_type eq "4") { ($packet_value, $packet_length) = RNG_REQ(); } elsif ($frame_type eq "5") { ($packet_value, $packet_length) = RNG_RSP($frame_count); } elsif ($frame_type eq "6") { ($packet_value, $packet_length) = REG_REQ($frame_count); } elsif ($frame_type eq "7") { ($packet_value, $packet_length) = REG_RSP($frame_count); } elsif ($frame_type eq "8") { ($packet_value, $packet_length) = UCC_REQ(); } elsif ($frame_type eq "9") { ($packet_value, $packet_length) = UCC_RSP(); } elsif ($frame_type eq "12") { ($packet_value, $packet_length) = BPKM_REQ($frame_count); } elsif ($frame_type eq "13") { ($packet_value, $packet_length) = BPKM_RSP($frame_count); } elsif ($frame_type eq "14") { ($packet_value, $packet_length) = REG_ACK($frame_count); } elsif ($frame_type eq "15") { ($packet_value, $packet_length) = DSA_REQ($frame_count); } elsif ($frame_type eq "16") { ($packet_value, $packet_length) = DSA_RSP($frame_count); } elsif ($frame_type eq "17") { ($packet_value, $packet_length) = DSA_ACK($frame_count); } elsif ($frame_type eq "18") { ($packet_value, $packet_length) = DSC_REQ($frame_count); } elsif ($frame_type eq "19") { ($packet_value, $packet_length) = DSC_RSP($frame_count); } elsif ($frame_type eq "20") { ($packet_value, $packet_length) = DSC_ACK($frame_count); } elsif ($frame_type eq "21") { ($packet_value, $packet_length) = DSD_REQ($frame_count); } elsif ($frame_type eq "22") { ($packet_value, $packet_length) = DSD_RSP(); } elsif ($frame_type eq "23") { ($packet_value, $packet_length) = DCC_REQ($frame_count); } elsif ($frame_type eq "24") { ($packet_value, $packet_length) = DCC_RSP($frame_count); } elsif ($frame_type eq "25") { ($packet_value, $packet_length) = DCC_ACK($frame_count); } elsif ($frame_type eq "29") { ($packet_value, $packet_length) = type29UCD($frame_count); } elsif ($frame_type eq "30") { ($packet_value, $packet_length) = INIT_RNG_REQ(); } elsif ($frame_type eq "33") { ($packet_value, $packet_length) = MDD($frame_count); } elsif ($frame_type eq "34") { ($packet_value, $packet_length) = B_INIT_RNG_REQ(); } elsif ($frame_type eq "35") { ($packet_value, $packet_length) = type35UCD($frame_count); } elsif ($frame_type eq "36") { ($packet_value, $packet_length) = DBC_REQ($frame_count); } elsif ($frame_type eq "37") { ($packet_value, $packet_length) = DBC_RSP($frame_count); } elsif ($frame_type eq "38") { ($packet_value, $packet_length) = DBC_ACK($frame_count); } elsif ($frame_type eq "44") { ($packet_value, $packet_length) = REG_REQ_MP($frame_count); } elsif ($frame_type eq "45") { ($packet_value, $packet_length) = REG_RSP_MP($frame_count); } elsif ($frame_type eq "a") { ($packet_value, $packet_length) = request_minislots(); } elsif ($frame_type eq "b") { ($packet_value, $packet_length) = request_bytes(); } else { print "\n This is not a valid option ($frame_type). Calling EXIT... \n\n"; exit; } print PCAP_FILE pack "H*", $packet_timestamp; print PCAP_FILE pack "V", $packet_length; print PCAP_FILE pack "V", $packet_length; print PCAP_FILE pack "H*", $packet_value; $frame_count++; } close PCAP_FILE; ################################################################################################# # END OF MAIN ################################################################################################# sub SYNC() { our $packet_value; our $packet_length = 0; # Add SYNC Message $packet_value = "000000" . sprintf("%02x", rand(0xFF)); $packet_length = $packet_length + 4; # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "01", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 0, 0); return ($packet_value, $packet_length); } sub type2UCD_GUI() { our @command_tlvs = (); our @command_subtlvs; our $last_tlv = 0; our $last_sub_tlv = 0; our $choosen_tlv; our $choosen_sub_tlv; our $tlv_number = 1; our $sub_tlv_number = 1; # Ask for TLV data while ($last_tlv != 1) { @command_subtlvs = (); $sub_tlv_number = 1; if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following TLVs can be added:\n\n"; print " 1) Modulation Rate\n"; print " 2) Frequency\n"; print " 3) Preamble Pattern\n"; print " 4) Burst Descriptor (DOCSIS 1.x)\n"; print " ...\n"; print " 5) Burst Descriptor (DOCSIS 2.0/3.0)\n"; print " ...\n"; print " 6) Extended Preamble Pattern\n"; print " 7) S-CDMA Mode Enable\n"; print " 15) Maintain Power Spectral Density\n"; print " 16) Ranging Required\n"; print " 18) Ranging Hold-Off Priority Field\n"; print " 19) Channel Class ID\n"; print "\n TLV " . $tlv_number . " - Choose TLV which should be added: "; $choosen_tlv = <>; chomp $choosen_tlv; if ($choosen_tlv eq "1") { } elsif ($choosen_tlv eq "2") { } elsif ($choosen_tlv eq "3") { } elsif ($choosen_tlv eq "4") { # Create BURST4 sub-TLVs $last_sub_tlv = 0; while ($last_sub_tlv != 1) { if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following sub-TLVs can be added:\n\n"; print " 1) Modulation Type\n"; print " 2) Differential Encoding\n"; print " 3) Preamble Length\n"; print " 4) Preamble Value Offset\n"; print " 5) FEC Error Correction (T)\n"; print " 6) FEC Codeword Information Bytes (k)\n"; print " 7) Scrambler Seed\n"; print " 8) Maximum Burst Size\n"; print " 9) Guard Time Size\n"; print " 10) Last Codeword Length\n"; print " 11) Scrambler on/off\n"; print "\n sub-TLV " . $sub_tlv_number++ . " - Choose sub-TLV which should be added: "; $choosen_sub_tlv = <>; chomp $choosen_sub_tlv; if ($choosen_sub_tlv eq "1") { } elsif ($choosen_sub_tlv eq "2") { } elsif ($choosen_sub_tlv eq "3") { } elsif ($choosen_sub_tlv eq "4") { } elsif ($choosen_sub_tlv eq "5") { } elsif ($choosen_sub_tlv eq "6") { } elsif ($choosen_sub_tlv eq "7") { } elsif ($choosen_sub_tlv eq "8") { } elsif ($choosen_sub_tlv eq "9") { } elsif ($choosen_sub_tlv eq "10") { } elsif ($choosen_sub_tlv eq "11") { } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } push @command_subtlvs, [$choosen_sub_tlv]; printf "\n Is this last sub-TLV to be added? (Choose: 1 for YES / 0 for NO) "; $last_sub_tlv = <>; } } elsif ($choosen_tlv eq "5") { # Create BURST5 sub-TLVs $last_sub_tlv = 0; while ($last_sub_tlv != 1) { if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following sub-TLVs can be added:\n\n"; print " 1) Modulation Type\n"; print " 2) Differential Encoding\n"; print " 3) Preamble Length\n"; print " 4) Preamble Value Offset\n"; print " 5) FEC Error Correction (T)\n"; print " 6) FEC Codeword Information Bytes (k)\n"; print " 7) Scrambler Seed\n"; print " 8) Maximum Burst Size\n"; print " 9) Guard Time Size\n"; print " 10) Last Codeword Length\n"; print " 11) Scrambler on/off\n"; print " 12) R-S Interleaver Depth (Ir)\n"; print " 13) R-S Interleaver Block Size (Br)\n"; print " 14) Preamble Type\n"; print "\n sub-TLV " . $sub_tlv_number++ . " - Choose sub-TLV which should be added: "; $choosen_sub_tlv = <>; chomp $choosen_sub_tlv; if ($choosen_sub_tlv eq "1") { } elsif ($choosen_sub_tlv eq "2") { } elsif ($choosen_sub_tlv eq "3") { } elsif ($choosen_sub_tlv eq "4") { } elsif ($choosen_sub_tlv eq "5") { } elsif ($choosen_sub_tlv eq "6") { } elsif ($choosen_sub_tlv eq "7") { } elsif ($choosen_sub_tlv eq "8") { } elsif ($choosen_sub_tlv eq "9") { } elsif ($choosen_sub_tlv eq "10") { } elsif ($choosen_sub_tlv eq "11") { } elsif ($choosen_sub_tlv eq "12") { } elsif ($choosen_sub_tlv eq "13") { } elsif ($choosen_sub_tlv eq "14") { } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } push @command_subtlvs, [$choosen_sub_tlv]; printf "\n Is this last sub-TLV to be added? (Choose: 1 for YES / 0 for NO) "; $last_sub_tlv = <>; } } elsif ($choosen_tlv eq "6") { } elsif ($choosen_tlv eq "7") { } elsif ($choosen_tlv eq "15") { } elsif ($choosen_tlv eq "16") { } elsif ($choosen_tlv eq "18") { } elsif ($choosen_tlv eq "19") { } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } #Save the TLV push @command_tlvs, [$choosen_tlv]; #Save the Sub TLVs (if any) foreach my $subtlv (@command_subtlvs) { push @{$command_tlvs[$tlv_number-1]}, $subtlv; } printf "\n Is this last TLV to be added? (Choose: 1 for YES / 0 for NO) "; $last_tlv = <>; $tlv_number++; } return @command_tlvs; } sub type2UCD () { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; my $choosen_tlv; my $choosen_sub_tlv; my $tlv_number = 1; my $sub_tlv_number = 1; my $sub_tlv_value; my $sub_tlv_length; my $i; my $j; # Add Upstream Channel ID field $packet_value = sprintf("%02x", rand(0xFF)); $packet_length = 1; # Add Config Change Count field $packet_value = $packet_value . sprintf("%02x", rand(0xFF)); $packet_length = $packet_length + 1; # Add Minislot Size field $packet_value = $packet_value . sprintf("%02x", 2 ** rand(0x8)); $packet_length = $packet_length + 1; # Add Downstream Channel ID field $packet_value = $packet_value . sprintf("%02x", rand(0xFF)); $packet_length = $packet_length + 1; # Add TLV data while (exists($all_frame_data[$frame_index][$tlv_number][0])) { $choosen_tlv = $all_frame_data[$frame_index][$tlv_number][0]; if ($choosen_tlv eq "1") { $packet_value = $packet_value . "01" . "01" . sprintf("%02x", 2 ** rand(0x5)); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "2") { $packet_value = $packet_value . "02" . "04" . sprintf("%08x", (int(rand(80)) + 5) * 1000000); $packet_length = $packet_length + 6; } elsif ($choosen_tlv eq "3") { $i = int(rand(127)) + 1; $packet_value = $packet_value . "03" . sprintf("%02x", $i); for (my $j = 0; $j < $i; $j++) { $packet_value = $packet_value . sprintf("%02x", rand(0xFF)); } $packet_length = $packet_length + $i + 2; } elsif ($choosen_tlv eq "4") { # Create BURST4 sub-TLVs $sub_tlv_value = ""; $sub_tlv_length = 0; $sub_tlv_number = 1; while (exists($all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0])) { $choosen_sub_tlv = $all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0]; if ($choosen_sub_tlv eq "1") { $sub_tlv_value = $sub_tlv_value . "01" . "01" . sprintf("%02x", rand(7) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "2") { $sub_tlv_value = $sub_tlv_value . "02" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "3") { $sub_tlv_value = $sub_tlv_value . "03" . "02" . sprintf("%04x", rand(1536) + 1); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "4") { $sub_tlv_value = $sub_tlv_value . "04" . "02" . sprintf("%04x", rand(0xFFFF)); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "5") { $sub_tlv_value = $sub_tlv_value . "05" . "01" . sprintf("%02x", rand(17)); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "6") { $sub_tlv_value = $sub_tlv_value . "06" . "01" . sprintf("%02x", rand(238) + 16); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "7") { $sub_tlv_value = $sub_tlv_value . "07" . "02" . sprintf("%04x", rand(0xFFFF)); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "8") { $sub_tlv_value = $sub_tlv_value . "08" . "01" . sprintf("%02x", rand(0xFF) + 16); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "9") { $sub_tlv_value = $sub_tlv_value . "09" . "01" . sprintf("%02x", rand(0xFF)); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "10") { $sub_tlv_value = $sub_tlv_value . "0A" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "11") { $sub_tlv_value = $sub_tlv_value . "0B" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } $sub_tlv_number++; } $packet_value = $packet_value . "04" . sprintf("%02x", $sub_tlv_length + 1) . sprintf("%02x", int(rand(15)) + 1) . $sub_tlv_value; $packet_length = $packet_length + 3 + $sub_tlv_length; } elsif ($choosen_tlv eq "5") { # Create BURST5 sub-TLVs $sub_tlv_value = ""; $sub_tlv_length = 0; $sub_tlv_number = 1; while (exists($all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0])) { $choosen_sub_tlv = $all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0]; if ($choosen_sub_tlv eq "1") { $sub_tlv_value = $sub_tlv_value . "01" . "01" . sprintf("%02x", rand(7) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "2") { $sub_tlv_value = $sub_tlv_value . "02" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "3") { $sub_tlv_value = $sub_tlv_value . "03" . "02" . sprintf("%04x", rand(1536) + 1); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "4") { $sub_tlv_value = $sub_tlv_value . "04" . "02" . sprintf("%04x", rand(0xFFFF)); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "5") { $sub_tlv_value = $sub_tlv_value . "05" . "01" . sprintf("%02x", rand(17)); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "6") { $sub_tlv_value = $sub_tlv_value . "06" . "01" . sprintf("%02x", rand(238) + 16); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "7") { $sub_tlv_value = $sub_tlv_value . "07" . "02" . sprintf("%04x", rand(0xFFFF)); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "8") { $sub_tlv_value = $sub_tlv_value . "08" . "01" . sprintf("%02x", rand(0xFF) + 16); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "9") { $sub_tlv_value = $sub_tlv_value . "09" . "01" . sprintf("%02x", rand(0xFF)); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "10") { $sub_tlv_value = $sub_tlv_value . "0A" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "11") { $sub_tlv_value = $sub_tlv_value . "0B" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "12") { $sub_tlv_value = $sub_tlv_value . "0C" . "01" . sprintf("%02x", rand(0xFF)); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "13") { $sub_tlv_value = $sub_tlv_value . "0D" . "02" . sprintf("%04x", rand(0xFFFF)); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "14") { $sub_tlv_value = $sub_tlv_value . "0E" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } $sub_tlv_number++; } $packet_value = $packet_value . "05" . sprintf("%02x", $sub_tlv_length + 1) . sprintf("%02x", int(rand(15)) + 1) . $sub_tlv_value; $packet_length = $packet_length + 3 + $sub_tlv_length; } elsif ($choosen_tlv eq "6") { $i = int(rand(63)) + 1; $packet_value = $packet_value . "06" . sprintf("%02x", $i); for (my $j = 0; $j < $i; $j++) { $packet_value = $packet_value . sprintf("%02x", rand(0xFF)); } $packet_length = $packet_length + $i + 2; } elsif ($choosen_tlv eq "7") { $packet_value = $packet_value . "07" . "01" . sprintf("%02x", int(rand(2)) + 1); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "15") { $packet_value = $packet_value . "0F" . "01" . sprintf("%02x", int(rand(2)) + 1); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "16") { $packet_value = $packet_value . "10" . "01" . sprintf("%02x", int(rand(3))); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "18") { $packet_value = $packet_value . "12" . "04" . random_bits(32, 0xFFFF000F); $packet_length = $packet_length + 6; } elsif ($choosen_tlv eq "19") { $packet_value = $packet_value . "13" . "04" . random_bits(32, 0xFFFF000F); $packet_length = $packet_length + 6; } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } $tlv_number++; } # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "02", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length, @command_tlvs); } sub Version1_MAP() { our $packet_value; our $packet_length = 0; our $elements; our $i; # Add Upstream channel ID $packet_value = random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add UCD Count $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Number of elements $elements = int(rand(240)) + 1; $packet_value = $packet_value . sprintf("%02x", $elements); $packet_length = $packet_length + 1; # Add Reserved $packet_value = $packet_value . "00"; $packet_length = $packet_length + 1; # Add Alloc Start Time $packet_value = $packet_value . random_bits(32, 0xFFFFFFFF); $packet_length = $packet_length + 4; # Add Ack Time $packet_value = $packet_value . random_bits(32, 0xFFFFFFFF); $packet_length = $packet_length + 4; # Add Ranging Backoff Start $packet_value = $packet_value . sprintf("%02x", rand(16)); $packet_length = $packet_length + 1; # Add Ranging Backoff End $packet_value = $packet_value . sprintf("%02x", rand(16)); $packet_length = $packet_length + 1; # Data Backoff Start $packet_value = $packet_value . sprintf("%02x", rand(16)); $packet_length = $packet_length + 1; # Data Backoff End $packet_value = $packet_value . sprintf("%02x", rand(16)); $packet_length = $packet_length + 1; # Add elements for (my $i=0; $i < $elements; $i++) { # Add element $packet_value = $packet_value . random_bits(32, 0xFFFFFFFF); $packet_length = $packet_length + 4; } # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "03", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub RNG_REQ() { our $packet_value; our $packet_length = 0; # Add Service Identifier $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Downstream Channel ID $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Reserved Field $packet_value = $packet_value . "00"; $packet_length = $packet_length + 1; # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "04", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub RNG_RSP_GUI() { our @command_tlvs = (); our $last_tlv = 0; our $choosen_tlv; our $tlv_number = 1; while ($last_tlv != 1) { if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following TLVs can be added:\n\n"; print " 1) Timing Adjuts, Integer Part\n"; print " 2) Power Level Adjust\n"; print " 3) Offset Frequency Adjust\n"; print " 4) Transmit Equalization Adjust\n"; print " 5) Ranging Status\n"; print " 6) Downstream frequency override\n"; print " 7) Upstream channel ID override\n"; print "\n TLV " . $tlv_number . " - Choose TLV which should be added: "; $choosen_tlv = <>; chomp $choosen_tlv; if ($choosen_tlv eq "1") { } elsif ($choosen_tlv eq "2") { } elsif ($choosen_tlv eq "3") { } elsif ($choosen_tlv eq "4") { } elsif ($choosen_tlv eq "5") { } elsif ($choosen_tlv eq "6") { } elsif ($choosen_tlv eq "7") { } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } #Save the TLV push @command_tlvs, [$choosen_tlv]; printf "\n Is this last TLV to be added? (Choose: 1 for YES / 0 for NO) "; $last_tlv = <>; $tlv_number++; } return @command_tlvs; } sub RNG_RSP() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; our $choosen_tlv; our $tlv_number = 1; our $i; our $j; # Add SID $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Upstream Channel ID $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add TLV data while (exists($all_frame_data[$frame_index][$tlv_number][0])) { $choosen_tlv = $all_frame_data[$frame_index][$tlv_number][0]; if ($choosen_tlv eq "1") { $packet_value = $packet_value . "01" . "04" . random_bits(32, 0xFFFFFFFF); $packet_length = $packet_length + 6; } elsif ($choosen_tlv eq "2") { $packet_value = $packet_value . "02" . "01" . random_bits(8, 0xFF); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "3") { $packet_value = $packet_value . "03" . "02" . random_bits(16, 0xFFFF); $packet_length = $packet_length + 4; } elsif ($choosen_tlv eq "4") { # Value 32 was choosen random, could not find the maximum value in the spec. $i = int(rand(32)) + 1; $packet_value = $packet_value . "04" . sprintf("%02x", $i); for (my $j = 0; $j < $i; $j++) { $packet_value = $packet_value . sprintf("%02x", rand(0xFF)); } $packet_length = $packet_length + $i + 2; } elsif ($choosen_tlv eq "5") { $packet_value = $packet_value . "05" . "01" . sprintf("%02x", int(rand(3)) + 1); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "6") { $packet_value = $packet_value . "06" . "04" . sprintf("%08x", (int(rand(1686)) + 108) * 1000000); $packet_length = $packet_length + 6; } elsif ($choosen_tlv eq "7") { $packet_value = $packet_value . "07" . "01" . random_bits(8, 0xFF); $packet_length = $packet_length + 3; } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } $tlv_number++; } # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "05", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub REG_REQ() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; # Add Temporary Service Identifier $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Annex C TLVs ($packet_value, $packet_length) = add_annex_c_tlvs($frame_index, $packet_value, $packet_length); # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "06", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub REG_RSP() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; # Add Service Identifier $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Response Code $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Annex C TLVs ($packet_value, $packet_length) = add_annex_c_tlvs($frame_index, $packet_value, $packet_length); # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "07", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub UCC_REQ() { our $packet_value; our $packet_length = 0; # Add Upstream Channel ID $packet_value = random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "08", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub UCC_RSP() { our $packet_value; our $packet_length = 0; # Add Upstream Channel ID $packet_value = random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "09", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub BPKM_REQ() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; # Add Code Field $packet_value = sprintf("%02x", (int(rand(16)))); $packet_length = $packet_length + 1; # Add Identifier Field $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Attributes ($packet_value, $packet_length) = add_bpkm_attributes($frame_index, $packet_value, $packet_length); # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "0C", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub BPKM_RSP() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; # Add Code Field $packet_value = sprintf("%02x", (int(rand(16)))); $packet_length = $packet_length + 1; # Add Identifier Field $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Attributes ($packet_value, $packet_length) = add_bpkm_attributes($frame_index, $packet_value, $packet_length); # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "0D", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub REG_ACK() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; # Add Service Identifier $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Confirmation Code $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Annex C TLVs ($packet_value, $packet_length) = add_annex_c_tlvs($frame_index, $packet_value, $packet_length); # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "0E", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub DSA_REQ() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; # Add Transaction ID $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Annex C TLVs ($packet_value, $packet_length) = add_annex_c_tlvs($frame_index, $packet_value, $packet_length); # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "0F", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub DSA_RSP() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; # Add Transaction ID $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Confirmation Code $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Annex C TLVs ($packet_value, $packet_length) = add_annex_c_tlvs($frame_index, $packet_value, $packet_length); # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "10", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub DSA_ACK() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; # Add Transaction ID $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Confirmation Code $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Annex C TLVs ($packet_value, $packet_length) = add_annex_c_tlvs($frame_index, $packet_value, $packet_length); # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "11", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub DSC_REQ() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; # Add Transaction ID $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Annex C TLVs ($packet_value, $packet_length) = add_annex_c_tlvs($frame_index, $packet_value, $packet_length); # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "12", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub DSC_RSP() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; # Add Transaction ID $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Confirmation Code $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Annex C TLVs ($packet_value, $packet_length) = add_annex_c_tlvs($frame_index, $packet_value, $packet_length); # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "13", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub DSC_ACK() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; # Add Transaction ID $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Confirmation Code $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Annex C TLVs ($packet_value, $packet_length) = add_annex_c_tlvs($frame_index, $packet_value, $packet_length); # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "14", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub DSD_REQ() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; # Add Transaction ID $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Reserved field $packet_value = $packet_value . "0000"; $packet_length = $packet_length + 2; # Add Service Flow ID $packet_value = $packet_value . random_bits(32, 0xFFFFFFFF); $packet_length = $packet_length + 4; # Add Annex C TLVs ($packet_value, $packet_length) = add_annex_c_tlvs($frame_index, $packet_value, $packet_length); # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "15", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub DSD_RSP() { our $packet_value; our $packet_length = 0; # Add Transaction ID $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Confirmation Code $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Reserved field $packet_value = $packet_value . "00"; $packet_length = $packet_length + 1; # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "16", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub DCC_REQ_GUI () { our @command_tlvs = (); our @command_subtlvs; our $choosen_tlv; our $choosen_sub_tlv; our $last_tlv = 0; our $last_sub_tlv = 0; our $tlv_number = 1; our $sub_tlv_number = 1; # Add Transaction ID # Add TLV Encoded information while ($last_tlv != 1) { @command_subtlvs = (); $sub_tlv_number = 1; if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following TLVs can be added:\n\n"; print " 1) Upstream Channel ID\n"; print " 2) Downstream Parameters\n"; print " ...\n"; print " 3) Initialization Technique\n"; print " 4) UCD Substitution\n"; print " 6) Security Association Identifier (SAID) Substitution\n"; print " 7) Service Flow Substitutions\n"; print " ...\n"; print " 8) CMTS MAC Address\n"; print " 27) HMAC-Digest\n"; print " 31) Key Sequence Number\n"; print "\n TLV " . $tlv_number . " - Choose which TLV will be generated: "; $choosen_tlv = <>; chomp $choosen_tlv; if ($choosen_tlv eq "1") { } elsif ($choosen_tlv eq "2") { $last_sub_tlv = 0; while ($last_sub_tlv != 1) { if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Class of Service sub-TLVs which can be added:\n\n"; print " 1) Downstream Frequency\n"; print " 2) Downstream Modulation Type\n"; print " 3) Downstream Symbol Rate\n"; print " 4) Downstream Interleaver Depth\n"; print " 5) Downstream Channel Identifier\n"; print " 6) SYNC Substitution\n"; print " 7) OFDM Block Frequency\n"; print "\n sub-TLV " . $sub_tlv_number++ . " - Choose which TLV will be generated: "; $choosen_sub_tlv = <>; chomp $choosen_sub_tlv; if ($choosen_sub_tlv eq "1") { } elsif ($choosen_sub_tlv eq "2") { } elsif ($choosen_sub_tlv eq "3") { } elsif ($choosen_sub_tlv eq "4") { } elsif ($choosen_sub_tlv eq "5") { } elsif ($choosen_sub_tlv eq "6") { } elsif ($choosen_sub_tlv eq "7") { } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } push @command_subtlvs, [$choosen_sub_tlv]; print "\n Is this last sub-TLV for this packet? (Choose: 1 for YES / 0 for NO) "; $last_sub_tlv = <>; } } elsif ($choosen_tlv eq "3") { } elsif ($choosen_tlv eq "4") { } elsif ($choosen_tlv eq "6") { } elsif ($choosen_tlv eq "7") { $last_sub_tlv = 0; while ($last_sub_tlv != 1) { if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Class of Service sub-TLVs which can be added:\n\n"; print " 1) Service Flow Identifier Substitution\n"; print " 2) Service Identifier Substitution\n"; print " 5) Unsolicited Grant Time Reference Substitution\n"; print "\n sub-TLV " . $sub_tlv_number++ . " - Choose which TLV will be generated: "; $choosen_sub_tlv = <>; chomp $choosen_sub_tlv; if ($choosen_sub_tlv eq "1") { } elsif ($choosen_sub_tlv eq "2") { } elsif ($choosen_sub_tlv eq "5") { } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } push @command_subtlvs, [$choosen_sub_tlv]; print "\n Is this last sub-TLV for this packet? (Choose: 1 for YES / 0 for NO) "; $last_sub_tlv = <>; } } elsif ($choosen_tlv eq "8") { } elsif ($choosen_tlv eq "27") { } elsif ($choosen_tlv eq "31") { } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } #Save the TLV push @command_tlvs, [$choosen_tlv]; #Save the Sub TLVs (if any) foreach my $subtlv (@command_subtlvs) { push @{$command_tlvs[$tlv_number-1]}, $subtlv; } print "\n Is this last TLV for this packet? (Choose: 1 for YES / 0 for NO) "; $last_tlv = <>; $tlv_number++; } return @command_tlvs; } sub DCC_REQ () { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; our $tlv_number = 1; our $choosen_tlv; our $sub_tlv_number = 1; our $choosen_sub_tlv; our $sub_tlv_length = 0; our $sub_tlv_value = ""; # Add Transaction ID $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add TLV Encoded information while (exists($all_frame_data[$frame_index][$tlv_number][0])) { $choosen_tlv = $all_frame_data[$frame_index][$tlv_number][0]; if ($choosen_tlv eq "1") { $packet_value = $packet_value . "01" . "01" . random_bits(8, 0xFF); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "2") { $sub_tlv_value = ""; $sub_tlv_length = 0; $sub_tlv_number = 1; while (exists($all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0])) { $choosen_sub_tlv = $all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0]; if ($choosen_sub_tlv eq "1") { $sub_tlv_value = $sub_tlv_value . "01" . "04" . sprintf("%08x", (int(rand(1686)) + 108) * 1000000); $sub_tlv_length = $sub_tlv_length + 6; } elsif ($choosen_sub_tlv eq "2") { $sub_tlv_value = $sub_tlv_value . "02" . "01" . sprintf("%02x", (int(rand(3)))); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "3") { $sub_tlv_value = $sub_tlv_value . "03" . "01" . sprintf("%02x", (int(rand(3)))); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "4") { $sub_tlv_value = $sub_tlv_value . "04" . "02" . random_bits(16, 0xFFFF); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "5") { $sub_tlv_value = $sub_tlv_value . "05" . "01" . random_bits(8, 0xFF); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "6") { $sub_tlv_value = $sub_tlv_value . "06" . "01" . sprintf("%02x", (int(rand(2)))); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "7") { $sub_tlv_value = $sub_tlv_value . "07" . "04" . sprintf("%08x", (int(rand(1686)) + 108) * 1000000); $sub_tlv_length = $sub_tlv_length + 6; } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } $sub_tlv_number++; } $packet_value = $packet_value . "02" . sprintf("%02x", $sub_tlv_length) . $sub_tlv_value; $packet_length = $packet_length + $sub_tlv_length + 2; } elsif ($choosen_tlv eq "3") { $packet_value = $packet_value . "03" . "01" . sprintf("%02x", (int(rand(5)))); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "4") { # TODO This has to be a full UCD packet $packet_value = $packet_value . "04" . "10" . random_bits(32, 0xFFFFFFFF) . random_bits(32, 0xFFFFFFFF) . random_bits(32, 0xFFFFFFFF) . random_bits(32, 0xFFFFFFFF); $packet_length = $packet_length + 18; } elsif ($choosen_tlv eq "6") { $packet_value = $packet_value . "06" . "04" . random_bits(16, 0x3FFF) . random_bits(16, 0x3FFF); $packet_length = $packet_length + 6; } elsif ($choosen_tlv eq "7") { $sub_tlv_value = ""; $sub_tlv_length = 0; $sub_tlv_number = 1; while (exists($all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0])) { $choosen_sub_tlv = $all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0]; if ($choosen_sub_tlv eq "1") { $sub_tlv_value = $sub_tlv_value . "01" . "08" . random_bits(32, 0xFFFFFFFF) . random_bits(32, 0xFFFFFFFF); $sub_tlv_length = $sub_tlv_length + 10; } elsif ($choosen_sub_tlv eq "2") { $sub_tlv_value = $sub_tlv_value . "02" . "04" . random_bits(16, 0x3FFF) . random_bits(16, 0x3FFF); $sub_tlv_length = $sub_tlv_length + 6; } elsif ($choosen_sub_tlv eq "5") { $sub_tlv_value = $sub_tlv_value . "05" . "04" . random_bits(32, 0xFFFFFFFF); $sub_tlv_length = $sub_tlv_length + 6; } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } $sub_tlv_number++; } $packet_value = $packet_value . "07" . sprintf("%02x", $sub_tlv_length) . $sub_tlv_value; $packet_length = $packet_length + $sub_tlv_length + 2; } elsif ($choosen_tlv eq "8") { $packet_value = $packet_value . "08" . "06" . random_bits(24, 0xFFFFFF) . random_bits(24, 0xFFFFFF); $packet_length = $packet_length + 8; } elsif ($choosen_tlv eq "27") { $packet_value = $packet_value . "1B" . "14" . random_bits(32, 0xFFFFFFFF) . random_bits(32, 0xFFFFFFFF) . random_bits(32, 0xFFFFFFF) . random_bits(32, 0xFFFFFFFF) . random_bits(32, 0xFFFFFFFF); $packet_length = $packet_length + 22; } elsif ($choosen_tlv eq "31") { $packet_value = $packet_value . "1F" . "01" . sprintf("%02x", (int(rand(16)))); $packet_length = $packet_length + 3; } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } $tlv_number++; } # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "17", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub DCC_RSP_GUI () { our @command_tlvs = (); our @command_subtlvs; our $choosen_tlv; our $choosen_sub_tlv; our $last_tlv = 0; our $last_sub_tlv = 0; our $tlv_number = 1; our $sub_tlv_number = 1; # Ask for TLV Encoded information while ($last_tlv != 1) { @command_subtlvs = (); $sub_tlv_number = 1; if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following TLVs can be added:\n\n"; print " 1) CM Jump Time\n"; print " ...\n"; print " 27) HMAC-Digest\n"; print " 31) Key Sequence Number\n"; print "\n TLV " . $tlv_number . " - Choose which TLV will be generated: "; $choosen_tlv = <>; chomp $choosen_tlv; if ($choosen_tlv eq "1") { $last_sub_tlv = 0; while ($last_sub_tlv != 1) { if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n CM Jump Time sub-TLVs:\n\n"; print " 1) Length of Jump\n"; print " 2) Start Time of Jump\n"; print "\n sub-TLV " . $sub_tlv_number++ . " - Choose which TLV will be generated: "; $choosen_sub_tlv = <>; chomp $choosen_sub_tlv; if ($choosen_sub_tlv eq "1") { } elsif ($choosen_sub_tlv eq "2") { } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } push @command_subtlvs, [$choosen_sub_tlv]; print "\n Is this last sub-TLV for this packet? (Choose: 1 for YES / 0 for NO) "; $last_sub_tlv = <>; } } elsif ($choosen_tlv eq "27") { } elsif ($choosen_tlv eq "31") { } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } #Save the TLV push @command_tlvs, [$choosen_tlv]; #Save the Sub TLVs (if any) foreach my $subtlv (@command_subtlvs) { push @{$command_tlvs[$tlv_number-1]}, $subtlv; } print "\n Is this last TLV for this packet? (Choose: 1 for YES / 0 for NO) "; $last_tlv = <>; $tlv_number++; } return @command_tlvs; } sub DCC_RSP () { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; our $tlv_number = 1; our $choosen_tlv; our $sub_tlv_number = 1; our $choosen_sub_tlv; our $sub_tlv_length = 0; our $sub_tlv_value = ""; # Add Transaction ID $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Confirmation Code $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add TLV Encoded information while (exists($all_frame_data[$frame_index][$tlv_number][0])) { $choosen_tlv = $all_frame_data[$frame_index][$tlv_number][0]; if ($choosen_tlv eq "1") { $sub_tlv_value = ""; $sub_tlv_length = 0; $sub_tlv_number = 1; while (exists($all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0])) { $choosen_sub_tlv = $all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0]; if ($choosen_sub_tlv eq "1") { $sub_tlv_value = $sub_tlv_value . "01" . "04" . random_bits(32, 0xFFFFFFFF); $sub_tlv_length = $sub_tlv_length + 6; } elsif ($choosen_sub_tlv eq "2") { $sub_tlv_value = $sub_tlv_value . "02" . "08" . random_bits(32, 0xFFFFFFFF) . random_bits(32, 0xFFFFFFFF); $sub_tlv_length = $sub_tlv_length + 10; } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } $sub_tlv_number++; } $packet_value = $packet_value . "01" . sprintf("%02x", $sub_tlv_length) . $sub_tlv_value; $packet_length = $packet_length + $sub_tlv_length + 2; } elsif ($choosen_tlv eq "27") { $packet_value = $packet_value . "1B" . "14" . random_bits(32, 0xFFFFFFFF) . random_bits(32, 0xFFFFFFFF) . random_bits(32, 0xFFFFFFF) . random_bits(32, 0xFFFFFFFF) . random_bits(32, 0xFFFFFFFF); $packet_length = $packet_length + 22; } elsif ($choosen_tlv eq "31") { $packet_value = $packet_value . "1F" . "01" . sprintf("%02x", (int(rand(16)))); $packet_length = $packet_length + 3; } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } $tlv_number++; } # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "18", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub DCC_ACK_GUI() { our @command_tlvs = (); our $choosen_tlv; our $last_tlv = 0; our $tlv_number = 1; # Add TLV Encoded information while ($last_tlv != 1) { if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following TLVs can be added:\n\n"; print " 27) HMAC-Digest\n"; print " 31) Key Sequence Number\n"; print "\n TLV " . $tlv_number . " - Choose which TLV will be generated: "; $choosen_tlv = <>; chomp $choosen_tlv; if ($choosen_tlv eq "27") { } elsif ($choosen_tlv eq "31") { } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } #Save the TLV push @command_tlvs, [$choosen_tlv]; print "\n Is this last TLV for this packet? (Choose: 1 for YES / 0 for NO) "; $last_tlv = <>; $tlv_number++; } return @command_tlvs; } sub DCC_ACK() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; our $tlv_number = 1; our $choosen_tlv; # Add Transaction ID $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add TLV Encoded information while (exists($all_frame_data[$frame_index][$tlv_number][0])) { $choosen_tlv = $all_frame_data[$frame_index][$tlv_number][0]; if ($choosen_tlv eq "27") { $packet_value = $packet_value . "1B" . "14" . random_bits(32, 0xFFFFFFFF) . random_bits(32, 0xFFFFFFFF) . random_bits(32, 0xFFFFFFF) . random_bits(32, 0xFFFFFFFF) . random_bits(32, 0xFFFFFFFF); $packet_length = $packet_length + 22; } elsif ($choosen_tlv eq "31") { $packet_value = $packet_value . "1F" . "01" . sprintf("%02x", (int(rand(16)))); $packet_length = $packet_length + 3; } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } $tlv_number++; } # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "19", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub type29UCD_GUI() { our @command_tlvs = (); our @command_subtlvs; our $last_tlv = 0; our $last_sub_tlv = 0; our $choosen_tlv; our $choosen_sub_tlv; our $tlv_number = 1; our $sub_tlv_number = 1; # Ask for TLV data while ($last_tlv != 1) { @command_subtlvs = (); $sub_tlv_number = 1; if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following TLVs can be added:\n\n"; print " 1) Modulation Rate\n"; print " 2) Frequency\n"; print " 3) Preamble Pattern\n"; print " 5) Burst Descriptor (DOCSIS 2.0/3.0)\n"; print " ...\n"; print " 6) Extended Preamble Pattern\n"; print " 7) S-CDMA Mode Enable\n"; print " 8) S-CDMA Spreading Intervals per frame\n"; print " 9) S-CDMA Codes per Minislot\n"; print " 10) S-CDMA Number of Active Codes\n"; print " 11) S-CDMA Code Hopping Seed\n"; print " 12) S-CDMA US ratio numerator 'M'\n"; print " 13) S-CDMA US ratio denominator 'N'\n"; print " 14) S-CDMA Timestamp Snapshop\n"; print " 15) Maintain Power Spectral Density\n"; print " 16) Ranging Required\n"; print " 17) S-CDMA Maximum Scheduled Codes enabled\n"; print " 18) Ranging Hold-Off Priority Field\n"; print " 19) Channel Class ID\n"; print "\n TLV " . $tlv_number . " - Choose TLV which should be added: "; $choosen_tlv = <>; chomp $choosen_tlv; if ($choosen_tlv eq "1") { } elsif ($choosen_tlv eq "2") { } elsif ($choosen_tlv eq "3") { } elsif ($choosen_tlv eq "5") { # Create BURST5 sub-TLVs $last_sub_tlv = 0; while ($last_sub_tlv != 1) { if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following sub-TLVs can be added:\n\n"; print " 1) Modulation Type\n"; print " 2) Differential Encoding\n"; print " 3) Preamble Length\n"; print " 4) Preamble Value Offset\n"; print " 5) FEC Error Correction (T)\n"; print " 6) FEC Codeword Information Bytes (k)\n"; print " 7) Scrambler Seed\n"; print " 8) Maximum Burst Size\n"; print " 9) Guard Time Size\n"; print " 10) Last Codeword Length\n"; print " 11) Scrambler on/off\n"; print " 12) R-S Interleaver Depth (Ir)\n"; print " 13) R-S Interleaver Block Size (Br)\n"; print " 14) Preamble Type\n"; print " 15) S-CDMA Spreader on/off\n"; print " 16) S-CDMA Codes per Subframe\n"; print " 17) S-CDMA Framer Interleaving Step Size\n"; print " 18) TCM Encoding\n"; print "\n sub-TLV " . $sub_tlv_number++ . " - Choose sub-TLV which should be added: "; $choosen_sub_tlv = <>; chomp $choosen_sub_tlv; if ($choosen_sub_tlv eq "1") { } elsif ($choosen_sub_tlv eq "2") { } elsif ($choosen_sub_tlv eq "3") { } elsif ($choosen_sub_tlv eq "4") { } elsif ($choosen_sub_tlv eq "5") { } elsif ($choosen_sub_tlv eq "6") { } elsif ($choosen_sub_tlv eq "7") { } elsif ($choosen_sub_tlv eq "8") { } elsif ($choosen_sub_tlv eq "9") { } elsif ($choosen_sub_tlv eq "10") { } elsif ($choosen_sub_tlv eq "11") { } elsif ($choosen_sub_tlv eq "12") { } elsif ($choosen_sub_tlv eq "13") { } elsif ($choosen_sub_tlv eq "14") { } elsif ($choosen_sub_tlv eq "15") { } elsif ($choosen_sub_tlv eq "16") { } elsif ($choosen_sub_tlv eq "17") { } elsif ($choosen_sub_tlv eq "18") { } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } push @command_subtlvs, [$choosen_sub_tlv]; printf "\n Is this last sub-TLV to be added? (Choose: 1 for YES / 0 for NO) "; $last_sub_tlv = <>; } } elsif ($choosen_tlv eq "6") { } elsif ($choosen_tlv eq "7") { } elsif ($choosen_tlv eq "8") { } elsif ($choosen_tlv eq "9") { } elsif ($choosen_tlv eq "10") { } elsif ($choosen_tlv eq "11") { } elsif ($choosen_tlv eq "12") { } elsif ($choosen_tlv eq "13") { } elsif ($choosen_tlv eq "14") { } elsif ($choosen_tlv eq "15") { } elsif ($choosen_tlv eq "16") { } elsif ($choosen_tlv eq "17") { } elsif ($choosen_tlv eq "18") { } elsif ($choosen_tlv eq "19") { } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } #Save the TLV push @command_tlvs, [$choosen_tlv]; #Save the Sub TLVs (if any) foreach my $subtlv (@command_subtlvs) { push @{$command_tlvs[$tlv_number-1]}, $subtlv; } printf "\n Is this last TLV to be added? (Choose: 1 for YES / 0 for NO) "; $last_tlv = <>; $tlv_number++; } return @command_tlvs; } sub type29UCD() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; our $choosen_tlv; our $choosen_sub_tlv; our $tlv_number = 1; our $sub_tlv_number = 1; our $sub_tlv_value; our $sub_tlv_length; our $i; our $j; # Add Upstream Channel ID field $packet_value = sprintf("%02x", rand(0xFF)); $packet_length = 1; # Add Config Change Count field $packet_value = $packet_value . sprintf("%02x", rand(0xFF)); $packet_length = $packet_length + 1; # Add Minislot Size field $packet_value = $packet_value . sprintf("%02x", 2 ** rand(0x8)); $packet_length = $packet_length + 1; # Add Downstream Channel ID field $packet_value = $packet_value . sprintf("%02x", rand(0xFF)); $packet_length = $packet_length + 1; # Add TLV data while (exists($all_frame_data[$frame_index][$tlv_number][0])) { $choosen_tlv = $all_frame_data[$frame_index][$tlv_number][0]; if ($choosen_tlv eq "1") { $packet_value = $packet_value . "01" . "01" . sprintf("%02x", 2 ** rand(0x5)); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "2") { $packet_value = $packet_value . "02" . "04" . sprintf("%08x", (int(rand(80)) + 5) * 1000000); $packet_length = $packet_length + 6; } elsif ($choosen_tlv eq "3") { $i = int(rand(127)) + 1; $packet_value = $packet_value . "03" . sprintf("%02x", $i); for (my $j = 0; $j < $i; $j++) { $packet_value = $packet_value . sprintf("%02x", rand(0xFF)); } $packet_length = $packet_length + $i + 2; } elsif ($choosen_tlv eq "5") { # Create BURST5 sub-TLVs $sub_tlv_value = ""; $sub_tlv_length = 0; $sub_tlv_number = 1; while (exists($all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0])) { $choosen_sub_tlv = $all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0]; if ($choosen_sub_tlv eq "1") { $sub_tlv_value = $sub_tlv_value . "01" . "01" . sprintf("%02x", rand(7) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "2") { $sub_tlv_value = $sub_tlv_value . "02" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "3") { $sub_tlv_value = $sub_tlv_value . "03" . "02" . sprintf("%04x", rand(1536) + 1); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "4") { $sub_tlv_value = $sub_tlv_value . "04" . "02" . sprintf("%04x", rand(0xFFFF)); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "5") { $sub_tlv_value = $sub_tlv_value . "05" . "01" . sprintf("%02x", rand(17)); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "6") { $sub_tlv_value = $sub_tlv_value . "06" . "01" . sprintf("%02x", rand(238) + 16); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "7") { $sub_tlv_value = $sub_tlv_value . "07" . "02" . sprintf("%04x", rand(0xFFFF)); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "8") { $sub_tlv_value = $sub_tlv_value . "08" . "01" . sprintf("%02x", rand(0xFF) + 16); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "9") { $sub_tlv_value = $sub_tlv_value . "09" . "01" . sprintf("%02x", rand(0xFF)); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "10") { $sub_tlv_value = $sub_tlv_value . "0A" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "11") { $sub_tlv_value = $sub_tlv_value . "0B" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "12") { $sub_tlv_value = $sub_tlv_value . "0C" . "01" . sprintf("%02x", rand(0xFF)); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "13") { $sub_tlv_value = $sub_tlv_value . "0D" . "02" . sprintf("%04x", rand(0xFFFF)); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "14") { $sub_tlv_value = $sub_tlv_value . "0E" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "15") { $sub_tlv_value = $sub_tlv_value . "0F" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "16") { $sub_tlv_value = $sub_tlv_value . "10" . "01" . sprintf("%02x", rand(128) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "17") { $sub_tlv_value = $sub_tlv_value . "11" . "01" . sprintf("%02x", rand(31) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "18") { $sub_tlv_value = $sub_tlv_value . "12" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } $sub_tlv_number++; } $packet_value = $packet_value . "05" . sprintf("%02x", $sub_tlv_length + 1) . sprintf("%02x", int(rand(15)) + 1) . $sub_tlv_value; $packet_length = $packet_length + 3 + $sub_tlv_length; } elsif ($choosen_tlv eq "6") { $i = int(rand(63)) + 1; $packet_value = $packet_value . "06" . sprintf("%02x", $i); for (my $j = 0; $j < $i; $j++) { $packet_value = $packet_value . sprintf("%02x", rand(0xFF)); } $packet_length = $packet_length + $i + 2; } elsif ($choosen_tlv eq "7") { $packet_value = $packet_value . "07" . "01" . sprintf("%02x", int(rand(2)) + 1); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "8") { $packet_value = $packet_value . "08" . "01" . sprintf("%02x", int(rand(32)) + 1); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "9") { $packet_value = $packet_value . "09" . "01" . sprintf("%02x", int(rand(31)) + 2); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "10") { $packet_value = $packet_value . "0A" . "01" . sprintf("%02x", int(rand(65)) + 64); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "11") { $packet_value = $packet_value . "0B" . "02" . random_bits(16, 0xFFFE); $packet_length = $packet_length + 4; } elsif ($choosen_tlv eq "12") { $packet_value = $packet_value . "0C" . "02" . random_bits(16, 0xFFFF); $packet_length = $packet_length + 4; } elsif ($choosen_tlv eq "13") { $packet_value = $packet_value . "0D" . "02" . random_bits(16, 0xFFFF); $packet_length = $packet_length + 4; } elsif ($choosen_tlv eq "14") { $packet_value = $packet_value . "0E" . "09" . random_bits(32, 0xFFFFFFFF) . random_bits(24, 0xFFFFFF) . random_bits(16, 0xFFFF); $packet_length = $packet_length + 11; } elsif ($choosen_tlv eq "15") { $packet_value = $packet_value . "0F" . "01" . sprintf("%02x", int(rand(2)) + 1); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "16") { $packet_value = $packet_value . "10" . "01" . sprintf("%02x", int(rand(3))); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "17") { $packet_value = $packet_value . "11" . "01" . sprintf("%02x", int(rand(2)) + 1); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "18") { $packet_value = $packet_value . "12" . "04" . random_bits(32, 0xFFFF000F); $packet_length = $packet_length + 6; } elsif ($choosen_tlv eq "19") { $packet_value = $packet_value . "13" . "04" . random_bits(32, 0xFFFF000F); $packet_length = $packet_length + 6; } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } $tlv_number++; } # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "03", "1D", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub INIT_RNG_REQ() { our $packet_value; our $packet_length = 0; # Add SID $packet_value = random_bits(16, 0x3FFF); $packet_length = $packet_length + 2; # Add Downstream Channel ID $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Upstream Channel ID $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "1E", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub MDD_GUI() { our @command_tlvs = (); our @command_subtlvs; our $last_tlv = 0; our $last_sub_tlv = 0; our $choosen_tlv; our $choosen_sub_tlv; our $tlv_number = 1; our $sub_tlv_number = 1; # Add TLV data while ($last_tlv != 1) { @command_subtlvs = (); $sub_tlv_number = 1; if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following TLVs can be added:\n\n"; print " 1) Downstream Channel Active List\n"; print " ...\n"; print " 2) MAC Domain Downstream Service Group\n"; print " ...\n"; print " 3) Downstream Ambiguity Resolution Frequency List TLV\n"; print " 4) Receive Channel Profile Reporting Control\n"; print " ...\n"; print " 5) IP Initialization Parameters\n"; print " ...\n"; print " 6) Early Authentication and Encryption\n"; print " 7) Upstream Active Channel List\n"; print " ...\n"; print " 8) Upstream Ambiguity Resolution Channel List\n"; print "\n TLV " . $tlv_number . " - Choose TLV which should be added: "; $choosen_tlv = <>; chomp $choosen_tlv; if ($choosen_tlv eq "1") { $last_sub_tlv = 0; while ($last_sub_tlv != 1) { if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following sub-TLVs can be added:\n\n"; print " 1) Channel ID\n"; print " 2) Frequency\n"; print " 3) Modulation Order/Annex\n"; print " 4) Primary Capable\n"; print " 5) CM-STATUS Event Enable Bitmask\n"; print " 6) MAP and UCD Transport Indicator\n"; print " 7) OFDM PLC Parameters\n"; print "\n sub-TLV " . $sub_tlv_number++ . " - Choose sub-TLV which should be added: "; $choosen_sub_tlv = <>; chomp $choosen_sub_tlv; if ($choosen_sub_tlv eq "1") { } elsif ($choosen_sub_tlv eq "2") { } elsif ($choosen_sub_tlv eq "3") { } elsif ($choosen_sub_tlv eq "4") { } elsif ($choosen_sub_tlv eq "5") { } elsif ($choosen_sub_tlv eq "6") { } elsif ($choosen_sub_tlv eq "7") { } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } push @command_subtlvs, [$choosen_sub_tlv]; printf "\n Is this last sub-TLV to be added? (Choose: 1 for YES / 0 for NO) "; $last_sub_tlv = <>; } } elsif ( $choosen_tlv eq "2" ) { $last_sub_tlv = 0; while ($last_sub_tlv != 1) { if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following sub-TLVs can be added:\n\n"; print " 1) MD-DS-SG Identifier\n"; print " 2) Downstream Channel ID list\n"; print "\n sub-TLV " . $sub_tlv_number++ . " - Choose sub-TLV which should be added: "; $choosen_sub_tlv = <>; chomp $choosen_sub_tlv; if ($choosen_sub_tlv eq "1") { } elsif ($choosen_sub_tlv eq "2") { } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } push @command_subtlvs, [$choosen_sub_tlv]; printf "\n Is this last sub-TLV to be added? (Choose: 1 for YES / 0 for NO) "; $last_sub_tlv = <>; } } elsif ( $choosen_tlv eq "3" ) { } elsif ( $choosen_tlv eq "4" ) { $last_sub_tlv = 0; while ($last_sub_tlv != 1) { if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following sub-TLVs can be added:\n\n"; print " 1) RCP SC-QAM Center Frequency Spacing\n"; print " 2) Verbose RCP reporting\n"; print " 3) Fragmented RCP transmission\n"; print "\n sub-TLV " . $sub_tlv_number++ . " - Choose sub-TLV which should be added: "; $choosen_sub_tlv = <>; chomp $choosen_sub_tlv; if ($choosen_sub_tlv eq "1") { } elsif ($choosen_sub_tlv eq "2") { } elsif ($choosen_sub_tlv eq "3") { } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } push @command_subtlvs, [$choosen_sub_tlv]; printf "\n Is this last sub-TLV to be added? (Choose: 1 for YES / 0 for NO) "; $last_sub_tlv = <>; } } elsif ( $choosen_tlv eq "5" ) { $last_sub_tlv = 0; while ($last_sub_tlv != 1) { if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following sub-TLVs can be added:\n\n"; print " 1) IP Provisioning Mode\n"; print " 2) Pre-Registration DSID\n"; print "\n sub-TLV " . $sub_tlv_number++ . " - Choose sub-TLV which should be added: "; $choosen_sub_tlv = <>; chomp $choosen_sub_tlv; if ($choosen_sub_tlv eq "1") { } elsif ($choosen_sub_tlv eq "2") { } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } push @command_subtlvs, [$choosen_sub_tlv]; printf "\n Is this last sub-TLV to be added? (Choose: 1 for YES / 0 for NO) "; $last_sub_tlv = <>; } } elsif ( $choosen_tlv eq "6" ) { } elsif ( $choosen_tlv eq "7" ) { $last_sub_tlv = 0; while ($last_sub_tlv != 1) { if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following sub-TLVs can be added:\n\n"; print " 1) Upstream Channel ID for a channel being listed\n"; print " 2) CM-STATUS Event Enable Bitmask\n"; print " 3) Upstream Channel Priority\n"; print " 4) Downstream Channel(s) on which MAPs and UCDs for this Upstream Channel are sent\n"; print "\n sub-TLV " . $sub_tlv_number++ . " - Choose sub-TLV which should be added: "; $choosen_sub_tlv = <>; chomp $choosen_sub_tlv; if ($choosen_sub_tlv eq "1") { } elsif ($choosen_sub_tlv eq "2") { } elsif ($choosen_sub_tlv eq "3") { } elsif ($choosen_sub_tlv eq "4") { } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } push @command_subtlvs, [$choosen_sub_tlv]; printf "\n Is this last sub-TLV to be added? (Choose: 1 for YES / 0 for NO) "; $last_sub_tlv = <>; } } elsif ( $choosen_tlv eq "8" ) { } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } #Save the TLV push @command_tlvs, [$choosen_tlv]; #Save the Sub TLVs (if any) foreach my $subtlv (@command_subtlvs) { push @{$command_tlvs[$tlv_number-1]}, $subtlv; } printf "\n Is this last TLV to be added? (Choose: 1 for YES / 0 for NO) "; $last_tlv = <>; $tlv_number++; } return @command_tlvs; } sub MDD() { my ($frame_index) = @_; our $packet_value = ""; our $packet_length = 0; our $choosen_tlv; our $choosen_sub_tlv; our $tlv_number = 1; our $sub_tlv_number = 1; our $sub_tlv_value; our $sub_tlv_length = 0; our $i = 0; our $j = 0; # Add Configuration Change Count $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Number of Fragments $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Fragment Sequence Number $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Current Channel ID $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add TLV data while (exists($all_frame_data[$frame_index][$tlv_number][0])) { $choosen_tlv = $all_frame_data[$frame_index][$tlv_number][0]; if ($choosen_tlv eq "1") { $sub_tlv_value = ""; $sub_tlv_length = 0; $sub_tlv_number = 1; while (exists($all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0])) { $choosen_sub_tlv = $all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0]; if ($choosen_sub_tlv eq "1") { $sub_tlv_value = $sub_tlv_value . "01" . "01" . random_bits(8, 0xFF); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "2") { $sub_tlv_value = $sub_tlv_value . "02" . "04" . sprintf("%08x", (int(rand(1686)) + 108) * 1000000); $sub_tlv_length = $sub_tlv_length + 6; } elsif ($choosen_sub_tlv eq "3") { my @array = (0, 1, 2, 16, 17, 18, 32, 33, 34); $sub_tlv_value = $sub_tlv_value . "03" . "01" . sprintf("%02x", $array[rand @array]); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "4") { $sub_tlv_value = $sub_tlv_value . "04" . "01" . random_bits(8, 0x01); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "5") { $sub_tlv_value = $sub_tlv_value . "05" . "02" . random_bits(16, 0x0036); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "6") { $sub_tlv_value = $sub_tlv_value . "06" . "01" . random_bits(8, 0x01); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "7") { $sub_tlv_value = $sub_tlv_value . "07" . "01" . random_bits(8, 0x7F); $sub_tlv_length = $sub_tlv_length + 3; } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } $sub_tlv_number++; } $packet_value = $packet_value . "01" . sprintf("%02x", $sub_tlv_length) . $sub_tlv_value; $packet_length = $packet_length + $sub_tlv_length + 2; } elsif ( $choosen_tlv eq "2" ) { $sub_tlv_value = ""; $sub_tlv_length = 0; $sub_tlv_number = 1; while (exists($all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0])) { $choosen_sub_tlv = $all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0]; if ($choosen_sub_tlv eq "1") { $sub_tlv_value = $sub_tlv_value . "01" . "01" . random_bits(8, 0xFF); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "2") { $i = rand(0x1F); $sub_tlv_value = $sub_tlv_value . "02" . sprintf("%02x", $i); for ($j=1; $j <= $i; $j++) { $sub_tlv_value = $sub_tlv_value . random_bits(8, 0xFF); } $sub_tlv_length = $sub_tlv_length + 2 + $i; } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } $sub_tlv_number++; } $packet_value = $packet_value . "02" . sprintf("%02x", $sub_tlv_length) . $sub_tlv_value; $packet_length = $packet_length + $sub_tlv_length + 2; } elsif ( $choosen_tlv eq "3" ) { $i = int(rand(8)) + 1; $packet_value = $packet_value . "03" . sprintf("%02x", $i * 4); for ($j=1; $j <= $i; $j++) { $packet_value = $packet_value . sprintf("%08x", (int(rand(1686)) + 108) * 1000000); } $packet_length = $packet_length + 2 + $i * 4; } elsif ( $choosen_tlv eq "4" ) { $sub_tlv_value = ""; $sub_tlv_length = 0; $sub_tlv_number = 1; while (exists($all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0])) { $choosen_sub_tlv = $all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0]; if ($choosen_sub_tlv eq "1") { $sub_tlv_value = $sub_tlv_value . "01" . "01" . sprintf("%02x", int(rand(2))); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "2") { $sub_tlv_value = $sub_tlv_value . "02" . "01" . sprintf("%02x", int(rand(2))); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "3") { $sub_tlv_value = $sub_tlv_value . "03" . "01" . "01"; $sub_tlv_length = $sub_tlv_length + 3; } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } $sub_tlv_number++; } $packet_value = $packet_value . "04" . sprintf("%02x", $sub_tlv_length) . $sub_tlv_value; $packet_length = $packet_length + $sub_tlv_length + 2; } elsif ( $choosen_tlv eq "5" ) { $sub_tlv_value = ""; $sub_tlv_length = 0; $sub_tlv_number = 1; while (exists($all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0])) { $choosen_sub_tlv = $all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0]; if ($choosen_sub_tlv eq "1") { $sub_tlv_value = $sub_tlv_value . "01" . "01" . sprintf("%02x", int(rand(4))); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "2") { $sub_tlv_value = $sub_tlv_value . "02" . "03" . random_bits(24, 0x0FFFFF); $sub_tlv_length = $sub_tlv_length + 5; } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } $sub_tlv_number++; } $packet_value = $packet_value . "05" . sprintf("%02x", $sub_tlv_length) . $sub_tlv_value; $packet_length = $packet_length + $sub_tlv_length + 2; } elsif ( $choosen_tlv eq "6" ) { $packet_value = $packet_value . "06" . "01" . sprintf("%02x", int(rand(2))); $packet_length = $packet_length + 3; } elsif ( $choosen_tlv eq "7" ) { $sub_tlv_value = ""; $sub_tlv_length = 0; $sub_tlv_number = 1; while (exists($all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0])) { $choosen_sub_tlv = $all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0]; if ($choosen_sub_tlv eq "1") { $sub_tlv_value = $sub_tlv_value . "01" . "01" . random_bits(8, 0xFF); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "2") { $sub_tlv_value = $sub_tlv_value . "02" . "02" . random_bits(16, 0x01C0); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "3") { $sub_tlv_value = $sub_tlv_value . "03" . "01" . sprintf("%02x", int(rand(8))); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "4") { $i = int(rand(16)) + 1; $sub_tlv_value = $sub_tlv_value . "04" . sprintf("%02x", $i); for ($j=1; $j <= $i; $j++) { $sub_tlv_value = $sub_tlv_value . random_bits(8, 0xFF); } $sub_tlv_length = $sub_tlv_length + 2 + $i; } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } $sub_tlv_number++; } $packet_value = $packet_value . "07" . sprintf("%02x", $sub_tlv_length) . $sub_tlv_value; $packet_length = $packet_length + $sub_tlv_length + 2; } elsif ( $choosen_tlv eq "8" ) { $i = int(rand(16)) + 1; $packet_value = $packet_value . "08" . sprintf("%02x", $i); for ($j=1; $j <= $i; $j++) { $packet_value = $packet_value . random_bits(8, 0xFF); } $packet_length = $packet_length + 2 + $i; } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } $tlv_number++; } # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "21", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub B_INIT_RNG_REQ() { our $packet_value; our $packet_length = 0; # Add Capabilities Flag $packet_value = random_bits(8, 0xC0); $packet_length = $packet_length + 1; # Add MAC Domain Downstream Service Group $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Downstream Channel ID $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Upstream Channel ID $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "22", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub type35UCD_GUI() { our @command_tlvs = (); our @command_subtlvs; our $last_tlv = 0; our $last_sub_tlv = 0; our $choosen_tlv; our $choosen_sub_tlv; our $tlv_number = 1; our $sub_tlv_number = 1; # Add TLV data while ($last_tlv != 1) { @command_subtlvs = (); $sub_tlv_number = 1; if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following TLVs can be added:\n\n"; print " 1) Modulation Rate\n"; print " 2) Frequency\n"; print " 3) Preamble Pattern\n"; print " 5) Burst Descriptor (DOCSIS 2.0/3.0)\n"; print " ...\n"; print " 6) Extended Preamble Pattern\n"; print " 7) S-CDMA Mode Enable\n"; print " 8) S-CDMA Spreading Intervals per frame\n"; print " 9) S-CDMA Codes per Minislot\n"; print " 10) S-CDMA Number of Active Codes\n"; print " 11) S-CDMA Code Hopping Seed\n"; print " 12) S-CDMA US ratio numerator 'M'\n"; print " 13) S-CDMA US ratio denominator 'N'\n"; print " 14) S-CDMA Timestamp Snapshop\n"; print " 15) Maintain Power Spectral Density\n"; print " 16) Ranging Required\n"; print " 17) S-CDMA Maximum Scheduled Codes enabled\n"; print " 18) Ranging Hold-Off Priority Field\n"; print " 19) Channel Class ID\n"; print " 20) S-CDMA Selection Mode for Active Codes and Code Hopping\n"; print " 21) S-CDMA Selection String for Active Codes\n"; print " 22) Higher UCD for the same UCID present bitmap\n"; print "\n TLV " . $tlv_number . " - Choose TLV which should be added: "; $choosen_tlv = <>; chomp $choosen_tlv; if ($choosen_tlv eq "1") { } elsif ($choosen_tlv eq "2") { } elsif ($choosen_tlv eq "3") { } elsif ($choosen_tlv eq "5") { # Create BURST5 sub-TLVs $last_sub_tlv = 0; while ($last_sub_tlv != 1) { if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following sub-TLVs can be added:\n\n"; print " 1) Modulation Type\n"; print " 2) Differential Encoding\n"; print " 3) Preamble Length\n"; print " 4) Preamble Value Offset\n"; print " 5) FEC Error Correction (T)\n"; print " 6) FEC Codeword Information Bytes (k)\n"; print " 7) Scrambler Seed\n"; print " 8) Maximum Burst Size\n"; print " 9) Guard Time Size\n"; print " 10) Last Codeword Length\n"; print " 11) Scrambler on/off\n"; print " 12) R-S Interleaver Depth (Ir)\n"; print " 13) R-S Interleaver Block Size (Br)\n"; print " 14) Preamble Type\n"; print " 15) S-CDMA Spreader on/off\n"; print " 16) S-CDMA Codes per Subframe\n"; print " 17) S-CDMA Framer Interleaving Step Size\n"; print " 18) TCM Encoding\n"; print "\n sub-TLV " . $sub_tlv_number++ . " - Choose sub-TLV which should be added: "; $choosen_sub_tlv = <>; chomp $choosen_sub_tlv; if ($choosen_sub_tlv eq "1") { } elsif ($choosen_sub_tlv eq "2") { } elsif ($choosen_sub_tlv eq "3") { } elsif ($choosen_sub_tlv eq "4") { } elsif ($choosen_sub_tlv eq "5") { } elsif ($choosen_sub_tlv eq "6") { } elsif ($choosen_sub_tlv eq "7") { } elsif ($choosen_sub_tlv eq "8") { } elsif ($choosen_sub_tlv eq "9") { } elsif ($choosen_sub_tlv eq "10") { } elsif ($choosen_sub_tlv eq "11") { } elsif ($choosen_sub_tlv eq "12") { } elsif ($choosen_sub_tlv eq "13") { } elsif ($choosen_sub_tlv eq "14") { } elsif ($choosen_sub_tlv eq "15") { } elsif ($choosen_sub_tlv eq "16") { } elsif ($choosen_sub_tlv eq "17") { } elsif ($choosen_sub_tlv eq "18") { } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } push @command_subtlvs, [$choosen_sub_tlv]; printf "\n Is this last sub-TLV to be added? (Choose: 1 for YES / 0 for NO) "; $last_sub_tlv = <>; } } elsif ($choosen_tlv eq "6") { } elsif ($choosen_tlv eq "7") { } elsif ($choosen_tlv eq "8") { } elsif ($choosen_tlv eq "9") { } elsif ($choosen_tlv eq "10") { } elsif ($choosen_tlv eq "11") { } elsif ($choosen_tlv eq "12") { } elsif ($choosen_tlv eq "13") { } elsif ($choosen_tlv eq "14") { } elsif ($choosen_tlv eq "15") { } elsif ($choosen_tlv eq "16") { } elsif ($choosen_tlv eq "17") { } elsif ($choosen_tlv eq "18") { } elsif ($choosen_tlv eq "19") { } elsif ($choosen_tlv eq "20") { } elsif ($choosen_tlv eq "21") { } elsif ($choosen_tlv eq "22") { } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } #Save the TLV push @command_tlvs, [$choosen_tlv]; #Save the Sub TLVs (if any) foreach my $subtlv (@command_subtlvs) { push @{$command_tlvs[$tlv_number-1]}, $subtlv; } printf "\n Is this last TLV to be added? (Choose: 1 for YES / 0 for NO) "; $last_tlv = <>; $tlv_number++; } return @command_tlvs; } sub type35UCD() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; our $choosen_tlv; our $choosen_sub_tlv; our $tlv_number = 1; our $sub_tlv_number = 1; our $sub_tlv_value; our $sub_tlv_length; our $i; our $j; # Add Upstream Channel ID field $packet_value = sprintf("%02x", rand(0xFF)); $packet_length = 1; # Add Config Change Count field $packet_value = $packet_value . sprintf("%02x", rand(0xFF)); $packet_length = $packet_length + 1; # Add Minislot Size field $packet_value = $packet_value . sprintf("%02x", 2 ** rand(0x8)); $packet_length = $packet_length + 1; # Add Downstream Channel ID field $packet_value = $packet_value . sprintf("%02x", rand(0xFF)); $packet_length = $packet_length + 1; # Add TLV data while (exists($all_frame_data[$frame_index][$tlv_number][0])) { $choosen_tlv = $all_frame_data[$frame_index][$tlv_number][0]; if ($choosen_tlv eq "1") { $packet_value = $packet_value . "01" . "01" . sprintf("%02x", 2 ** rand(0x5)); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "2") { $packet_value = $packet_value . "02" . "04" . sprintf("%08x", (int(rand(80)) + 5) * 1000000); $packet_length = $packet_length + 6; } elsif ($choosen_tlv eq "3") { $i = int(rand(127)) + 1; $packet_value = $packet_value . "03" . sprintf("%02x", $i); for (my $j = 0; $j < $i; $j++) { $packet_value = $packet_value . sprintf("%02x", rand(0xFF)); } $packet_length = $packet_length + $i + 2; } elsif ($choosen_tlv eq "5") { # Create BURST5 sub-TLVs $sub_tlv_value = ""; $sub_tlv_length = 0; $sub_tlv_number = 1; while (exists($all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0])) { $choosen_sub_tlv = $all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0]; if ($choosen_sub_tlv eq "1") { $sub_tlv_value = $sub_tlv_value . "01" . "01" . sprintf("%02x", rand(7) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "2") { $sub_tlv_value = $sub_tlv_value . "02" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "3") { $sub_tlv_value = $sub_tlv_value . "03" . "02" . sprintf("%04x", rand(1536) + 1); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "4") { $sub_tlv_value = $sub_tlv_value . "04" . "02" . sprintf("%04x", rand(0xFFFF)); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "5") { $sub_tlv_value = $sub_tlv_value . "05" . "01" . sprintf("%02x", rand(17)); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "6") { $sub_tlv_value = $sub_tlv_value . "06" . "01" . sprintf("%02x", rand(238) + 16); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "7") { $sub_tlv_value = $sub_tlv_value . "07" . "02" . sprintf("%04x", rand(0xFFFF)); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "8") { $sub_tlv_value = $sub_tlv_value . "08" . "01" . sprintf("%02x", rand(0xFF) + 16); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "9") { $sub_tlv_value = $sub_tlv_value . "09" . "01" . sprintf("%02x", rand(0xFF)); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "10") { $sub_tlv_value = $sub_tlv_value . "0A" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "11") { $sub_tlv_value = $sub_tlv_value . "0B" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "12") { $sub_tlv_value = $sub_tlv_value . "0C" . "01" . sprintf("%02x", rand(0xFF)); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "13") { $sub_tlv_value = $sub_tlv_value . "0D" . "02" . sprintf("%04x", rand(0xFFFF)); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "14") { $sub_tlv_value = $sub_tlv_value . "0E" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "15") { $sub_tlv_value = $sub_tlv_value . "0F" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "16") { $sub_tlv_value = $sub_tlv_value . "10" . "01" . sprintf("%02x", rand(128) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "17") { $sub_tlv_value = $sub_tlv_value . "11" . "01" . sprintf("%02x", rand(31) + 1); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "18") { $sub_tlv_value = $sub_tlv_value . "12" . "01" . sprintf("%02x", rand(2) + 1); $sub_tlv_length = $sub_tlv_length + 3; } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } $sub_tlv_number++; } $packet_value = $packet_value . "05" . sprintf("%02x", $sub_tlv_length + 1) . sprintf("%02x", int(rand(15)) + 1) . $sub_tlv_value; $packet_length = $packet_length + 3 + $sub_tlv_length; } elsif ($choosen_tlv eq "6") { $i = int(rand(63)) + 1; $packet_value = $packet_value . "06" . sprintf("%02x", $i); for (my $j = 0; $j < $i; $j++) { $packet_value = $packet_value . sprintf("%02x", rand(0xFF)); } $packet_length = $packet_length + $i + 2; } elsif ($choosen_tlv eq "7") { $packet_value = $packet_value . "07" . "01" . sprintf("%02x", int(rand(2)) + 1); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "8") { $packet_value = $packet_value . "08" . "01" . sprintf("%02x", int(rand(32)) + 1); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "9") { $packet_value = $packet_value . "09" . "01" . sprintf("%02x", int(rand(31)) + 2); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "10") { $packet_value = $packet_value . "0A" . "01" . sprintf("%02x", int(rand(65)) + 64); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "11") { $packet_value = $packet_value . "0B" . "02" . random_bits(16, 0xFFFE); $packet_length = $packet_length + 4; } elsif ($choosen_tlv eq "12") { $packet_value = $packet_value . "0C" . "02" . random_bits(16, 0xFFFF); $packet_length = $packet_length + 4; } elsif ($choosen_tlv eq "13") { $packet_value = $packet_value . "0D" . "02" . random_bits(16, 0xFFFF); $packet_length = $packet_length + 4; } elsif ($choosen_tlv eq "14") { $packet_value = $packet_value . "0E" . "09" . random_bits(32, 0xFFFFFFFF) . random_bits(24, 0xFFFFFF) . random_bits(16, 0xFFFF); $packet_length = $packet_length + 11; } elsif ($choosen_tlv eq "15") { $packet_value = $packet_value . "0F" . "01" . sprintf("%02x", int(rand(2)) + 1); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "16") { $packet_value = $packet_value . "10" . "01" . sprintf("%02x", int(rand(3))); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "17") { $packet_value = $packet_value . "11" . "01" . sprintf("%02x", int(rand(2)) + 1); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "18") { $packet_value = $packet_value . "12" . "04" . random_bits(32, 0xFFFF000F); $packet_length = $packet_length + 6; } elsif ($choosen_tlv eq "19") { $packet_value = $packet_value . "13" . "04" . random_bits(32, 0xFFFF000F); $packet_length = $packet_length + 6; } elsif ($choosen_tlv eq "20") { $packet_value = $packet_value . "14" . "01" . sprintf("%02x", int(rand(4))); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "21") { $packet_value = $packet_value . "15" . "10" . random_bits(32, 0xFFFFFFFF) . random_bits(32, 0xFFFFFFFF) . random_bits(32, 0xFFFFFFFF) . random_bits(32, 0xFFFFFFFF); $packet_length = $packet_length + 18; } elsif ($choosen_tlv eq "22") { $packet_value = $packet_value . "16" . "01" . random_bits(8, 0x01); $packet_length = $packet_length + 3; } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } $tlv_number++; } # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "04", "23", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub DBC_REQ() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; # Add Transaction ID $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Number of fragments $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Fragment Sequence Number $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Annex C TLVs ($packet_value, $packet_length) = add_annex_c_tlvs($frame_index, $packet_value, $packet_length); # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "24", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub DBC_RSP() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; # Add Transaction ID $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Confirmation Code $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Annex C TLVs ($packet_value, $packet_length) = add_annex_c_tlvs($frame_index, $packet_value, $packet_length); # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "25", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub DBC_ACK() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; # Add Transaction ID $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Annex C TLVs ($packet_value, $packet_length) = add_annex_c_tlvs($frame_index, $packet_value, $packet_length); # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "26", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub REG_REQ_MP() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; # Add Service Identifier $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Number of fragments $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Fragment Sequence Number $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Annex C TLVs ($packet_value, $packet_length) = add_annex_c_tlvs($frame_index, $packet_value, $packet_length); # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "2C", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub REG_RSP_MP() { my ($frame_index) = @_; our $packet_value; our $packet_length = 0; # Add Service Identifier $packet_value = random_bits(16, 0xFFFF); $packet_length = $packet_length + 2; # Add Response Code $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Number of fragments $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Fragment Sequence Number $packet_value = $packet_value . random_bits(8, 0xFF); $packet_length = $packet_length + 1; # Add Annex C TLVs ($packet_value, $packet_length) = add_annex_c_tlvs($frame_index, $packet_value, $packet_length); # Add MAC Management header ($packet_value, $packet_length) = add_mac_management($packet_value, $packet_length, "00", "00", "01", "2D", "00"); # Add DOCSIS header ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, "00", 192, 2, 0); return ($packet_value, $packet_length); } sub request_minislots() { our $packet_value = ""; our $packet_length = 0; ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, sprintf("%02x", rand(0xFF)), 192, 4, 0); return ($packet_value, $packet_length); } sub request_bytes() { our $packet_value = ""; our $packet_length = 0; ($packet_value, $packet_length) = add_docsis($packet_value, $packet_length, "0000", undef, sprintf("%02x", rand(0xFF)), 192, 8, 0); return ($packet_value, $packet_length); } # value, length, dsap, ssap, version, type, reserved/multipart sub add_mac_management () { our @input = @_; our $packet_value; our $packet_length = 0; our $i; # Add Reserved/Multipart field $packet_value = $input[6] . $input[0]; $packet_length = $input[1] + 1; # Add Type field $packet_value = $input[5] . $packet_value; $packet_length = $packet_length + 1; # Add Version field $packet_value = $input[4] . $packet_value; $packet_length = $packet_length + 1; # Add Control field $packet_value = "03" . $packet_value; $packet_length = $packet_length + 1; # Add SSAP field $packet_value = $input[3] . $packet_value; $packet_length = $packet_length + 1; # Add DSAP field $packet_value = $input[2] . $packet_value; $packet_length = $packet_length + 1; # Add Length field $packet_value = sprintf("%04x", $packet_length) . $packet_value; $packet_length = $packet_length + 2; # Add Source MAC Address for ($i = 0; $i < 3; $i++) { $packet_value = sprintf("%02x", rand(0xFF)) . $packet_value; $packet_length = $packet_length + 1; } $packet_value = "00015C" . $packet_value; $packet_length = $packet_length + 3; # Add Destination MAC Address for ($i = 0; $i < 3; $i++) { $packet_value = sprintf("%02x", rand(0xFF)) . $packet_value; $packet_length = $packet_length + 1; } $packet_value = "00015C" . $packet_value; $packet_length = $packet_length + 3; return ($packet_value, $packet_length); } # value, length, hcs, ehdr, macparm, fc_type (64/128/192), fc_parm (2..62), ehdr_on (0/1) sub add_docsis () { our @input = @_; our $packet_value; our $packet_length; our @v; my $ctx = Digest::CRC->new(width => 16, poly => 0x1021, init => 0xFFFF, xorout => 0xFFFF, refin => 1, refout => 1); if ($input[6] eq "0" || $input[6] eq "2") { # Add HCS field $ctx->reset; $ctx->add(chr($input[5] + $input[6] + $input[7])); $ctx->add(chr(0x00)); $ctx->add(chr(0x00)); $ctx->add(chr($packet_length)); @v = split //, sprintf("%04x", hex($ctx->hexdigest)); $packet_value = $v[2] . $v[3] . $v[0] . $v[1] . $input[0]; $packet_length = $input[1] + 2; # TODO Add ehdr field # Add Length field $packet_value = sprintf("%04x", $packet_length - 2) . $packet_value; $packet_length = $packet_length + 2; # Add MAC_PARM field $packet_value = $input[4] . $packet_value; use bytes; $packet_length = $packet_length + (length (pack "H*", $input[4])); no bytes; # Add Frame Control (FC) field $packet_value = sprintf("%02x", $input[5] + $input[6] + $input[7]) . $packet_value; $packet_length = $packet_length + 1; } elsif ($input[6] eq "4") { # Add HCS field $packet_value = $input[2] . $input[0]; $packet_length = $input[1] + 2; # Add SID $packet_value = sprintf("%04x", rand(0x3FFF)) . $packet_value; $packet_length = $packet_length + 2; # Add Minislots field $packet_value = sprintf("%02x", rand(0xFF)) . $packet_value; $packet_length = $packet_length + 1; # Add Frame Control (FC) field $packet_value = sprintf("%02x", $input[5] + $input[6] + $input[7]) . $packet_value; $packet_length = $packet_length + 1; } elsif ($input[6] eq "8") { # Add HCS field $packet_value = $input[2] . $input[0]; $packet_length = $input[1] + 2; # Add SID $packet_value = sprintf("%04x", rand(0x3FFF)) . $packet_value; $packet_length = $packet_length + 2; # Add Bytes field $packet_value = sprintf("%04x", rand(0xFF)) . $packet_value; $packet_length = $packet_length + 2; # Add Frame Control (FC) field $packet_value = sprintf("%02x", $input[5] + $input[6] + $input[7]) . $packet_value; $packet_length = $packet_length + 1; } return ($packet_value, $packet_length); } sub random_bits { my $i = 0; our $value = ""; our $binary = ""; our @input = @_; our @bits = split //, sprintf ("%0" . $input[0] . "b", $input[1]); foreach (@bits) { if ($_ == 1) { $bits[$i] = int(rand(2)); } $binary = join("", $binary, $bits[$i]); $value = sprintf("%0" . $input[0] / 4 . "x", oct("0b" . $binary)); $i++; } return $value; } sub add_annex_c_tlvs_GUI { our @command_tlvs = (); our @command_subtlvs; our $last_tlv = 0; our $last_sub_tlv = 0; our $choosen_tlv; our $choosen_sub_tlv; our $tlv_number = 1; our $sub_tlv_number = 1; our $i; while ($last_tlv != 1) { @command_subtlvs = (); $sub_tlv_number = 1; if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Choose Annex C TLVs to be added:\n\n"; print " 1) Downstream Frequency\n"; print " 2) Upstream Channel ID\n"; print " 3) Network Access\n"; print " 4) DOCSIS 1.0 Class of Service\n"; print " ...\n"; print " 5) Modem Capabilities\n"; print " ...\n"; print " 45) Downstream Unencrypted Traffic (DUT) Filtering Encoding\n"; print " ...\n"; print "\n TLV " . $tlv_number . " - Choose which TLV will be generated: "; $choosen_tlv = <>; chomp $choosen_tlv; if ($choosen_tlv eq "1") { } elsif ($choosen_tlv eq "2") { } elsif ($choosen_tlv eq "3") { } elsif ($choosen_tlv eq "4") { $last_sub_tlv = 0; while ($last_sub_tlv != 1) { if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Class of Service sub-TLVs which can be added:\n\n"; print " 1) Class ID\n"; print " 2) Maximum Downstream Rate\n"; print " 3) Maximum Upstream Rate\n"; print " 4) Upstream Channel Priority\n"; print " 5) Guaranteed Minimum Upstream Chanel Data Rate\n"; print " 6) Maximum Upstream Channel Transmit Burst\n"; print " 7) Class-of-Service Privacy Enable\n"; print "\n sub-TLV " . $sub_tlv_number . " - Choose which TLV will be generated: "; $choosen_sub_tlv = <>; chomp $choosen_sub_tlv; if ($choosen_sub_tlv eq "1") { } elsif ($choosen_sub_tlv eq "2") { } elsif ($choosen_sub_tlv eq "3") { } elsif ($choosen_sub_tlv eq "4") { } elsif ($choosen_sub_tlv eq "5") { } elsif ($choosen_sub_tlv eq "6") { } elsif ($choosen_sub_tlv eq "7") { } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } push @command_subtlvs, [$choosen_sub_tlv]; print "\n Is this last sub-TLV for this packet? (Choose: 1 for YES / 0 for NO) "; $last_sub_tlv = <>; } } elsif ($choosen_tlv eq "5") { $last_sub_tlv = 0; while ($last_sub_tlv != 1) { if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Modem Capabilities sub-TLVs which can be added:\n\n"; print " 40) Extended Upstream Transmit Power Capability\n"; print " 48) Extended Packet Length Support Capability\n"; print "\n sub-TLV " . $sub_tlv_number . " - Choose which TLV will be generated: "; $choosen_sub_tlv = <>; chomp $choosen_sub_tlv; if ($choosen_sub_tlv eq "40") { } elsif ($choosen_sub_tlv eq "48") { } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } push @command_subtlvs, [$choosen_sub_tlv]; print "\n Is this last sub-TLV for this packet? (Choose: 1 for YES / 0 for NO) "; $last_sub_tlv = <>; } } elsif ($choosen_tlv eq "45") { $last_sub_tlv = 0; while ($last_sub_tlv != 1) { if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Downstream Unencrypted Traffic sub-TLVs which can be added:\n\n"; print " 1) Downstream Unencrypted Traffic (DUT) Control\n"; print " 2) Extended Packet Length Support Capability\n"; print "\n sub-TLV " . $sub_tlv_number . " - Choose which TLV will be generated: "; $choosen_sub_tlv = <>; chomp $choosen_sub_tlv; if ($choosen_sub_tlv eq "1") { } elsif ($choosen_sub_tlv eq "2") { } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } push @command_subtlvs, [$choosen_sub_tlv]; print "\n Is this last sub-TLV for this packet? (Choose: 1 for YES / 0 for NO) "; $last_sub_tlv = <>; } } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } #Save the TLV push @command_tlvs, [$choosen_tlv]; #Save the Sub TLVs (if any) foreach my $subtlv (@command_subtlvs) { push @{$command_tlvs[$tlv_number-1]}, $subtlv; } print "\n Is this last TLV for this packet? (Choose: 1 for YES / 0 for NO) "; $last_tlv = <>; } return @command_tlvs; } sub add_annex_c_tlvs { my $frame_index; our $packet_value; our $packet_length; our $tlv_number = 1; our $choosen_tlv; our $sub_tlv_number = 1; our $choosen_sub_tlv; our $sub_tlv_length = 0; our $sub_tlv_value = ""; our $this_tlv_length = 0; our $i; $frame_index = $_[0]; $packet_value = $_[1]; $packet_length = $_[2]; # Add TLV data while (exists($all_frame_data[$frame_index][$tlv_number][0])) { $choosen_tlv = $all_frame_data[$frame_index][$tlv_number][0]; if ($choosen_tlv eq "1") { $packet_value = $packet_value . "01" . "04" . sprintf("%08x", (int(rand(1686)) + 108) * 1000000); $packet_length = $packet_length + 6; } elsif ($choosen_tlv eq "2") { $packet_value = $packet_value . "02" . "01" . random_bits(8, 0xFF); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "3") { $packet_value = $packet_value . "03" . "01" . random_bits(8, 0x01); $packet_length = $packet_length + 3; } elsif ($choosen_tlv eq "4") { $sub_tlv_value = ""; $sub_tlv_length = 0; $sub_tlv_number = 1; while (exists($all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0])) { $choosen_sub_tlv = $all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0]; if ($choosen_sub_tlv eq "1") { $sub_tlv_value = $sub_tlv_value . "01" . "01" . sprintf("%02x", (int(rand(16)) + 1)); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "2") { $sub_tlv_value = $sub_tlv_value . "02" . "04" . random_bits(32, 0x00FF0000); $sub_tlv_length = $sub_tlv_length + 6; } elsif ($choosen_sub_tlv eq "3") { $sub_tlv_value = $sub_tlv_value . "03" . "04" . random_bits(32, 0x00FF0000); $sub_tlv_length = $sub_tlv_length + 6; } elsif ($choosen_sub_tlv eq "4") { $sub_tlv_value = $sub_tlv_value . "04" . "01" . sprintf("%02x", (int(rand(8)))); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "5") { $sub_tlv_value = $sub_tlv_value . "05" . "04" . random_bits(32, 0x00FF0000); $sub_tlv_length = $sub_tlv_length + 6; } elsif ($choosen_sub_tlv eq "6") { $sub_tlv_value = $sub_tlv_value . "06" . "02" . random_bits(16, 0xFF00); $sub_tlv_length = $sub_tlv_length + 4; } elsif ($choosen_sub_tlv eq "7") { $sub_tlv_value = $sub_tlv_value . "07" . "01" . sprintf("%02x", (int(rand(2)))); $sub_tlv_length = $sub_tlv_length + 3; } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } $sub_tlv_number++; } $packet_value = $packet_value . "04" . sprintf("%02x", $sub_tlv_length) . $sub_tlv_value; $packet_length = $packet_length + $sub_tlv_length + 2; } elsif ($choosen_tlv eq "5") { $sub_tlv_value = ""; $sub_tlv_length = 0; $sub_tlv_number = 1; while (exists($all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0])) { $choosen_sub_tlv = $all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0]; if ($choosen_sub_tlv eq "40") { $sub_tlv_value = $sub_tlv_value . "28" . "01" . sprintf("%02x", int(rand(39)) + 205); $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "48") { $sub_tlv_value = $sub_tlv_value . "30" . "02" . "07D0"; $sub_tlv_length = $sub_tlv_length + 4; } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } $sub_tlv_number++; } $packet_value = $packet_value . "05" . sprintf("%02x", $sub_tlv_length) . $sub_tlv_value; $packet_length = $packet_length + $sub_tlv_length + 2; } elsif ($choosen_tlv eq "45") { $sub_tlv_value = ""; $sub_tlv_length = 0; $sub_tlv_number = 1; while (exists($all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0])) { $choosen_sub_tlv = $all_frame_data[$frame_index][$tlv_number][$sub_tlv_number][0]; if ($choosen_sub_tlv eq "1") { $sub_tlv_value = $sub_tlv_value . "01" . "01" . "01"; $sub_tlv_length = $sub_tlv_length + 3; } elsif ($choosen_sub_tlv eq "2") { $this_tlv_length = int(rand(10) + 10); $sub_tlv_value = $sub_tlv_value . "02" . sprintf("%02x", $this_tlv_length); for ($i = 0; $i < $this_tlv_length; $i++) { $sub_tlv_value = $sub_tlv_value . random_bits(8, 0xFF); } $sub_tlv_length = $sub_tlv_length + 2 + $this_tlv_length; } else { print "\n This is not a valid option ($choosen_sub_tlv). Calling EXIT... \n\n"; exit; } $sub_tlv_number++; } $packet_value = $packet_value . "2D" . sprintf("%02x", $sub_tlv_length) . $sub_tlv_value; $packet_length = $packet_length + $sub_tlv_length + 2; } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } $tlv_number++; } return ($packet_value, $packet_length); } sub add_bpkm_attributes_GUI() { our @command_tlvs = (); our $tlv_number = 1; our $choosen_tlv; our $last_tlv = 0; while ($last_tlv != 1) { if ($clear_screen) { system $^O eq 'MSWin32' ? 'cls' : 'clear'; } print "\n Following Attributes can be added:\n\n"; print " 1) Serial Number\n"; print " 2) Manufacturer ID\n"; print " 3) MAC Address\n"; print " 4) RSA Public Key\n"; print " 5) CM Identification\n"; print " 6) Display String\n"; print " 7) Authorization Key\n"; print " 8) Encrypted Traffic Encryption Key (TEK)\n"; print " 9) Key Lifetime\n"; print " 10) Key Sequence Number\n"; print " 11) HMAC Digesh\n"; print " 12) SAID\n"; print " 13) TEK-Parameters\n"; print " 15) Cipher Block Chaining (CBC) Initialization Vector\n"; print " 16) Error Code\n"; print " 17) CA Certificate\n"; print " 18) CM Certificate\n"; print " 19) Security Capabilities\n"; print " 20) Cryptographic Suite\n"; print " 21) Cryptographic Suite List\n"; print " 22) BPI Version\n"; print " 23) SA Descriptor\n"; print " 24) SA Type\n"; print " 25) SA Query\n"; print " 26) SA Query Type\n"; print " 27) IPv4 Address\n"; print " 127) Vendor Defined\n"; print "\n Attribute " . $tlv_number . " - Choose which Attribute will be generated: "; $choosen_tlv = <>; chomp $choosen_tlv; if ($choosen_tlv eq "1") { } elsif ($choosen_tlv eq "2") { } elsif ($choosen_tlv eq "3") { } elsif ($choosen_tlv eq "4") { } elsif ($choosen_tlv eq "5") { } elsif ($choosen_tlv eq "6") { } elsif ($choosen_tlv eq "7") { } elsif ($choosen_tlv eq "8") { } elsif ($choosen_tlv eq "9") { } elsif ($choosen_tlv eq "10") { } elsif ($choosen_tlv eq "11") { } elsif ($choosen_tlv eq "12") { } elsif ($choosen_tlv eq "13") { } elsif ($choosen_tlv eq "15") { } elsif ($choosen_tlv eq "16") { } elsif ($choosen_tlv eq "127") { } elsif ($choosen_tlv eq "17") { } elsif ($choosen_tlv eq "18") { } elsif ($choosen_tlv eq "19") { } elsif ($choosen_tlv eq "20") { } elsif ($choosen_tlv eq "21") { } elsif ($choosen_tlv eq "22") { } elsif ($choosen_tlv eq "23") { } elsif ($choosen_tlv eq "24") { } elsif ($choosen_tlv eq "25") { } elsif ($choosen_tlv eq "26") { } elsif ($choosen_tlv eq "27") { } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } #Save the TLV push @command_tlvs, [$choosen_tlv]; print "\n Is this last Attribute for this packet? (Choose: 1 for YES / 0 for NO) "; $last_tlv = <>; $tlv_number++; } return @command_tlvs; } sub add_bpkm_attributes() { our @input = @_; my $frame_index; our $packet_value; our $packet_length; our $tlv_number = 1; our $choosen_tlv; our $last_tlv = 0; our @ISO8859_1; our $i; our $j; our $this_attribute_length; our $attributes_length = 0; our $attributes_value = ""; our $compound_attributes_length = 0; our $compound_attributes_value = ""; our @DES_length; our @AuthKey; our @TEK; our $compound_length = 0; our $compound_value = ""; our $vendor_defined_length; our @CryptoSuite; $frame_index = $input[0]; $packet_value = $input[1]; $packet_length = $input[2]; # Add TLV data while (exists($all_frame_data[$frame_index][$tlv_number][0])) { $choosen_tlv = $all_frame_data[$frame_index][$tlv_number][0]; if ($choosen_tlv eq "1") { $this_attribute_length = int(rand(10)) + 10; $attributes_value = $attributes_value . "01" . sprintf("%04x", $this_attribute_length); $attributes_length = $attributes_length + 3; @ISO8859_1 = ("41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "2D"); for ($i = 1; $i <= $this_attribute_length; $i++) { $attributes_value = $attributes_value . $ISO8859_1[rand(@ISO8859_1)]; } $attributes_length = $attributes_length + $this_attribute_length; } elsif ($choosen_tlv eq "2") { $attributes_value = $attributes_value . "02" . "0003"; $attributes_length = $attributes_length + 3; $attributes_value = $attributes_value . random_bits(8, 0xFF) . random_bits(8, 0xFF) . random_bits(8, 0xFF); $attributes_length = $attributes_length + 3; } elsif ($choosen_tlv eq "3") { $attributes_value = $attributes_value . "03" . "0006"; $attributes_length = $attributes_length + 3; $attributes_value = $attributes_value . random_bits(24, 0xFFFFFF) . random_bits(24, 0xFFFFFF); $attributes_length = $attributes_length + 6; } elsif ($choosen_tlv eq "4") { @DES_length = (106, 140, 270); $this_attribute_length = $DES_length[rand(@DES_length)]; $attributes_value = $attributes_value . "04" . sprintf("%04x", $this_attribute_length); $attributes_length = $attributes_length + 3; for ($i = 0; $i < $this_attribute_length; $i++) { $attributes_value = $attributes_value . random_bits(8, 0xFF); } $attributes_length = $attributes_length + $this_attribute_length; } elsif ($choosen_tlv eq "5") { $compound_attributes_value = ""; $compound_attributes_length = 0; $compound_value = ""; $compound_length = 0; $this_attribute_length = int(rand(10)) + 10; $compound_attributes_value = $compound_attributes_value . "01" . sprintf("%04x", $this_attribute_length); $compound_attributes_length = $compound_attributes_length + 3; @ISO8859_1 = ("41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "2D"); for ($i = 1; $i <= $this_attribute_length; $i++) { $compound_attributes_value = $compound_attributes_value . $ISO8859_1[rand(@ISO8859_1)]; } $compound_attributes_length = $compound_attributes_length + $this_attribute_length; $compound_attributes_value = $compound_attributes_value . "02" . "0003"; $compound_attributes_length = $compound_attributes_length + 3; $compound_attributes_value = $compound_attributes_value . random_bits(8, 0xFF) . random_bits(8, 0xFF) . random_bits(8, 0xFF); $compound_attributes_length = $compound_attributes_length + 3; $compound_attributes_value = $compound_attributes_value . "03" . "0006"; $compound_attributes_length = $compound_attributes_length + 3; $compound_attributes_value = $compound_attributes_value . random_bits(24, 0xFFFFFF) . random_bits(24, 0xFFFFFF); $compound_attributes_length = $compound_attributes_length + 6; @DES_length = (106, 140, 270); $this_attribute_length = $DES_length[rand(@DES_length)]; $compound_attributes_value = $compound_attributes_value . "04" . sprintf("%04x", $this_attribute_length); $compound_attributes_length = $compound_attributes_length + 3; for ($i = 0; $i < $this_attribute_length; $i++) { $compound_attributes_value = $compound_attributes_value . random_bits(8, 0xFF); } $compound_attributes_length = $compound_attributes_length + $this_attribute_length; $compound_value = $compound_value . "02" . "0003"; $compound_length = $compound_length +3; $compound_value = $compound_value . random_bits(8, 0xFF) . random_bits(8, 0xFF) . random_bits(8, 0xFF); $compound_length = $compound_length +3; for ($i = 0; $i < rand(10); $i++) { $vendor_defined_length = int(rand(12)) + 1; $compound_value = $compound_value . random_bits(8, 0xFE) . sprintf("%04x", $vendor_defined_length); for ($j = 0; $j < $vendor_defined_length; $j++) { $compound_value = $compound_value . random_bits(8, 0xFF); } $compound_length = $compound_length + 1 + 2 + $vendor_defined_length; } $compound_attributes_value = $compound_attributes_value . "7F" . sprintf("%04x", $compound_length) . $compound_value; $compound_attributes_length = $compound_attributes_length + 1 + 2 + $compound_length; $attributes_value = $attributes_value . "05" . sprintf("%04x", $compound_attributes_length) . $compound_attributes_value; $attributes_length = $attributes_length + 1 + 2 + $compound_attributes_length; } elsif ($choosen_tlv eq "6") { $this_attribute_length = int(rand(118)) + 10; $attributes_value = $attributes_value . "06" . sprintf("%04x", $this_attribute_length); $attributes_length = $attributes_length + 3; @ISO8859_1 = ("41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "2D"); for ($i = 1; $i <= $this_attribute_length; $i++) { $attributes_value = $attributes_value . $ISO8859_1[rand(@ISO8859_1)]; } $attributes_length = $attributes_length + $this_attribute_length; } elsif ($choosen_tlv eq "7") { @AuthKey = (96, 128, 256); $this_attribute_length = $AuthKey[rand(@AuthKey)]; $attributes_value = $attributes_value . "07" . sprintf("%04x", $this_attribute_length); $attributes_length = $attributes_length + 3; for ($i = 0; $i < $this_attribute_length; $i++) { $attributes_value = $attributes_value . random_bits(8, 0xFF); } $attributes_length = $attributes_length + $this_attribute_length; } elsif ($choosen_tlv eq "8") { @TEK = (8, 16); $this_attribute_length = $TEK[rand(@TEK)]; $attributes_value = $attributes_value . "08" . sprintf("%04x", $this_attribute_length); $attributes_length = $attributes_length + 3; for ($i = 0; $i < $this_attribute_length; $i++) { $attributes_value = $attributes_value . random_bits(8, 0xFF); } $attributes_length = $attributes_length + $this_attribute_length; } elsif ($choosen_tlv eq "9") { $attributes_value = $attributes_value . "09" . "0004"; $attributes_length = $attributes_length + 3; $attributes_value = $attributes_value . random_bits(32, 0xFFFFFFFF); $attributes_length = $attributes_length + 4; } elsif ($choosen_tlv eq "10") { $attributes_value = $attributes_value . "0A" . "0001"; $attributes_length = $attributes_length + 3; $attributes_value = $attributes_value . random_bits(8, 0x0F); $attributes_length = $attributes_length + 1; } elsif ($choosen_tlv eq "11") { $attributes_value = $attributes_value . "0B" . "0014"; $attributes_length = $attributes_length + 3; for ($i = 0; $i < 20; $i++) { $attributes_value = $attributes_value . random_bits(8, 0xFF); } $attributes_length = $attributes_length + 20; } elsif ($choosen_tlv eq "12") { $attributes_value = $attributes_value . "0C" . "0002"; $attributes_length = $attributes_length + 3; $attributes_value = $attributes_value . random_bits(16, 0x3FFF); $attributes_length = $attributes_length + 2; } elsif ($choosen_tlv eq "13") { @TEK = (8, 16); $this_attribute_length = $TEK[rand(@TEK)]; if ($this_attribute_length == 8) { $attributes_value = $attributes_value . "0D" . "0021"; $attributes_length = $attributes_length + 3; } elsif ($this_attribute_length == 16) { $attributes_value = $attributes_value . "0D" . "0031"; $attributes_length = $attributes_length + 3; } $attributes_value = $attributes_value . "08" . sprintf("%04x", $this_attribute_length); $attributes_length = $attributes_length + 3; for ($i = 0; $i < $this_attribute_length; $i++) { $attributes_value = $attributes_value . random_bits(8, 0xFF); } $attributes_length = $attributes_length + $this_attribute_length; $attributes_value = $attributes_value . "09" . "0004"; $attributes_length = $attributes_length + 3; $attributes_value = $attributes_value . random_bits(32, 0xFFFFFFFF); $attributes_length = $attributes_length + 4; $attributes_value = $attributes_value . "0A" . "0001"; $attributes_length = $attributes_length + 3; $attributes_value = $attributes_value . random_bits(8, 0x0F); $attributes_length = $attributes_length + 1; $attributes_value = $attributes_value . "0F" . sprintf("%04x", $this_attribute_length); $attributes_length = $attributes_length + 3; for ($i = 0; $i < $this_attribute_length; $i++) { $attributes_value = $attributes_value . random_bits(8, 0xFF); } $attributes_length = $attributes_length + $this_attribute_length; } elsif ($choosen_tlv eq "15") { @TEK = (8, 16); $this_attribute_length = $TEK[rand(@TEK)]; $attributes_value = $attributes_value . "0F" . sprintf("%04x", $this_attribute_length); $attributes_length = $attributes_length + 3; for ($i = 0; $i < $this_attribute_length; $i++) { $attributes_value = $attributes_value . random_bits(8, 0xFF); } $attributes_length = $attributes_length + $this_attribute_length; } elsif ($choosen_tlv eq "16") { $attributes_value = $attributes_value . "10" . "0001"; $attributes_length = $attributes_length + 3; $attributes_value = $attributes_value . sprintf("%02x", int(rand(11))); $attributes_length = $attributes_length + 1; } elsif ($choosen_tlv eq "127") { $compound_value = ""; $compound_length = 0; $compound_value = $compound_value . "02" . "0003"; $compound_length = $compound_length +3; $compound_value = $compound_value . random_bits(8, 0xFF) . random_bits(8, 0xFF) . random_bits(8, 0xFF); $compound_length = $compound_length +3; for ($i = 0; $i < rand(10); $i++) { $vendor_defined_length = int(rand(12)) + 1; $compound_value = $compound_value . random_bits(8, 0xFE) . sprintf("%04x", $vendor_defined_length); for ($j = 0; $j < $vendor_defined_length; $j++) { $compound_value = $compound_value . random_bits(8, 0xFF); } $compound_length = $compound_length + 1 + 2 + $vendor_defined_length; } $attributes_value = $attributes_value . "7F" . sprintf("%04x", $compound_length) . $compound_value; $attributes_length = $attributes_length + 1 + 2 + $compound_length; } elsif ($choosen_tlv eq "17") { $this_attribute_length = int(rand(128)) + 128; $attributes_value = $attributes_value . "11" . sprintf("%04x", $this_attribute_length); $attributes_length = $attributes_length + 1 + 2 + $this_attribute_length; for ($i = 0; $i < $this_attribute_length; $i++) { $attributes_value = $attributes_value . random_bits(8, 0xFF); } } elsif ($choosen_tlv eq "18") { $this_attribute_length = int(rand(128)) + 128; $attributes_value = $attributes_value . "12" . sprintf("%04x", $this_attribute_length); $attributes_length = $attributes_length + 1 + 2 + $this_attribute_length; for ($i = 0; $i < $this_attribute_length; $i++) { $attributes_value = $attributes_value . random_bits(8, 0xFF); } } elsif ($choosen_tlv eq "19") { $attributes_value = $attributes_value . "13" . "000D"; $attributes_length = $attributes_length + 1 + 2; $attributes_value = $attributes_value . "15" . "0006" . "010002000300"; $attributes_length = $attributes_length + 1 + 2 + 6; $attributes_value = $attributes_value . "16" . "0001" . sprintf("%02x", int(rand(2))); $attributes_length = $attributes_length + 1 + 2 + 1; } elsif ($choosen_tlv eq "20") { @CryptoSuite = ("0100", "0200", "0300"); $attributes_value = $attributes_value . "14" . "0002" . $CryptoSuite[rand(@CryptoSuite)]; $attributes_length = $attributes_length + 1 + 2 + 2; } elsif ($choosen_tlv eq "21") { $attributes_value = $attributes_value . "15" . "0006" . "010002000300"; $attributes_length = $attributes_length + 1 + 2 + 6; } elsif ($choosen_tlv eq "22") { $attributes_value = $attributes_value . "16" . "0001" . sprintf("%02x", int(rand(2))); $attributes_length = $attributes_length + 1 + 2 + 1; } elsif ($choosen_tlv eq "23") { $attributes_value = $attributes_value . "17" . "000E"; $attributes_length = $attributes_length + 3; $attributes_value = $attributes_value . "0C" . "0002"; $attributes_length = $attributes_length + 3; $attributes_value = $attributes_value . random_bits(16, 0x3FFF); $attributes_length = $attributes_length + 2; $attributes_value = $attributes_value . "18" . "0001" . sprintf("%02x", int(rand(3))); $attributes_length = $attributes_length + 1 + 2 + 1; @CryptoSuite = ("0100", "0200", "0300"); $attributes_value = $attributes_value . "14" . "0002" . $CryptoSuite[rand(@CryptoSuite)]; $attributes_length = $attributes_length + 1 + 2 + 2; } elsif ($choosen_tlv eq "24") { $attributes_value = $attributes_value . "18" . "0001" . sprintf("%02x", int(rand(3))); $attributes_length = $attributes_length + 1 + 2 + 1; } elsif ($choosen_tlv eq "25") { $attributes_value = $attributes_value . "19" . "000B"; $attributes_length = $attributes_length + 3; $attributes_value = $attributes_value . "1A" . "0001" . random_bits(8, 0xFF); $attributes_length = $attributes_length + 1 + 2 + 1; $attributes_value = $attributes_value . "1B" . "0004" . random_bits(32, 0xFEFFFFFF); $attributes_length = $attributes_length + 1 + 2 + 4; } elsif ($choosen_tlv eq "26") { $attributes_value = $attributes_value . "1A" . "0001" . random_bits(8, 0xFF); $attributes_length = $attributes_length + 1 + 2 + 1; } elsif ($choosen_tlv eq "27") { $attributes_value = $attributes_value . "1B" . "0004" . random_bits(32, 0xFEFFFFFF); $attributes_length = $attributes_length + 1 + 2 + 4; } else { print "\n This is not a valid option ($choosen_tlv). Calling EXIT... \n\n"; exit; } $tlv_number++; } # Add Attributes Length $packet_value = $packet_value . sprintf("%04x", $attributes_length); $packet_length = $packet_length + 2; # Add Attributes Value $packet_value = $packet_value . $attributes_value; $packet_length = $packet_length + $attributes_length; return ($packet_value, $packet_length); }
AdrianSimionov/docsis-generator
gen-capture.pl
Perl
mit
149,402
#! /usr/bin/env perl use strict; use warnings; use Getopt::Long; use POSIX qw/strftime/; my $verbose; my $backup_dir = '.'; my $ts; my $db; my $file; GetOptions( "database=s" => \$db, # string "backup_dir=s" => \$backup_dir, # string "verbose" => \$verbose # flag ) or die("Error in command line arguments\n"); if ( defined($db) ) { if ($db ne 'all') { # Set timestamp $ts = strftime( '%Y%m%d%H%M%S', localtime ); # Backup Database parts; backupDb($db); # Clean Definer statements and re-assemble cleanDefiners(); print "Backup completed :)\n Filename: $backup_dir/$db-backup-$ts.sql\n"; } else { my @databases = `mysqlshow | sed '1,/Databases/d'`; foreach my $database (@databases){ if (defined((split(' ', $database))[1]) and (split(' ', $database))[1] ne '') { backupDb((split(' ', $database))[1]); cleanDefiners(); print "Backup completed :)\n Filename: $backup_dir/$db-backup-$ts.sql\n"; } } } } else { die("Database name was not given"); } sub backupDb { $db = shift; # dumping out the schema print "Writing out the schema!\n"; `mysqldump --no-data --skip-triggers $db > $backup_dir/$db-schema-$ts.sql`; # dumping out the data print "Writing out the data\n"; `mysqldump --opt --skip-lock-tables --single-transaction --no-create-info --skip-triggers $db > $backup_dir/$db-data-$ts.sql`; print "Write out the triggers\n"; # dumping out the triggers `mysqldump --no-data --no-create-info $db > $backup_dir/$db-triggers-$ts.sql`; print "Write out the routines/functions!\n"; # dumping out the routines/functiones `mysqldump --routines --skip-triggers --no-create-info --no-data --no-create-db --skip-opt $db > $backup_dir/$db-funcs-$ts.sql`; } sub cleanDefiners { # Load file to memory loadFile("$backup_dir/$db-triggers-$ts.sql"); my $altered = $file; $altered =~ s/(\/\*!50017 DEFINER=\`\w.*\`@\`.+\`\*\/)//g; writeFile( "$backup_dir/$db-triggers-no-definer-$ts.sql", $altered ); print "Remove definers from triggers\n"; $altered = ''; loadFile("$backup_dir/$db-schema-$ts.sql"); $altered = $file; $altered =~ s/(\/\*\!50013.*?\*\/)//g; writeFile( "$backup_dir/$db-schema-$ts.sql", $altered ); print "Remove definers from schema/views\n"; $altered = ''; loadFile("$backup_dir/$db-funcs-$ts.sql"); $altered = $file; $altered =~ s/(DEFINER=`.+?`@`.+?`)//g; writeFile( "$backup_dir/$db-funcs-$ts.sql", $altered ); print "Remove definers from functions\n"; # Disable Foreign Key Checks `echo "SET foreign_key_checks = 0;" > $backup_dir/disable-foreign-keys.sql`; # Join the dump together again `cat $backup_dir/disable-foreign-keys.sql $backup_dir/$db-schema-$ts.sql $backup_dir/$db-data-$ts.sql $backup_dir/$db-triggers-no-definer-$ts.sql $backup_dir/$db-funcs-$ts.sql > $backup_dir/$db-backup-$ts.sql`; # Remove interim files `rm -f $backup_dir/$db-schema-$ts.sql $backup_dir/$db-data-$ts.sql $backup_dir/$db-triggers-no-definer-$ts.sql $backup_dir/$db-triggers-$ts.sql $backup_dir/$db-funcs-$ts.sql > /dev/null`; } sub loadFile { my $filename = shift; open(my $fh, '<', $filename ) or die "cannot open file $filename"; { local $/; $file = <$fh>; } close($fh); } sub writeFile { my $filename = shift; my $message = shift; open(my $fh, '>', $filename ) or die "cannot open file $filename"; print $fh $message; close($fh); }
guisea/mysql-backup-manager
bin/concisebackup.pl
Perl
mit
3,727
#!usr/bin/perl #!/usr/local/bin/perl #Title: Normalize each time data #Auther: Naoto Imamachi #ver: 1.0.0 #Date: 2014-09-01 use warnings; use strict; my $input = $ARGV[0]; my @list=( "mRNA", "ncRNA", ); #MAIN#################################### foreach my $filename(@list){ my $r2; my $half; my $a_1; my $a_2; my $b_2; my $a_3; my $b_3; my $c_3; open (IN,"<$input\_$filename\_rel_normalized_cal.fpkm_table") || die; open (OUT,">$input\_$filename\_rel_normalized_cal_model_selection_for_fig.fpkm_table") || die; select(OUT); OUTER:while(my $line = <IN>){ chomp $line; my @data = split /\t/,$line; if($data[0] eq "id"){ #print "gr_id\tmodel\tr2\thalf_life\n"; print "gr_id\tmodel\tr2\thalf_life\trambda\ta_1\ta_2\tb_2\ta_3\tb_3\tc_3\n"; next OUTER; } print "$data[0]\t"; if($data[1] eq "ok"){ #my @AIC = ( #"model1",$data[7]], #["model2",$data[13]], #["model3",$data[20]], #); #@AIC = sort{@$a[1] <=> @$b[1]} @AIC; $a_1 = $data[4]; $a_2 = $data[10]; $b_2 = $data[11]; $a_3 = $data[16]; $b_3 = $data[17]; $c_3 = $data[18]; INNER:foreach(0..2){ my $name = "model1"; #Model1 if($name eq "model1"){ $a_1 = $data[4]; $r2 = $data[3]; $half = $data[6]; if($half > 24){ $half = "24.0"; } if($a_1 > 0){ #print "model1\t$r2\t$half\n"; print "model1\t$r2\t$half\t0\t$a_1\t$a_2\t$b_2\t$a_3\t$b_3\t$c_3\n"; next OUTER; }else{ next INNER; } #Model2 }elsif($name eq "model2"){ $a_2 = $data[10]; $b_2 = $data[11]; $r2 = $data[9]; $half = $data[12]; if($half eq "Inf"){ $half = "24.0"; }elsif($half > 24){ $half= "24.0"; } if($a_2 > 0 && $b_2 > 0 && $b_2 < 1 ){ #print "model2\t$r2\t$half\n"; print "model2\t$r2\t$half\t0\t$a_1\t$a_2\t$b_2\t$a_3\t$b_3\t$c_3\n"; next OUTER; }else{ next INNER; } #Model3 }elsif($name eq "model3"){ $a_3 = $data[16]; $b_3 = $data[17]; $c_3 = $data[18]; $r2 = $data[15]; $half = $data[19]; if($half > 24){ $half = "24.0"; } if($a_3 > 0 && $b_3 > 0 && $c_3 < 1 && $c_3 > 0){ #print "model3\t$r2\t$half\n"; print "model3\t$r2\t$half\t0\t$a_1\t$a_2\t$b_2\t$a_3\t$b_3\t$c_3\n"; next OUTER; }else{ next INNER; } }else{ next INNER; } } #The others => Model1 $a_1 = $data[4]; $r2 = $data[3]; $half = $data[6]; if($a_1 < 0){ #print "model1\t$r2\t24\n"; print "model1\t$r2\t24\t0\t$a_1\t$a_2\t$b_2\t$a_3\t$b_3\t$c_3\n"; next OUTER; }else{ #print "no_good_model\t24\t\n"; print "no_good_model\t0\t0\t0\t0\t0\t0\t0\t0\t0\n"; next OUTER; } }else{ #print "$data[1]\tNA\tNA\n"; print "$data[1]\t0\t0\t0\t0\t0\t0\t0\t0\t0\n"; } } close(IN); close(OUT); select(STDOUT); } print "Process were successfully finished\n";
Naoto-Imamachi/NGS_data_analysis_pipeline
cuffnorm_BRIC-seq/F_model_selection_for_fig_model1_only.pl
Perl
mit
3,012
use Stream ':all'; my $s = iterate { my ($a, $b) = @{$_[0]}; $b++ if (rand() < 0.2); $a = rand() * 5 - 2 + $b * 10; [$a, $b]; } [0, 0]; my $t = cut_sort($s, sub {$_[0][0] <=> $_[1][0]}, sub { $_[1]->[1] > $_[0]->[1] + 5 }); $t = transform {"$_[0][0]\t$_[0][1]"} $t; { local $"= "\n"; show($t, 500); }
rcm/hop
Streams/ex_cut_sort.pl
Perl
apache-2.0
310
#!/usr/bin/env perl # 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. use strict; use warnings; use Bio::EnsEMBL::Registry; # # This script downloads all the paralogues of a given species # and prints them by group (gene-tree). Given another species, it can # also split the paralogues into "in-" and "out-" paralogues. # # NOTE: A group of paralogues (A1, A2, A3) will be printed only once, # the genes being listed in an arbitrary order # ## Load the registry automatically my $reg = "Bio::EnsEMBL::Registry"; $reg->load_registry_from_url('mysql://anonymous@ensembldb.ensembl.org'); ## Get the compara GenomeDB adaptor my $genome_db_adaptor = $reg->get_adaptor("Multi", "compara", "GenomeDB"); ## Get the compara member adaptor my $gene_member_adaptor = $reg->get_adaptor("Multi", "compara", "GeneMember"); ## Get the compara homology adaptor my $homology_adaptor = $reg->get_adaptor("Multi", "compara", "Homology"); my $species = "human"; my $genome_db = $genome_db_adaptor->fetch_by_registry_name($species); my $boundary_species = "mouse"; my $boundary_genome_db = $genome_db_adaptor->fetch_by_registry_name($boundary_species); my $all_genes = $gene_member_adaptor->fetch_all_by_GenomeDB($genome_db); my %protein_to_gene = map {$_->get_canonical_SeqMember->stable_id => $_->stable_id} @$all_genes; warn "Loaded ", scalar(@$all_genes), " genes\n"; sub print_groups_of_paralogues { my ($gene_member, $paralogues, $txt_prefix, $seen) = @_; return unless scalar(@$paralogues); #print $txt_prefix, "\n"; #map {print $_->toString(), "\n"} @$paralogues; my @para_stable_ids = map {$protein_to_gene{$_->get_all_Members()->[1]->stable_id}} @$paralogues; map {$seen->{$_} = 1} @para_stable_ids; my $paralogues_str = join(",", $gene_member->stable_id, @para_stable_ids); my $tree = $paralogues->[0]->gene_tree; my $tree_id = $tree->stable_id || $tree->get_value_for_tag('model_name'); print join("\t", $tree_id, $txt_prefix, scalar(@$paralogues)+1, $paralogues_str), "\n"; } my %seen = (); my %seeni = (); my %seeno = (); # Comment the blocks according to your needs foreach my $gene_member (@$all_genes) { unless ($seen{$gene_member->stable_id}) { # All paralogues my $all_paras = $homology_adaptor->fetch_all_by_Member($gene_member, -METHOD_LINK_TYPE => 'ENSEMBL_PARALOGUES'); print_groups_of_paralogues($gene_member, $all_paras, 'all', \%seen); } unless ($seeni{$gene_member->stable_id}) { # In-paralogues my $in_paras = $homology_adaptor->fetch_all_in_paralogues_from_Member_NCBITaxon($gene_member, $boundary_genome_db->taxon); print_groups_of_paralogues($gene_member, $in_paras, 'in', \%seeni); } unless ($seeno{$gene_member->stable_id}) { # Out-paralogues my $out_paras = $homology_adaptor->fetch_all_out_paralogues_from_Member_NCBITaxon($gene_member, $boundary_genome_db->taxon); print_groups_of_paralogues($gene_member, $out_paras, 'out', \%seeno); } }
Ensembl/ensembl-compara
scripts/examples/homology_getAllParalogues.pl
Perl
apache-2.0
3,620
package DMOZ::Weighter; use strict; use warnings; use MooseX::Role::Parameterized; parameter field => ( isa => 'Str', required => 1 ); role { # weighter has 'weighter' => ( is => 'ro' , isa => 'CodeRef' , builder => '_weighter_builder' ); method _weighter_builder => sub { my $this = shift; my $weighter = sub { my $object = shift; my $order = shift; my $feature = shift; # CURRENT : access global data via a service my $corpus_size = $this->global_data->global_count( 'summary' , $order ); my $global_count = $this->global_data->global_count( 'summary' , $order , join( " " , ref( $feature ) ? @{ $feature } : $feature ) ); my $weight = log ( $corpus_size / ( 1 + $global_count ) ); if ( $weight < 0 ) { $this->error( "Invalid Weight for feature ($feature) is negative: $weight"); } return $weight; }; return $weighter; }; }; 1;
ypetinot/web-summarization
src/perl/DMOZ/Weighter.pm
Perl
apache-2.0
941
#!/usr/bin/env perl # # $Id: scaledb_plugin_diag.pl,v 1.1 2015-12-18 00:18:18 igor Exp $ # # # to analyze MySQL configuration with respect to file system layout, # network and memory # use strict; use warnings; use Getopt::Long; my $ERRORS =0; my %mysql_config=(); my %config =(); my $my_cnf=undef; my $verbose=undef; my $help =undef; my $plugin_cnf=undef; my $mysqld = undef; my $ts = time; my $temp_dir=defined $ENV{TEMP}?$ENV{TEMP}:"/tmp"; my $output_file = "$temp_dir/$ENV{USER}.plugin_info.$ts.txt"; sub help { print "Usage: --config=<mysql_config> [options]\n"; print " options:\n"; print " --help : prints this message and exit\n"; print " --verbose : prints messages about what it does\n"; print " --mysqld=<binary>: location of mysqld (default:none)\n"; print " -o filename : stores diagnostics into file (default : \$TEMP/\$USER.cas_info.txt\n"; exit 1; } sub info { my $message = shift; my ($Y,$M,$D,$h,$m,$s) = (localtime())[5,4,3,2,1,0]; $Y+=1900; $M+=1; my $formated_message=sprintf("%d-%02d-%02d %02d:%02d.%02d INFO %s\n",$Y,$M,$D,$h,$m,$s,$message); # always print to output file for diagnostics print FINFO $formated_message; # but only print to STDOUT when user set $verbose flag return unless $verbose ; print $formated_message; } sub info2 { my $message = shift; my ($Y,$M,$D,$h,$m,$s) = (localtime())[5,4,3,2,1,0]; $Y+=1900; $M+=1; my $formated_message=sprintf("%d-%02d-%02d %02d:%02d.%02d INFO %s\n",$Y,$M,$D,$h,$m,$s,$message); print FINFO $formated_message; } sub error_exit { my $message = shift; my ($Y,$M,$D,$h,$m,$s) = (localtime())[5,4,3,2,1,0]; $Y+=1900; $M+=1; my $formated_message = sprintf("%d-%02d-%02d %02d:%02d.%02d FATAL %s\n",$Y,$M,$D,$h,$m,$s,$message); $ERRORS=1 if($ERRORS==0); print FINFO $formated_message; print $formated_message; print FINFO "Total errors: $ERRORS\n"; print "Total errors: $ERRORS\n"; close FINFO; print "Results of this run saved in '$output_file'"; exit 1; } sub error { $ERRORS++; my $message = shift; my ($Y,$M,$D,$h,$m,$s) = (localtime())[5,4,3,2,1,0]; $Y+=1900; $M+=1; my $formated_message = sprintf("%d-%02d-%02d %02d:%02d.%02d ERROR %s\n",$Y,$M,$D,$h,$m,$s,$message); print FINFO $formated_message; print $formated_message; } sub check_must_haves{ my $sub = "check_must_haves"; info2 "$sub - entered"; my @must_haves = qw(scaledb_cas_config_ips scaledb_cas_config_ports ); foreach my $param(@must_haves){ info "$sub - verifying config param '$param' exists"; if(!exists $config{$param}){ error "$sub - missing config parameter:'$param'"; info2 "$sub - dumping configs:"; map{info2 " '$_'='$config{$_}'\n"} (keys %config); error_exit "$sub - can't continue without '$param'"; } } info "$sub - checking for transaction-isolation=READ-COMMITTED"; if(! exists $mysql_config{transaction_isolation} or $mysql_config{transaction_isolation} ne lc'READ-COMMITTED') { error "$sub - mysql configuration missing or incorrect,". " should have: transaction-isolation=READ-COMMITTED"; } info "$sub - checking for query_cache_size=0"; if(! exists $mysql_config{query_cache_size} or $mysql_config{query_cache_size} ne '0') { error "$sub - mysql configuration missing or incorrect,". " should have: query_cache_size=0"; } info2 "$sub - exited"; } # # returns true if param is know # false otherwise # sub check_known_params{ my $sub = "check_known_params"; my $new_param = shift; info2 "$sub - received param '$new_param'"; my %list_of_params = ( "scaledb_data_directory"=>1, "scaledb_log_directory"=>1, "scaledb_max_file_handles"=>1, "scaledb_aio_flag"=>1, "scaledb_io_threads"=>1, "scaledb_cas_config_ips"=>1, "scaledb_cas_config_ports"=>1, "scaledb_slm_threads"=>1, "scaledb_buffer_size_index"=>1, "scaledb_buffer_size_data"=>1, "scaledb_buffer_size_blob"=>1, "scaledb_cluster_password"=>1, "scaledb_debug"=>2, "scaledb_debug_interactive"=>2, "scaledb_debug_buffer_size"=>2, "scaledb_debug_file"=>1, "scaledb_debug_lines_per_file"=>1, "scaledb_debug_files_count"=>1, "scaledb_debug_string"=>2, "scaledb_debug_locking_mode"=>2, "scaledb_log_sql"=>3, "scaledb_node_name"=>2, "scaledb_service_port"=>2, "scaledb_cluster_port"=>1, "scaledb_cluster_user"=>1, ); if(!exists $list_of_params{$new_param}){ error "$sub - parameter:'$new_param' is unknown" ; return 0; } info "$sub - verified '$new_param' - ok"; info2 "$sub - exited"; return 1; } # # From Mb to Kb # sub calc_scaledb_memory { my $sub = "calc_scaledb_memory"; info2 "$sub - entered"; my $ret_code=3; # # when buffers specified in 8Kblocks # foreach my $component ( qw(index data blob)){ if(!exists $config{"scaledb_buffer_size_$component"}){ info "$sub - cache for $component is not specified"; $config{"scaledb_buffer_size_$component"}=0; $ret_code--; next; } info2 "$sub - cache configuration for $component: ". $config{"scaledb_buffer_size_$component"}; if($config{"scaledb_buffer_size_$component"}=~/^(\d+)$/){ info2 "$sub - cache for '$component' configured in 8K blocks!"; $config{"scaledb_buffer_size_$component"}=$1*8; } } # # exiting because cache sizes are not specified # return undef unless $ret_code; # # when buffers specified in Mb # foreach my $component ( qw(index data blob)){ if($config{"scaledb_buffer_size_$component"}=~/^(\d+)\s*M$/){ $config{"scaledb_buffer_size_$component"}=$1*1024; } if($config{"scaledb_buffer_size_$component"}!~/^(\d+)$/){ error "$sub - invalid value '$1' for $component cache configuration"; next; } info "$sub - converted cache size for $component to (Kb) ". $config{"scaledb_buffer_size_$component"}; } info2 "$sub - exited"; } # # From Mb to Kb # - POST - mysql_config{total_required_memory} # sub calc_mysql_memory { my $sub = "calc_mysql_memory"; info2 "$sub - entered"; my $ret_code=3; $mysql_config{total_required_memory}=0; my @list_of_buffers = qw( key_buffer_size read_rnd_buffer_size sort_buffer_size myisam_sort_buffer_size ); my @list_of_innodb_buffers = qw( innodb_additional_mem_pool_size innodb_log_file_size innodb_buffer_pool_size ); my @all_buffers; if(exists $mysql_config{skip_innodb} or ( exists $mysql_config{skip_innodb} and $mysql_config{skip_innodb} == '1' )){ info2 "$sub - innodb disabled - not couting innodb buffers"; @all_buffers = @list_of_buffers; }else{ info2 "$sub - including innodb buffers"; @all_buffers = (@list_of_buffers,@list_of_innodb_buffers); } # # when buffers specified in 8Kblocks # foreach my $param( @all_buffers ){ if(!exists $mysql_config{$param}){ info2 "$sub - buffer $param is not set"; next; } info2 "$sub - buffer $param set to:$mysql_config{$param}"; if($mysql_config{$param}=~/^(\d+)$/){ info2 "$sub - buffer $param configured in bytes,converting to kb"; $mysql_config{$param}=$1/1024; }elsif($mysql_config{$param}=~/^(\d+)\s*(.)$/){ if(lc $2 eq 'm'){ info2 "$sub - buffer $param configured in M-bytes,converting to kb"; $mysql_config{$param}=$1*1024; }elsif(lc $2 eq 'k'){ info2 "$sub - buffer $param configured in K-bytes,don't convert"; }elsif(lc $2 eq 'g'){ info2 "$sub - buffer $param configured in G-bytes,converting to kb"; $mysql_config{$param}=$1*1024*1024; }else{ error "$sub - buffer $param configured with unsupported units,converting to kb"; $mysql_config{$param}=$1*1024; } }else{ error "$sub - cant' understand configuration for $param,settig to 0"; $mysql_config{$param}=0; } $mysql_config{total_required_memory}+=$mysql_config{$param}; } info2 "$sub - mysql requires (Kb):$mysql_config{total_required_memory}"; info2 "$sub - exited"; } sub evaluate_memory { my $sub = "evaluate_memory"; info2 "$sub - entered"; my %meminfo = (); open MEMINFO,"/proc/meminfo" or error_exit "main - failed to open /proc/meminfo:$!"; while(<MEMINFO>){ chomp; if (/^(\w+):\s*(\d+)\b/){ info2 "main - meminfo:'$1'='$2'"; $meminfo{$1}=$2; } } close MEMINFO; my $available_memory = $meminfo{MemFree}+$meminfo{Cached}; my $user_requested_memory = $config{scaledb_buffer_size_index} + $config{scaledb_buffer_size_data} + $config{scaledb_buffer_size_blob} + $mysql_config{total_required_memory}; info "$sub - comparing available_memory(KB):'$available_memory' to needed '$user_requested_memory'"; my $diff = 100*$user_requested_memory/$available_memory; info2 "$sub - calculated prcntl diff: $diff "; if ($user_requested_memory>$available_memory){ error "$sub - requested too much memory for mysql!"; }elsif ($diff > 80 ){ error "$sub - mysql maybe configured for too much memory !"; }else{ info "$sub - memory allocation for mysql looks ok"; } info2 "$sub - exited"; } sub parsing_mysql_conifg { my $sub = "parsing_mysql_config"; info2 "$sub - entered"; if ( ! -r $my_cnf ){ error_exit "$sub - $my_cnf does not exist or is not readable"; } open FMYCNF,"$my_cnf" or error_exit "$sub - failed to open configuration $my_cnf:$!\n"; info "$sub - reading configuration from '$my_cnf'"; my $started_mysqld_section=undef; my $mysqld_section_found=undef; while(<FMYCNF>){ next if /^#/; chomp; info2 "$sub - reading mysql config:$_"; last if($started_mysqld_section and /^\[/); $started_mysqld_section=1 if(/^\[\s*mysqld\s*\]/); next unless $started_mysqld_section; $mysqld_section_found=1; if(/\s*(.*?)\s*=\s*(.*?)\s*$/){ my $param=lc $1; my $value=lc $2; info2 "$sub - got mysql config param :'$param'='$value'"; $value=~s/("|')//g; $param=~s/-/_/g; $value=1 if $value eq 'true'; $value=0 if $value eq 'false'; if(exists $mysql_config{$param}){ error "$sub - param '$param' reassigning from '$mysql_config{$param}' to '$mysql_config{$param}'"; } $mysql_config{$param}=$value; } } close FMYCNF; error_exit "failed to find [mysqld] ". " section in mysql configuration file" unless $mysqld_section_found; $mysql_config{port}=3306 unless exists $mysql_config{port}; info2 "$sub - exited"; } sub find_plugin_config { my $sub = "find_plugin_config"; info2 "$sub - entered"; info2 "$sub - determining absolute path for plugin config"; if(exists $mysql_config{scaledb_config_file}){ $plugin_cnf = $mysql_config{scaledb_config_file}; }else{ if(exists $mysql_config{datadir}){ $mysql_config{datadir}=~s/\/$//; $plugin_cnf = $mysql_config{datadir}."/scaledb.cnf"; }elsif($mysqld){ my $mysqld_help = `$mysqld --help --verbose`; if($?){ error "$sub - Failed to find plugin configuration"; error_exit "$sub - Failed to start mysqld to get default datadir"; } }else{ error_exit "$sub - Failed to find plugin configuration\n". " provide '--mysqld=mysqld_binary_location'\n". " to get default datadir"; } } info "$sub - found plugin configuration:'$plugin_cnf'"; error_exit "$sub - There is no such file :'$plugin_cnf',". " or it is not readable" unless -r $plugin_cnf; info2 "$sub - exited"; } sub parsing_plugin_config { my $sub = "parsing_plugin_config"; info2 "$sub - entered"; open FCNF,"$plugin_cnf" or error_exit "$sub - failed to open configuration $plugin_cnf:$!\n"; info "$sub - reading configuration from '$plugin_cnf'"; while(<FCNF>){ next if /^#/; chomp; if(/\s*(.*?)\s*=\s*(.*?)\s*$/){ my $param=$1; my $value=$2; info2 "$sub - got plugin config param :'$param'='$value'"; next unless check_known_params($param); $value=~s/("|')//g; if(exists $config{$param}){ error "$sub - param '$param' reassigning from '$config{$param}' to '$config{$param}'"; } $config{$param}=$value; } } close FCNF; info2 "$sub - exited"; } sub verify_plugin_location { my $sub = "verify_plugin_location"; info2 "$sub - entered"; if(exists $mysql_config{plugin_dir}){ my $scaledb_plugin = "$mysql_config{plugin_dir}/ha_scaledb.so"; error "$sub - failed to find $scaledb_plugin" unless -f $scaledb_plugin; } my @libscaledb=(); if(exists $ENV{LD_LIBRARY_PATH}){ foreach my $dir (split /:/,$ENV{LD_LIBRARY_PATH}){ $dir=~s/\/$//; if( -x "$dir/libscaledb.so" ){ push @libscaledb,"$dir/libscaledb.so"; } } } foreach my $dir (qw(/lib64 /usr/lib64 /usr/local/lib64)){ if( -x "$dir/libscaledb.so" ){ push @libscaledb,"$dir/libscaledb.so"; } } if(@libscaledb==1){ info "$sub - found libscaledb: $libscaledb[0]"; }elsif(@libscaledb==0){ error"$sub - did not find libscaledb, specify in LD_LIBRARY_PATH"; }else{ error "$sub - found many instances of libscaledb library:@libscaledb"; } info2 "$sub - exited"; } # # # MAIN # # GetOptions("config=s"=>\$my_cnf, "help"=>\$help, "verbose"=>\$verbose, "mysqld=s"=>\$mysqld, "o=s"=>\$output_file); help() unless $my_cnf; help() if $help; open FINFO,">$output_file" or die "Failed openning output file for diagnostic messages:$output_file:$!\n"; info2 "main - dumping diagnositcs to '$output_file'"; parsing_mysql_conifg(); find_plugin_config(); parsing_plugin_config(); check_must_haves(); verify_plugin_location(); my @cas_ips; my @cas_ports; info "main - extracting cas configuration ip and port"; @cas_ips = split /,/,$config{scaledb_cas_config_ips}; @cas_ports = split /,/,$config{scaledb_cas_config_ports}; if (@cas_ips==1){ info "main - configured without mirror!"; }elsif (@cas_ips==2){ info "main - configured for a mirror"; }else{ error "main - to many configuration ips - support only for 1 mirror"; } my $cas_ip = $cas_ips[0]; my $cas_port = $cas_ports[0]; $cas_ip=~s/\s*//g; $cas_port=~s/\s*//g; # # bad formating # error_exit "main - bad ip address:$cas_ip" if $cas_ip!~/^\d+\.\d+\.\d+\.\d+$/; error_exit "main - bad port :$cas_port" if $cas_port!~/^\d+$/; # # CAS_PORT should be in allowable range and available # error "main - cas_port:$cas_port is not in ". "permissisble range:(1000 to 56000)" if $cas_port<1000 or $cas_port>56000; info "main - trying to ping '$cas_ip:$cas_port'"; # # TESTING THAT IP ADDRESS AVAILABLE # info2 "main - searching for netcat binary"; my $netcat=`which nc 2>/dev/null`; if (!defined $netcat){ info2 "didn't find netcat in PATH, looking in other places"; foreach my $dir (qw(/sbin /usr/sbin /usr/local/sbin)){ $netcat="$dir/nc" if -f "$dir/nc"; } } if($netcat){ chomp $netcat; info "main - found netcat: '$netcat'"; my $cmd = "echo PING | $netcat $cas_ip $cas_port"; info "main - running:'$cmd'"; my @nc_output=`$cmd 2>&1`; if($?){ error "main - netcat failed to connect to cas" ; }elsif( $nc_output[0]!~/PONG/){ error "main - test failed for $cas_ip:$cas_port" }else{ info "main - $cas_ip:$cas_port test - ok" } }else{ error "failed to find netcat, continue without". " testing for CAS availability" unless $netcat; } # # network testing # my @listeners=(); info "main - searching for netstat binary in PATH"; my $netstat = `which netstat 2>/dev/null`; error_exit "main - failed to find netstat" if($?); chomp $netstat; $netstat = "$netstat -t -n -p -l -T "; info "main - runnning '$netstat' to determine running TCP servers"; my @ntout = `$netstat 2>&1`; error "main - failed to run netstat:@ntout" if ($?); foreach my $line (@ntout){ next unless $line=~/^tcp/; my $server = (split/\s+/,$line)[3]; my ($server_ip,$server_port) = split/:/,$server; if( $server_port eq $mysql_config{port}){ error "main - port $mysql_config{port} is not available - it is already in use"; } } # # got overal scaledb # calc_scaledb_memory(); calc_mysql_memory(); evaluate_memory(); # # our information collected # close FINFO; print "Results of this run saved in '$output_file'\n";
igbelousov/scaledb-deb-package
debian/usr/bin/scaledb_plugin_diag.pl
Perl
apache-2.0
17,805
package PerlOrg::Control::Search; use strict; use base qw(Combust::Control); use Yahoo::Search; use Combust::Constant qw(OK); use LWP::Simple qw(get); use XML::Simple qw(XMLin); my $yahoo = Yahoo::Search->new(AppId => 'perl.org-search'); sub handler { my $self = shift; my $query = $self->req_param('q'); my $page = $self->req_param('p') || 1; my $count = $self->req_param('n') || 15; my $maxcount = $yahoo->MaxCount('Doc'); $count = $maxcount if $count > $maxcount; $self->tpl_param('count_per_page' => $count); $self->tpl_param('page_number' => $page); my $start = ($page * $count) - $count; if ($query) { my $site = 'site:perl.org -site:use.perl.org'; my $search = $yahoo->Query(Doc => $query . " $site", Start => $start, Count => $count, ); if ($search->CountAvail < 10) { my $spell = $yahoo->Query(Spell => $query); $self->tpl_param(spell => $spell); #warn Data::Dumper->Dump([\$spell], [qw(spell)]); } #my $related= $yahoo->Query(Related => $query); #$self->tpl_param(related => $related); #warn Data::Dumper->Dump([\$related], [qw(related)]); $self->tpl_param(search => $search); $self->tpl_param(query => $query); #warn Data::Dumper->Dump([\$search], [qw(search)]); if ($page == 1) { my $xml = get("http://search.cpan.org/search?mode=all&format=xml&n=5&query=". $query); my $cpan = XMLin($xml, KeepRoot => 0, KeyAttr => [], ForceArray => [qw(author dist module)]); for my $type (qw(module dist author)) { push @{$cpan->{results}}, @{$cpan->{$type}} if $cpan->{$type}; } warn Data::Dumper->Dump([\$cpan], [qw(cpan)]); $self->tpl_param('cpan', $cpan); } } $self->send_output(scalar $self->evaluate_template('search/results.html')); return OK; } 1;
autarch/perlweb
lib/PerlOrg/Control/Search.pm
Perl
apache-2.0
1,841
#!/usr/bin/env perl # Copyright 2014 European Molecular Biology Laboratory - 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. use strict; use warnings; use Mojolicious::Lite; use Carp; use EpiRR::Schema; use EpiRR::Service::OutputService; use EpiRR::App::Controller; use utf8; plugin 'Config'; my $db = app->config('db'); my $schema = EpiRR::Schema->connect( $db->{dsn}, $db->{user}, $db->{password}, ) || die "Could not connect"; my $os = EpiRR::Service::OutputService->new( schema => $schema ); my $controller = EpiRR::App::Controller->new( output_service => $os, schema => $schema ); get '/summary' => sub { my $self = shift; my ( $project_summary, $status_summary, $all_summary )= $controller->fetch_summary(); $self->respond_to( json => sub { $self->render( json => { 'summary' => $all_summary, 'project_summary' => $project_summary, 'status_summary' => $status_summary, } ); }, html => sub { $self->stash( title => 'Epigenome Summary', project_summary => $project_summary, status_summary => $status_summary, all_summary => $all_summary ); $self->render( template => 'summary' ); } ); }; get '/view/all' => sub { my $self = shift; my $datasets = $controller->fetch_current(); $self->respond_to( json => sub { my @hash_datasets; for my $d (@$datasets) { my $url = $self->req->url->to_abs; my $path = $url->path; my $hd = $d->to_hash; my $full_accession = $d->full_accession; my $link_path = $path; $link_path =~ s!/view/all!/view/$full_accession!; $link_path =~ s/\.json$//; $url->path($link_path); $hd->{_links}{self} = "$url"; push @hash_datasets, $hd; } $self->render( json => \@hash_datasets ); }, html => sub { $self->stash( datasets => $datasets, title => 'Epigenomes', ); $self->render( template => 'viewall' ); }, ); }; get '/view/#id' => sub { my $self = shift; my $id = $self->param('id'); my $dataset = $controller->fetch($id); if ( !$dataset ) { return $self->reply->not_found; } my $url = $self->req->url->to_abs; my $acc = $dataset->accession; my $this_version = $dataset->full_accession; my $path = $url->path; my $links = { self => { href => $url }, }; if ( $dataset->version > 1 ) { my $prev_url = $url; my $prev_version = $dataset->accession . '.' . ( $dataset->version - 1 ); if ( $prev_url !~ s/$this_version/$prev_version/ ) { $prev_url =~ s/$acc/$prev_version/; } $links->{previous_version} = {href => $prev_url}; } if ( !$dataset->is_current ) { my $curr_url = $url; $curr_url =~ s/$this_version/$acc/; $links->{current_version} = { href => $curr_url }; } $self->respond_to( json => sub { my $hd = $dataset->to_hash; $hd->{_links} = $links; $self->render( json => $hd ); }, html => sub { $self->stash( dataset => $dataset, links => $links, title => 'Epigenome ' . $dataset->full_accession, ); $self->render( template => 'viewid' ); }, ); }; get '/' => sub { my $self = shift; my $url = $self->req->url->to_abs->to_string; $url =~ s/\/$//; $self->render( template => 'index', title => '', url => $url ); }; # Start the Mojolicious command system app->start; __DATA__ @@ layouts/layout.html.ep <!DOCTYPE html> <html> <head> <title>EpiRR <%= $title %></title> <link href="favicon.ico" rel="icon" type="image/x-icon" /> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <style> #totalrow td { border-top-color: #DDD; border-top-width: 2px; border-top-style: solid; } .ctotal { border-left-color: #DDD; border-left-width: 2px; border-left-style: solid; } </style> </head> <body> <div class="container-fluid"> <%= content %> </div> <!-- Latest compiled and minified JavaScript --> <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <script src="https://www.ebi.ac.uk/vg/epirr/GDPR_banner.js"></script> </body> </html> @@ index.html.ep % layout 'layout'; <h1>EpiRR REST API</h1> <h2>Introduction</h2> <p>The <b>Epi</b>genome <b>R</b>eference <b>R</b>egistry, aka EpiRR, serves as a registry for datasets grouped in reference epigenomes and their respective metadata, including direct links to the raw data in public sequence archives. IHEC reference epigenomes must meet the minimum the criteria listed <a target="_blank" href="http://ihec-epigenomes.org/research/reference-epigenome-standards/">here</a> and any associated metadata should comply with the IHEC specifications described <a target="_blank" href="https://github.com/IHEC/ihec-metadata/blob/master/specs/Ihec_metadata_specification.md">here</a>.</p> <br> <h2>Accessing EpiRR data</h2> <p>EpiRR REST API provides language agnostic bindings to the EpiRR data, which you can access from <a href="https://www.ebi.ac.uk/vg/epirr/">https://www.ebi.ac.uk/vg/epirr/</a></p> <h3>REST API Endpoints</h3> <dl class="dl-horizontal"> <dt><a href="<%= $url %>/summary">/summary</a></dt> <dd>Report summary stats</dd> <dt><a href="<%= $url %>/view/all">/view/all</a></dt> <dd>List all current reference Epigenomes</dt> <dt>/view/:id</dt> <dd>View in detail a specific reference Epigenome</dt> </dl> <h3>Response types</h3> <p>Append <code>?format=<var>x</var></code> to the end of your query to control the format.</p> <p>Formats available:</p> <ul> <li>json</li> <li>html</li> </ul> <p>Alternatively, use the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">"Accept"</a> header in your HTTP request.</p> <br> <h2>How to make submissions to EpiRR</h2> <p>Submissions to EpiRR can be arranged by contacting <a href="mailto:blueprint-dcc@ebi.ac.uk">blueprint-dcc@ebi.ac.uk</a>. Submissions are accepted as either JSON or custom text format files, where one file must be used per reference epigenome. For more information on EpiRR submissions, please visit the <a target="_blank" href="https://github.com/Ensembl/EpiRR">EpiRR Github repository</a>.</p> @@ viewid.html.ep % layout 'layout'; <h1><%= $dataset->full_accession %></h1> <dl class="dl-horizontal"> <dt>Type</dt><dd><%= $dataset->type %></dd> <dt>Status</dt><dd><%= $dataset->status %></dd> <dt>Project</dt><dd><%= $dataset->project %></dd> <dt>Local name</dt><dd><%= $dataset->local_name %></dd> <dt>Description</dt><dd><%= $dataset->description %></dd> <dt>Is live version?</dt><dd><%= $dataset->is_current ? 'yes' : 'no' %></dd> % if ($links->{current_version} || $links->{previous_version}) { <dt>Other versions</dt> % if ($links->{current_version}) { <dd><a href="<%= $links->{current_version}{href}%>">live</a></dd> %} % if ($links->{previous_version}) { <dd><a href="<%= $links->{previous_version}{href}%>">previous</a></dd> %} %} </dl> <h2>Metadata</h2> <dl class="dl-horizontal"> % for my $kv ($dataset->meta_data_kv) { <dt><%= $kv->[0] %></dt><dd><%= $kv->[1] %></dd> % } </dl> <h2>Raw data</h2> <table class="table table-hover table-condensed table-striped"> <thead> <tr> <th>Assay type</th> <th>Experiment type</th> <th>Archive</th> <th>Primary ID</th> <th>Secondary ID</th> <th>Link</th> </tr> </thead> <tbody> % for my $rd ($dataset->all_raw_data) { <tr> <td><%= $rd->assay_type %></td> <td><%= $rd->experiment_type %></td> <td><%= $rd->archive %></td> <td><%= $rd->primary_id %></td> <td><%= $rd->secondary_id %></td> <td><a href="<%= $rd->archive_url %>">View in archive</a></td> </tr> % } </tbody> </table> @@ viewall.html.ep % layout 'layout'; <h1>EpiRR Epigenomes</h1> <table class="table table-hover table-condensed table-striped"> <thead> <tr> <th>Project</th> <th>Type</th> <th>Status</th> <th>ID</th> <th>Local name</th> <th>Description</th> <th></th> </tr> </thead> <tbody> % for my $d (@$datasets) { <tr> <td><%= $d->project %></td> <td><%= $d->type %></td> <td><%= $d->status %></td> <td><%= $d->full_accession %></td> <td><%= $d->local_name %></td> <td><%= $d->description %></td> <td><a href="./<%= $d->full_accession %>">Detail</a></td> </tr> % } </tbody> </table> @@ summary.html.ep % layout 'layout'; <h1>EpiRR Epigenome Summary</h1> <table class="table table-hover table-condensed table-striped"> <thead> <tr> <th>Project</th> % for my $s ( sort {$a cmp $b} keys %$status_summary) { <th><%= $s %></th> % } <th class="ctotal">Total Epigenome count</th> </tr> </thead> <tbody> % for my $sp (sort {$a cmp $b} keys %$project_summary) { <tr> <td><%= $sp %></td> % for my $st ( sort {$a cmp $b} keys %$status_summary) { <td><%= $$all_summary{$sp}{$st} // 0%></td> %} <td class="ctotal"><%= $$project_summary{$sp} %></td> </tr> % } <tr id="totalrow"> <td>Total</td> % my $total_dataset_count = 0; % for my $s ( sort {$a cmp $b} keys %$status_summary) { % $total_dataset_count += $$status_summary{$s}; <td><%= $$status_summary{$s} %></td> % } <td class="ctotal"><%=$total_dataset_count %></td> </tr> </tbody> </table> @@ not_found.html.ep % layout 'layout', title => '404'; <h1>Not found</h1> <p>We do not have any information on that. Please see the <%= link_to 'list of records' => '/view/all' %>.</p>
EMBL-EBI-GCA/EpiRR
web/epirr.pl
Perl
apache-2.0
10,754
# # 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 network::juniper::ggsn::mode::globalstats; use base qw(centreon::plugins::templates::counter); use strict; use warnings; use Digest::MD5 qw(md5_hex); sub custom_drop_in_calc { my ($self, %options) = @_; $self->{result_values}->{ggsnUplinkDrops} = $options{new_datas}->{$self->{instance} . '_ggsnUplinkDrops'} - $options{old_datas}->{$self->{instance} . '_ggsnUplinkDrops'}; $self->{result_values}->{ggsnUplinkPackets} = $options{new_datas}->{$self->{instance} . '_ggsnUplinkPackets'} - $options{old_datas}->{$self->{instance} . '_ggsnUplinkPackets'}; if ($self->{result_values}->{ggsnUplinkPackets} == 0) { $self->{result_values}->{drop_prct} = 0; } else { $self->{result_values}->{drop_prct} = $self->{result_values}->{ggsnUplinkDrops} * 100 / $self->{result_values}->{ggsnUplinkPackets}; } return 0; } sub custom_drop_out_calc { my ($self, %options) = @_; $self->{result_values}->{ggsnDownlinkDrops} = $options{new_datas}->{$self->{instance} . '_ggsnDownlinkDrops'} - $options{old_datas}->{$self->{instance} . '_ggsnDownlinkDrops'}; $self->{result_values}->{ggsnDownlinkPackets} = $options{new_datas}->{$self->{instance} . '_ggsnDownlinkPackets'} - $options{old_datas}->{$self->{instance} . '_ggsnDownlinkPackets'}; if ($self->{result_values}->{ggsnDownlinkPackets} == 0) { $self->{result_values}->{drop_prct} = 0; } else { $self->{result_values}->{drop_prct} = $self->{result_values}->{ggsnDownlinkDrops} * 100 / $self->{result_values}->{ggsnDownlinkPackets}; } return 0; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'global', type => 0, cb_prefix_output => 'prefix_global_output', skipped_code => { -10 => 1 } } ]; $self->{maps_counters}->{global} = [ { label => 'traffic-in', set => { key_values => [ { name => 'ggsnUplinkBytes', per_second => 1 } ], output_template => 'Traffic In : %s %s/s', output_change_bytes => 2, perfdatas => [ { label => 'traffic_in', template => '%s', unit => 'b/s', min => 0, cast_int => 1 }, ], } }, { label => 'traffic-out', set => { key_values => [ { name => 'ggsnDownlinkBytes', per_second => 1 } ], output_template => 'Traffic Out : %s %s/s', output_change_bytes => 2, perfdatas => [ { label => 'traffic_out', template => '%s', unit => 'b/s', min => 0, cast_int => 1 }, ], } }, { label => 'drop-in', set => { key_values => [ { name => 'ggsnUplinkDrops', diff => 1 }, { name => 'ggsnUplinkPackets', diff => 1 } ], output_template => 'Drop In Packets : %.2f %%', threshold_use => 'drop_prct', output_use => 'drop_prct', closure_custom_calc => \&custom_drop_in_calc, perfdatas => [ { label => 'drop_in', value => 'ggsnUplinkDrops', template => '%s', min => 0, max => 'ggsnUplinkPackets' }, ], } }, { label => 'drop-out', set => { key_values => [ { name => 'ggsnDownlinkDrops', diff => 1 }, { name => 'ggsnDownlinkPackets', diff => 1 } ], output_template => 'Drop Out Packets : %.2f %%', threshold_use => 'drop_prct', output_use => 'drop_prct', closure_custom_calc => \&custom_drop_out_calc, perfdatas => [ { label => 'drop_out', value => 'ggsnDownlinkDrops', template => '%s', min => 0, max => 'ggsnDownlinkPackets' }, ], } }, { label => 'active-pdp', set => { key_values => [ { name => 'ggsnNbrOfActivePdpContexts' } ], output_template => 'Active Pdp : %s', perfdatas => [ { label => 'active_pdp', template => '%s', min => 0 }, ], } }, { label => 'attempted-activation-pdp', set => { key_values => [ { name => 'ggsnAttemptedActivation', diff => 1 } ], output_template => 'Attempted Activation Pdp : %s', perfdatas => [ { label => 'attempted_activation_pdp', template => '%s', min => 0 }, ], } }, { label => 'attempted-deactivation-pdp', set => { key_values => [ { name => 'ggsnAttemptedDeactivation', diff => 1 } ], output_template => 'Attempted Deactivation Pdp : %s', perfdatas => [ { label => 'attempted_deactivation_pdp', template => '%s', min => 0 }, ], } }, { label => 'attempted-deactivation-pdp', set => { key_values => [ { name => 'ggsnAttemptedDeactivation', diff => 1 } ], output_template => 'Attempted Deactivation Pdp : %s', perfdatas => [ { label => 'attempted_deactivation_pdp', template => '%s', min => 0 }, ], } }, { label => 'attempted-self-deactivation-pdp', set => { key_values => [ { name => 'ggsnAttemptedSelfDeactivation', diff => 1 } ], output_template => 'Attempted Self Deactivation Pdp : %s', perfdatas => [ { label => 'attempted_self_deactivation_pdp', template => '%s', min => 0 }, ], } }, { label => 'attempted-update-pdp', set => { key_values => [ { name => 'ggsnAttemptedUpdate', diff => 1 } ], output_template => 'Attempted Update Pdp : %s', perfdatas => [ { label => 'attempted_update_pdp', template => '%s', min => 0 }, ], } }, { label => 'completed-activation-pdp', set => { key_values => [ { name => 'ggsnCompletedActivation', diff => 1 } ], output_template => 'Completed Activation Pdp : %s', perfdatas => [ { label => 'completed_activation_pdp', template => '%s', min => 0 }, ], } }, { label => 'completed-deactivation-pdp', set => { key_values => [ { name => 'ggsnCompletedDeactivation', diff => 1 } ], output_template => 'Completed Deactivation Pdp : %s', perfdatas => [ { label => 'completed_deactivation_pdp', template => '%s', min => 0 }, ], } }, { label => 'completed-self-deactivation-pdp', set => { key_values => [ { name => 'ggsnCompletedSelfDeactivation', diff => 1 } ], output_template => 'Completed Self Deactivation Pdp : %s', perfdatas => [ { label => 'completed_self_deactivation_pdp', emplate => '%s', min => 0 }, ], } }, { label => 'completed-update-pdp', set => { key_values => [ { name => 'ggsnCompletedUpdate', diff => 1 } ], output_template => 'Completed Update Pdp : %s', perfdatas => [ { label => 'completed_update_pdp', template => '%s', min => 0 }, ], } }, ]; } sub prefix_global_output { my ($self, %options) = @_; return 'Global Stats '; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options, statefile => 1); bless $self, $class; $options{options}->add_options(arguments => { }); return $self; } my $mapping = { ggsnNbrOfActivePdpContexts => { oid => '.1.3.6.1.4.1.10923.1.1.1.1.1.3.2' }, ggsnAttemptedActivation => { oid => '.1.3.6.1.4.1.10923.1.1.1.1.1.3.3.1' }, ggsnAttemptedDeactivation => { oid => '.1.3.6.1.4.1.10923.1.1.1.1.1.3.3.2' }, ggsnAttemptedSelfDeactivation => { oid => '.1.3.6.1.4.1.10923.1.1.1.1.1.3.3.3' }, ggsnAttemptedUpdate => { oid => '.1.3.6.1.4.1.10923.1.1.1.1.1.3.3.4' }, ggsnCompletedActivation => { oid => '.1.3.6.1.4.1.10923.1.1.1.1.1.3.4.1' }, ggsnCompletedDeactivation => { oid => '.1.3.6.1.4.1.10923.1.1.1.1.1.3.4.2' }, ggsnCompletedSelfDeactivation => { oid => '.1.3.6.1.4.1.10923.1.1.1.1.1.3.4.3' }, ggsnCompletedUpdate => { oid => '.1.3.6.1.4.1.10923.1.1.1.1.1.3.4.4' }, ggsnUplinkPackets => { oid => '.1.3.6.1.4.1.10923.1.1.1.1.1.3.11.1' }, ggsnUplinkBytes => { oid => '.1.3.6.1.4.1.10923.1.1.1.1.1.3.11.2' }, ggsnUplinkDrops => { oid => '.1.3.6.1.4.1.10923.1.1.1.1.1.3.11.3' }, ggsnDownlinkPackets => { oid => '.1.3.6.1.4.1.10923.1.1.1.1.1.3.12.1' }, ggsnDownlinkBytes => { oid => '.1.3.6.1.4.1.10923.1.1.1.1.1.3.12.2' }, ggsnDownlinkDrops => { oid => '.1.3.6.1.4.1.10923.1.1.1.1.1.3.12.3' }, }; sub manage_selection { my ($self, %options) = @_; if ($options{snmp}->is_snmpv1()) { $self->{output}->add_option_msg(short_msg => "Need to use SNMP v2c or v3."); $self->{output}->option_exit(); } my $oid_ggsnGlobalStats = '.1.3.6.1.4.1.10923.1.1.1.1.1.3'; my $snmp_result = $options{snmp}->get_table( oid => $oid_ggsnGlobalStats, nothing_quit => 1 ); $self->{global} = $options{snmp}->map_instance(mapping => $mapping, results => $snmp_result, instance => '0'); $self->{global}->{ggsnDownlinkBytes} *= 8 if (defined($self->{global}->{ggsnDownlinkBytes})); $self->{global}->{ggsnUplinkBytes} *= 8 if (defined($self->{global}->{ggsnUplinkBytes})); $self->{cache_name} = "juniper_ggsn_" . $options{snmp}->get_hostname() . '_' . $options{snmp}->get_port() . '_' . $self->{mode} . '_' . (defined($self->{option_results}->{filter_counters}) ? md5_hex($self->{option_results}->{filter_counters}) : md5_hex('all')); } 1; __END__ =head1 MODE Check global statistics. =over 8 =item B<--warning-*> Threshold warning. Can be: 'traffic-in' (bps), 'traffic-out' (bps), 'drop-in' (%), 'drop-out' (%), 'active-pdp', 'attempted-activation-pdp', 'attempted-update-pdp', 'attempted-deactivation-pdp', 'attempted-self-deactivation-pdp', 'completed-activation-pdp', 'completed-update-pdp', 'completed-deactivation-pdp', 'completed-self-deactivation-pdp'. =item B<--critical-*> Threshold critical. Can be: 'traffic-in' (bps), 'traffic-out' (bps), 'drop-in' (%), 'drop-out' (%), 'active-pdp', 'attempted-activation-pdp', 'attempted-update-pdp', 'attempted-deactivation-pdp', 'attempted-self-deactivation-pdp', 'completed-activation-pdp', 'completed-update-pdp', 'completed-deactivation-pdp', 'completed-self-deactivation-pdp'. =back =cut
Tpo76/centreon-plugins
network/juniper/ggsn/mode/globalstats.pm
Perl
apache-2.0
11,784
package Paws::RDS::DescribeDBClusterParameterGroups; use Moose; has DBClusterParameterGroupName => (is => 'ro', isa => 'Str'); has Filters => (is => 'ro', isa => 'ArrayRef[Paws::RDS::Filter]'); has Marker => (is => 'ro', isa => 'Str'); has MaxRecords => (is => 'ro', isa => 'Int'); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'DescribeDBClusterParameterGroups'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::RDS::DBClusterParameterGroupsMessage'); class_has _result_key => (isa => 'Str', is => 'ro', default => 'DescribeDBClusterParameterGroupsResult'); 1; ### main pod documentation begin ### =head1 NAME Paws::RDS::DescribeDBClusterParameterGroups - Arguments for method DescribeDBClusterParameterGroups on Paws::RDS =head1 DESCRIPTION This class represents the parameters used for calling the method DescribeDBClusterParameterGroups on the Amazon Relational Database Service service. Use the attributes of this class as arguments to method DescribeDBClusterParameterGroups. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to DescribeDBClusterParameterGroups. As an example: $service_obj->DescribeDBClusterParameterGroups(Att1 => $value1, Att2 => $value2, ...); Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object. =head1 ATTRIBUTES =head2 DBClusterParameterGroupName => Str The name of a specific DB cluster parameter group to return details for. Constraints: =over =item * Must be 1 to 255 alphanumeric characters =item * First character must be a letter =item * Cannot end with a hyphen or contain two consecutive hyphens =back =head2 Filters => ArrayRef[L<Paws::RDS::Filter>] This parameter is not currently supported. =head2 Marker => Str An optional pagination token provided by a previous C<DescribeDBClusterParameterGroups> request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by C<MaxRecords>. =head2 MaxRecords => Int The maximum number of records to include in the response. If more records exist than the specified C<MaxRecords> value, a pagination token called a marker is included in the response so that the remaining results can be retrieved. Default: 100 Constraints: Minimum 20, maximum 100. =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method DescribeDBClusterParameterGroups in L<Paws::RDS> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/RDS/DescribeDBClusterParameterGroups.pm
Perl
apache-2.0
2,877
=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::Web::ToolsPipeConfig::FileChameleon; ### Provides configs for File Chameleon for tools pipeline use strict; use warnings; use parent qw(EnsEMBL::Web::ToolsPipeConfig); sub logic_name { 'FileChameleon' } sub runnable { 'EnsEMBL::Web::RunnableDB::FileChameleon' } sub queue_name { $SiteDefs::ENSEMBL_FC_QUEUE } sub is_lsf { !$SiteDefs::ENSEMBL_FC_RUN_LOCAL } sub lsf_timeout { $SiteDefs::ENSEMBL_FC_LSF_TIMEOUT } sub memory_usage { $SiteDefs::ENSEMBL_FC_MEMORY_USAGE } sub analysis_capacity { $SiteDefs::ENSEMBL_FC_ANALYSIS_CAPACITY } 1;
muffato/public-plugins
tools_hive/modules/EnsEMBL/Web/ToolsPipeConfig/FileChameleon.pm
Perl
apache-2.0
1,380
%------------------------------------------------------------------------------ % % Functional goodies % % Martin Dvorak % 1999 %------------------------------------------------------------------------------ /** Module: Text: Aplikace programování vy¹¹ího øádu ze svìta funkcionálního programování. */ %------------------------------------------------------------------------------ % ToDo: %------------------------------------------------------------------------------ /** mapList(+Function, +InputList, -OutputList) Text: Èasto potøebujeme provést se v¹emi prvky seznamu stejnou operaci a z takto získaných výsledkù vytvoøit opìt seznam. Takové zpracování zajistí predikát vy¹¹ího øádu nazvaný mapList. Example: ?- mapList(+(10),[1,5,7],R). R = [10,15,17] Yes */ mapList(Fun,[IH|IT],[OH|OT]):- :-@ [Fun,IH,OH], mapList(Fun,IT,OT). mapList(_,[],[]). %------------------------------------------------------------------------------ /** mapListDL(+Function, -InputList, -OutputDifList) Text: Predikát mapListDL/3 je variantou mapList/3. Li¹í se tím, ¾e vydává výsledek ve formì rozdílového seznamu. Example: ?- mapListDL(square,[1,5,7],R). R = [1,25,49,X]-X Yes */ mapListDL(_,[],D-D). mapListDL(Fun,[IH|IT],[OH|OT]-D):- :-@ [Fun,IH,OH], mapListDL(Fun,IT,OT-D). %------------------------------------------------------------------------------ /** foldL(+Action, +InitVal, +InputList, -OutputList) Text: Predikát vy¹¹ího øádu, který aplikuje danou binární operaci Action s levou asociativitou a její výsledky akumuluje. Example: % foldL(f, 3, [a,b,c], R) % => % f(f(f(3,a),b),c) */ foldL(F,InVal,[I|IT],Out):- :-@ [F,InVal,I,OutVal], foldL(F,OutVal,IT,Out). foldL(_,Out,[],Out). %------------------------------------------------------------------------------ /** foldR(+Action, +InitVal, +InputList, -OutputList) Text: Predikát vy¹¹ího øádu, který aplikuje danou binární operaci Action s pravou asociativitou a její výsledky akumuluje. Example: % foldR(f, 3, [a,b,c], R) % => % f(a,f(b,f(c,3))) */ foldR(F,InVal,[I|IT],Out):- foldR(F,InVal,IT,Out_), :-@ [F,I,Out_,Out]. % count value when returning foldR(_,InVal,[],InVal). %------------------------------------------------------------------------------ /** mAppend(+InputList, -OutputList) Text: Predikát "multi append" propojí v¹echny podseznamy daného seznamu. Arg: InputList Seznam seznamù. Example: ?- mAppend([[],[1,2],[3]],L). L = [1,2,3] Yes */ mAppend([],[]). mAppend(In,Out):- foldL( append, [], In, Out ). %------------------------------------------------------------------------------ /** mapFilter(+Function, +InputList, -OutputList) Text: Varianta predikátu mapList/3, která ignoruje selhání predikátu Function. Arg: Function Operace aplikovaná na polo¾ky seznamu InputList. Example: ?- mapFilter(inc(1),[1,a,v,c,5],L). L = [2,6] Yes */ mapFilter(_,[],[]). mapFilter(Fun,[IH|IT],Output):- ( :-@ [Fun,IH,OH], Output=[OH|OT] ; Output=OT ), mapFilter(Fun,IT,OT). %------------------------------------------------------------------------------ /** nonMapFilter(+Function, +InputList, -OutputList) Text: Varianta predikátu mapList/3, která ulo¾í do seznamu OutputList pouze ty prvky InputList na kterých predikát Function selhal. Arg: Function Operace aplikovaná na polo¾ky seznamu InputList. Example: ?- nonMapFilter(dec,[1,a,v,c,5],L). % dec/2 check its args L = [a,v,c] Yes */ nonMapFilter(_,[],[]). nonMapFilter(Fun,[IH|IT],Output):- ( :-@ [Fun,IH,_], Output=OT ; Output=[IH|OT] ), nonMapFilter(Fun,IT,OT). %------------------------------------------------------------------------------ /** filter(+Condition, +InputList, -FilteredList) Text: Ze seznamu InputList jsou odfiltrovány polo¾ky nesplòující podmínku Condition. */ filter(Cond,[IH|IT],Filtered):- (:-@ [Cond,IH] -> Filtered=[IH|OT] ; Filtered=OT), filter(Cond,IT,OT). filter(_,[],[]). %------------------------------------------------------------------------------ /** nonFilter(+Condition, +InputList, -FilteredList) Text: Do seznamu FilteredList jsou ulo¾eny polo¾ky InputList, které nesplòují podmínku Condition. */ nonFilter(Cond,[IH|IT],Filtered):- ( :-@ [ Cond, IH ] -> Filtered=OT ; Filtered=[IH|OT] ), nonFilter(Cond,IT,OT). nonFilter(_,[],[]). %------------------------------------------------------------------------------ /** zip(+Pred, +List1, +List2, +OutList) Text: Predikát zip spojí dva stejnì dlouhé seznamy do jediného tak, ¾e se na stejnolehlé prvky aplikuje zadaná funkce a její hodnota se umís»uje na pøíslu¹né místo ve výsledném seznamu. Jestli¾e mají seznamy rùznou délku, má výsledek velikost krat¹ího z nich. Example: ?- zip(+,[1,2,3],[4,5,6],L). L = [5,7,9] Yes */ zip(Pred,[IH1|IT1],[IH2|IT2],[OH|OT]):- :-@ [Pred,IH1,IH2,OH], zip(Pred,IT1,IT2,OT). zip(_,[],_,[]). zip(_,_,[],[]). %------------------------------------------------------------------------------ /** exists(+Cond, +List) Text: Uspìje, pokud nìkterá z polo¾ek v seznamu splòuje danou podmínku Cond. Example: ?- exists(isOdd,[2,3]). Yes */ exists(_,[]):-fail. exists(Cond,[IH|IT]):- :-@[Cond,IH] -> true ; exists(Cond,IT). %------------------------------------------------------------------------------ /** alls(+Cond, +List) Text: Uspìje, pokud v¹echny polo¾ky v seznamu splòují danou podmínku Cond. Example: ?- alls(isOdd,[1,3]). Yes */ alls(_,[]). alls(Cond,[IH|IT]):- :-@[Cond,IH] -> alls(Cond,IT). %------------------------------------------------------------------------------ /** =->(+Predicate1, +Predicate2, -Result) Text: Zøetìzená aplikace predikátù. Nejdøíve je aplikován Predicate2 a potom Predicate1. Pou¾ití nachází pøedev¹ím v predikátech vy¹¹ího øádu jako fold* èi mapList/3. Example: ?- :-@ [mapList(+) =-> foldR(append,[]),[[0,1],[2]],R]. R= [+(0), +(1), +(2)] Yes */ =->(P1,P2,I,O):- :-@ [P2,I,Ot], :-@ [P1,Ot,O]. %- EOF ------------------------------------------------------------------------
dvorka/parser-combinators
src/prolog/pc/library/fun.pl
Perl
apache-2.0
6,715
# # 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 apps::vmware::connector::mode::datastoreusage; 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; $self->{version} = '1.0'; $options{options}->add_options(arguments => { "datastore-name:s" => { name => 'datastore_name' }, "filter" => { name => 'filter' }, "scope-datacenter:s" => { name => 'scope_datacenter' }, "disconnect-status:s" => { name => 'disconnect_status', default => 'unknown' }, "warning:s" => { name => 'warning', }, "critical:s" => { name => 'critical', }, "warning-provisioned:s" => { name => 'warning_provisioned', }, "critical-provisioned:s" => { name => 'critical_provisioned', }, "units:s" => { name => 'units', default => '%' }, "free" => { name => 'free' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); foreach my $label (('warning', 'critical', 'warning_provisioned', 'critical_provisioned')) { if (($self->{perfdata}->threshold_validate(label => $label, value => $self->{option_results}->{$label})) == 0) { my ($label_opt) = $label; $label_opt =~ tr/_/-/; $self->{output}->add_option_msg(short_msg => "Wrong " . $label_opt . " threshold '" . $self->{option_results}->{$label} . "'."); $self->{output}->option_exit(); } } if ($self->{output}->is_litteral_status(status => $self->{option_results}->{disconnect_status}) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong disconnect-status status option '" . $self->{option_results}->{disconnect_status} . "'."); $self->{output}->option_exit(); } if (!defined($self->{option_results}->{units}) || $self->{option_results}->{units} !~ /^(%|B)$/) { $self->{output}->add_option_msg(short_msg => "Wrong units option '" . $self->{option_results}->{units} . "'."); $self->{output}->option_exit(); } } sub run { my ($self, %options) = @_; $self->{connector} = $options{custom}; $self->{connector}->add_params(params => $self->{option_results}, command => 'datastoreusage'); $self->{connector}->run(); } 1; __END__ =head1 MODE Check datastore usage. =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<--disconnect-status> Status if datastore disconnected (default: 'unknown'). =item B<--warning> Threshold warning (depends units option). =item B<--critical> Threshold critical (depends units option). =item B<--warning-provisioned> Threshold warning for provisioned storage (percent). =item B<--critical-provisioned> Threshold critical for provisioned storage (percent). =item B<--units> Units of thresholds (Default: '%') ('%', 'B'). =item B<--free> Thresholds are on free space left. =back =cut
wilfriedcomte/centreon-plugins
apps/vmware/connector/mode/datastoreusage.pm
Perl
apache-2.0
4,311
# # Copyright 2016 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 storage::hitachi::hnas::snmp::plugin; use strict; use warnings; use base qw(centreon::plugins::script_snmp); sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '1.0'; %{$self->{modes}} = ( 'cluster-status' => 'centreon::common::bluearc::snmp::mode::clusterstatus', 'interfaces' => 'snmp_standard::mode::interfaces', 'list-interfaces' => 'snmp_standard::mode::listinterfaces', 'hardware' => 'centreon::common::bluearc::snmp::mode::hardware', 'volume-usage' => 'centreon::common::bluearc::snmp::mode::volumeusage', ); return $self; } 1; __END__ =head1 PLUGIN DESCRIPTION Check Hitachi HNAS in SNMP. =cut
bcournaud/centreon-plugins
storage/hitachi/hnas/snmp/plugin.pm
Perl
apache-2.0
1,666
# # Ensembl module for Bio::EnsEMBL::Funcgen::DBSQL::ProbeSetAdaptor # =head1 LICENSE Copyright (c) 1999-2011 The European Bioinformatics Institute and Genome Research Limited. All rights reserved. This software is distributed under a modified Apache license. For license details, please see http://www.ensembl.org/info/about/code_licence.html =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <ensembl-dev@ebi.ac.uk>. Questions may also be sent to the Ensembl help desk at <helpdesk@ensembl.org>. =head1 NAME Bio::EnsEMBL::DBSQL::ProbeSetAdaptor - A database adaptor for fetching and storing ProbeSet objects. =head1 SYNOPSIS use Bio::EnsEMBL::Registry; use Bio::EnsEMBL::Funcgen::ProbeSet; my $reg = Bio::EnsEMBL::Registry->load_adaptors_from_db(-host => 'ensembldb.ensembl.org', -user => 'anonymous'); my $pset_a = Bio::EnsEMBL::Resgitry->get_adpator($species, 'funcgen', 'ProbeSet'); #Fetching a probeset by name my $probeset = $pset_a->fetch_by_array_probeset_name('Array-1', 'ProbeSet-1'); ### Fetching probeset with transcript annotations ### # Generated by the Ensembl array mapping pipeline my @probesets = @{$pset_a->fetch_all_by_linked_Transcript($transcript)}; #Note: Associated linkage annotation is stored in the associated DBEntries =head1 DESCRIPTION The ProbeSetAdaptor is a database adaptor for storing and retrieving ProbeSet objects. =head1 SEE ALSO Bio::EnsEMBL::Funcgen::ProbeSet ensembl-functgenomics/scripts/examples/microarray_annotation_example.pl Or for details on how to run the array mapping pipeline see: ensembl-functgenomics/docs/array_mapping.txt =cut use strict; use warnings; package Bio::EnsEMBL::Funcgen::DBSQL::ProbeSetAdaptor; use Bio::EnsEMBL::Utils::Exception qw( throw warning ); use Bio::EnsEMBL::Funcgen::ProbeSet; use Bio::EnsEMBL::Funcgen::DBSQL::BaseAdaptor; use vars qw(@ISA); @ISA = qw(Bio::EnsEMBL::Funcgen::DBSQL::BaseAdaptor); #Exported from BaseAdaptor $true_tables{probe_set} = [['probe_set', 'ps']]; @{$tables{probe_set}} = @{$true_tables{probe_set}}; =head2 fetch_by_array_probeset_name Arg [1] : string - name of array Arg [2] : string - name of probeset Example : my $probeset = $opsa->fetch_by_array_probeset_name('Array-1', 'Probeset-1'); Description: Returns a probeset given the array name and probeset name This will uniquely define a probeset. Only one probeset is ever returned. Returntype : Bio::EnsEMBL::ProbeSet Exceptions : None Caller : General Status : At Risk =cut sub fetch_by_array_probeset_name{ my ($self, $array_name, $probeset_name) = @_; if(! ($array_name && $probeset_name)){ throw('Must provide array_name and probeset_name arguments'); } #Extend query tables push @{$tables{probe_set}}, (['probe', 'p'], ['array_chip', 'ac'], ['array', 'a']); #Extend query and group #This needs generic_fetch_bind_param my $constraint = 'ps.name= ? AND ps.probe_set_id=p.probe_set_id AND p.array_chip_id=ac.array_chip_id AND ac.array_id=a.array_id AND a.name= ? GROUP by ps.probe_set_id'; #my $constraint = 'ps.name="'.$probeset_name.'" and ps.probe_set_id=p.probe_set_id and p.array_chip_id=ac.array_chip_id and ac.array_id=a.array_id and a.name="'.$array_name.'" group by ps.probe_set_id'; $self->bind_param_generic_fetch($probeset_name,SQL_VARCHAR); $self->bind_param_generic_fetch($array_name,SQL_VARCHAR); my $pset = $self->generic_fetch($constraint)->[0]; #Reset tables @{$tables{probe_set}} = @{$true_tables{probe_set}}; return $pset; } =head2 fetch_all_by_name Arg [1] : string - probe set name Example : my @probes = @{$pdaa->fetch_all_by_name('ProbeSet1')}; Description: Convenience method to re-instate the functionality of $core_dbentry_adpator->fetch_all_by_external_name('probeset_name'); WARNING: This may not be the probeset you are expecting as probeset names are not unqiue across arrays and vendors. These should ideally be validated using the attached array information or alternatively use fetch_by_array_probeset_name Returns a probe with the given name. Returntype : Arrayref Exceptions : Throws if name not passed Caller : General Status : At Risk =cut sub fetch_all_by_name{ my ($self, $name) = @_; throw('Must provide a probeset name argument') if ! defined $name; $self->bind_param_generic_fetch($name, SQL_VARCHAR); return $self->generic_fetch('ps.name=?'); } =head2 fetch_by_ProbeFeature Arg [1] : Bio::EnsEMBL::ProbeFeature Example : my $probeset = $opsa->fetch_by_ProbeFeature($feature); Description: Returns the probeset that created a particular feature. Returntype : Bio::EnsEMBL::ProbeSet Exceptions : Throws if argument is not a Bio::EnsEMBL::ProbeFeature object Caller : General Status : At Risk =cut #This is a good candidate for complex query extension #As we will most likely want the probe also if we are fetching the ProbeSet #For a given feature. #We could also set the probe in the ProbeFeature object, so we don't re-query #should the user use ProbeFeature->get_probe #This is also a case for passing the array name to automatically set #the probe name? As we will likely know the array name beforehand. #Could we also bring back annotations for this Probe/ProbeSet? # sub fetch_by_ProbeFeature { my ($self, $pfeature) = @_; $self->db->is_stored_and_valid('Bio::EnsEMBL::Funcgen::ProbeFeature', $pfeature); #Extend query tables push @{$tables{probe_set}}, (['probe', 'p']); #Extend query and group my $pset = $self->generic_fetch('p.probe_id='.$pfeature->probe_id.' and p.probe_set_id=ps.probe_set_id GROUP by ps.probe_set_id')->[0]; #Reset tables @{$tables{probe_set}} = @{$true_tables{probe_set}}; return $pset; } =head2 fetch_all_by_Array Arg [1] : Bio::EnsEMBL::Funcgen::Array Example : my @probesets = @{$pset_adaptor->fetch_all_by_Array($array)}; Description: Fetch all ProbeSets on a particular array. Returntype : Listref of Bio::EnsEMBL::ProbeSet objects. Exceptions : throws if arg is not valid or stored Caller : General Status : At Risk =cut sub fetch_all_by_Array { my $self = shift; my $array = shift; if(! (ref($array) && $array->isa('Bio::EnsEMBL::Funcgen::Array') && $array->dbID())){ throw('Need to pass a valid stored Bio::EnsEMBL::Funcgen::Array'); } #get all array_chip_ids, for array and do a subselect statement with generic fetch my $constraint = ( " ps.probe_set_id in" ." ( SELECT distinct(p.probe_set_id)" ." from probe p where" ." p.array_chip_id IN (".join(",", @{$array->get_array_chip_ids()}).")" ." )" ); return $self->generic_fetch($constraint); } =head2 _tables Args : None Example : None Description: PROTECTED implementation of superclass abstract method. Returns the names and aliases of the tables to use for queries. Returntype : List of listrefs of strings Exceptions : None Caller : Internal Status : At Risk =cut sub _tables { my $self = shift; return @{$tables{probe_set}}; } =head2 _columns Args : None Example : None Description: PROTECTED implementation of superclass abstract method. Returns a list of columns to use for queries. Returntype : List of strings Exceptions : None Caller : Internal Status : At Risk =cut sub _columns { my $self = shift; #remove xref_id and use xref tables return qw( ps.probe_set_id ps.name ps.size ps.family); } =head2 _objs_from_sth Arg [1] : DBI statement handle object Example : None Description: PROTECTED implementation of superclass abstract method. Creates ProbeSet objects from an executed DBI statement handle. Returntype : Listref of Bio::EnsEMBL::ProbeSet objects Exceptions : None Caller : Internal Status : At Risk =cut sub _objs_from_sth { my ($self, $sth) = @_; my (@result, $current_dbid, $probeset_id, $name, $size, $family); my ($array, %array_cache); $sth->bind_columns( \$probeset_id, \$name, \$size, \$family); #do not have array_chip adaptor #use array adaptor directly #how are we going ot handle the cache here????? my $probeset; while ( $sth->fetch() ) { #$array = $array_cache{$array_id} || $self->db->get_ArrayAdaptor()->fetch_by_dbID($array_id); #This is nesting array object in probeset! #$array = $array_cache{$arraychip_id} || $self->db->get_ArrayAdaptor()->fetch_by_array_chip_dbID($arraychip_id); #Is this required? or should we lazy load this? #Should we also do the same for probe i.e. nest or lazy load probeset #Setting here prevents, multiple queries, but if we store the array cache in the adaptor we can overcome this #danger of eating memory here, but it's onld the same as would be used for generating all the probesets #what about clearing the cache? #also as multiple array_chips map to same array, cache would be redundant #need to store only once and reference. #have array_cache and arraychip_map #arraychip_map would give array_id which would be key in array cache #This is kinda reinventing the wheel, but reducing queries and redundancy of global cache #cache would never be populated if method not called #there for reducing calls and memory, increasing speed of generation/initation #if method were called #would slightly slow down processing, and would slightly increase memory as cache(small as non-redundant) #and map hashes would persist #Do we even need this???? #warn("Can we lazy load the arrays from a global cache, which is itself lazy loaded and non-redundant?\n"); #this current id stuff is due to lack of probeset table in core #if (!$current_dbid || $current_dbid != $probeset_id) { # New probeset $probeset = Bio::EnsEMBL::Funcgen::ProbeSet->new ( -dbID => $probeset_id, -name => $name, -size => $size, # -array => $array, -family => $family, -adaptor => $self, ); push @result, $probeset; #$current_dbid = $probeset_id; #} else { # # Extend existing probe # $probe->add_Array_probename($array, $name); #} } return \@result; } =head2 store Arg [1] : List of Bio::EnsEMBL::Funcgen::ProbeSet objects Example : $opa->store($probeset1, $probeset2, $probeset3); Description: Stores given ProbeSet objects in the database. Should only be called once per probe because no checks are made for duplicates.??? It certainly looks like there is :/ Sets dbID and adaptor on the objects that it stores. Returntype : None Exceptions : Throws if arguments are not Probe objects Caller : General Status : At Risk =cut sub store { my ($self, @probesets) = @_; my ($sth, $array); if (scalar @probesets == 0) { throw('Must call store with a list of Probe objects'); } my $db = $self->db(); PROBESET: foreach my $probeset (@probesets) { if ( !ref $probeset || !$probeset->isa('Bio::EnsEMBL::Funcgen::ProbeSet') ) { throw('ProbeSet must be an ProbeSet object'); } if ( $probeset->is_stored($db) ) { warning('ProbeSet [' . $probeset->dbID() . '] is already stored in the database'); next PROBESET; } $sth = $self->prepare(" INSERT INTO probe_set (name, size, family) VALUES (?, ?, ?) "); $sth->bind_param(1, $probeset->name(), SQL_VARCHAR); $sth->bind_param(2, $probeset->size(), SQL_INTEGER); $sth->bind_param(3, $probeset->family(), SQL_VARCHAR); $sth->execute(); my $dbID = $sth->{'mysql_insertid'}; $probeset->dbID($dbID); $probeset->adaptor($self); } return \@probesets; } 1;
adamsardar/perl-libs-custom
EnsemblAPI/ensembl-functgenomics/modules/Bio/EnsEMBL/Funcgen/DBSQL/ProbeSetAdaptor.pm
Perl
apache-2.0
11,992
#!/usr/bin/perl # # 10:39 2008/10/4 # Jonathan Tsai # Ver 1.00 # # auto dns file and restart dns server # # 1.00 (2008/10/4) First release version $g_prgname = substr($0, rindex($0,"/")+1); $g_ver = "1.00 (2008/10/4)"; $p_config = !defined($ARGV[0])?"/opt/trysrvtool/upddnsfile.conf":$ARGV[0]; @arr_config=(); if (-e $p_config) { @tmp_config = split(/\n/, `/bin/cat $p_config | /bin/grep -v "#"`); foreach $v_config (@tmp_config) { $v_config =~ s/ |\r//g; if (length($v_config)>0) { push @arr_config, $v_config; } } } if (@arr_config==0) { exit; } $idx=0; $isModify=0; foreach $v_info (@arr_config) { $idx++; $v_result = runupd($v_info); if (length($v_result)>0) { print($v_result); $isModify++; } } if ($isModify>0) { # restart DNS $msg = `service named restart`; print("----\n[$msg]----\n"); } exit; sub runupd { local($p_config) = @_; local($v_dns_config_file, $v_record_name, $v_get_ip_url); local($v_getIP, $v_msg); ($v_dns_config_file, $v_record_name, $v_get_ip_url) = split(/\t| /, $p_config); $v_getIP = `/usr/bin/curl -s "$v_get_ip_url"`; if (length($v_getIP)<7 ||length($v_getIP)>15) { print("Error:get IP($v_getIP) is wrong!\n"); return; } if (!-e $v_dns_config_file) { print("Error:DNS config file($v_dns_config_file) is not exist!\n"); return; } $v_dns_config_data = `/bin/cat $v_dns_config_file`; $v_dns_config_edit = ""; $v_time_flag = 0; $v_nowdatetime = the_datetime(time); foreach $v_dns_line (split(/\n/, $v_dns_config_data)) { $v_trim_line = $v_dns_line; $v_trim_line =~ s/ |\t//g; if ($v_time_flag==1) { $v_dns_config_edit .= "\t\t\t\t$v_nowdatetime\t\t; serial (d. adams)\n"; $v_time_flag=0; } elsif (index($v_dns_line, "SOA")>0){ $v_dns_config_edit .= $v_dns_line."\n"; $v_time_flag=1; } elsif (substr($v_dns_line,0,length($v_record_name)+1) eq $v_record_name."\t") { $v_nowIP = (split(/\t/,$v_dns_line))[4]; if ($v_nowIP ne $v_getIP) { $v_dns_config_edit .= "$v_record_name\t\tIN\tA\t$v_getIP\t; Auto modified on $v_nowdatetime\n"; $v_msg="$v_record_name:[$v_nowIP]->[$v_getIP]\n"; } } elsif (length($v_trim_line)>0) { $v_dns_config_edit .= $v_dns_line."\n"; } } if (length($v_msg)>0) { #print("-----\n$v_dns_config_edit-----\n"); open(FILE, ">$v_dns_config_file"); print FILE $v_dns_config_edit; close(FILE); } return($v_msg); } sub the_datetime { local($p_sec_vaule) = @_; local(@t_datetime, $i); @t_datetime = localtime($p_sec_vaule); $t_datetime[4] ++; $t_datetime[5] += 1900; for($i=0; $i<6; $i++) { if (length($t_datetime[$i]) == 1) { $t_datetime[$i] = "0".$t_datetime[$i]; } } return($t_datetime[5].$t_datetime[4].$t_datetime[3].$t_datetime[2].$t_datetime[1]); }
tryweb/trysrvtool
upddnsfile.pl
Perl
apache-2.0
2,746
package DDG::Goodie::LoremIpsum; # ABSTRACT: generates random latin use strict; use warnings; use DDG::Goodie; use utf8; use Text::Lorem::More; use Lingua::EN::Numericalize; triggers any => 'lorem ipsum', 'lipsum', 'latin'; zci is_cached => 0; zci answer_type => 'lorem_ipsum'; sub pluralise { my ($amount, $to_pluralise) = @_; return $amount == 1 ? $to_pluralise : ($to_pluralise . 's'); } my $types = qr/(?<type>word|sentence|paragraph)/i; my $modifier_re = qr/(?<modifier>random|regular)/i; my $amountre = qr/(?<amount>\d+)/; my $lorem_re = qr/(?:latin|l(?:orem )?ipsum)/i; my $forms = qr/^(?: (((?<amount>\d+)\s)?($types)s?\sof((?!$modifier_re).)*(?<modifier>$modifier_re)?+.*($lorem_re)) |((?<amount>\d+)\s(?<modifier>$modifier_re)?\s*($lorem_re)\s($types)s?) )$/xi; # Generates a string containing all the nonsense words/sentences. sub generate_latin { my ($amount, $modifier, $type) = @_; my $word = Text::Lorem::More->new(); my $words; if ($type eq 'sentence') { $words = $word->sentences($amount); } elsif ($type eq 'word') { $words = $word->words($amount); } elsif ($type eq 'paragraph') { $words = $word->paragraphs($amount); }; return $words; } sub get_result_and_formatted { my $query = shift; # Treat 'a' as 'one' for the purposes of amounts. $query =~ s/^a /one /i; $query =~ s/line/sentence/g; # Convert initial words into numbers if possible. my $formatted = $query =~ s/^\w+[a-rt-z](?=\b)/str2nbr($&)/ier; return unless $formatted =~ $forms; my $amount = $+{'amount'} // 1; my $modifier = $+{'modifier'} // 'regular'; my $type = $+{'type'}; my $result = generate_latin($amount, $modifier, $type); # Proper-case modifier (latin -> Latin) my $fmodifier = $modifier =~ s/^\w/\u$&/r; # E.g, "3 words of lorem ipsum" my $formatted_input = "$amount @{[pluralise $amount, $type]} of Lorem Ipsum"; return ($result, $formatted_input); } sub build_infobox_element { my $query = shift; my @split = split ' ', $query; return { label => $query, url => 'https://duckduckgo.com/?q=' . (join '+', @split) . '&ia=answer', }; } my $infobox = [ { heading => "Example Queries", }, build_infobox_element('5 sentences of lorem ipsum'), build_infobox_element('20 words of random latin'), build_infobox_element('10 paragraphs of lorem ipsum'), ]; handle query_lc => sub { my $query = $_; my $default = "5 paragraphs of lorem ipsum" if $query =~ /^\s*l(orem )?ipsum\s*$/; my ($result, $formatted_input) = get_result_and_formatted($default // $query) or return; my @paragraphs = split "\n\n", $result; return $result, structured_answer => { id => 'lorem_ipsum', name => 'Answer', data => { title => "$formatted_input", lorem_paragraphs => \@paragraphs, use_paragraphs => $#paragraphs ? 1 : 0, infoboxData => $default ? $infobox : 0, }, meta => { sourceName => "Lipsum", sourceUrl => "http://lipsum.com/" }, templates => { group => 'info', options => { moreAt => 1, content => 'DDH.lorem_ipsum.content', chompContent => 1, } } }; }; 1;
mohan08p/zeroclickinfo-goodies
lib/DDG/Goodie/LoremIpsum.pm
Perl
apache-2.0
3,476
package Oneliners::Controller::Root; use Moose; use Oneliners::Form::Oneliner; use namespace::autoclean; BEGIN { extends 'Catalyst::Controller' } __PACKAGE__->config(namespace => ''); sub oneliners_form { my ($self, $c) = @_; my $form = Oneliners::Form::Oneliner->new; my $oneliners = $c->model('Oneliners')->new; $oneliners->items([]); $oneliners->deserialize; $c->stash(template => 'index.ttkt.html', form => $form, items => $oneliners->items); $form->process(params => $c->req->params ); return unless $form->validated(); my $oneliner = $c->model('Oneliner')->new($c->req->params); push @{$oneliners->items}, $oneliner; $oneliners->serialize; $c->response->redirect($c->uri_for($self->action_for('posted'))); } sub posted :Local :Args(0) { my ($self, $c) = @_; $c->stash(template => 'posted.ttkt.html'); } sub index :Path :Args(0) { my ( $self, $c ) = @_; $self->oneliners_form($c); } sub default :Path { my ( $self, $c ) = @_; $c->response->body( 'Page not found' ); $c->response->status(404); } sub end : ActionClass('RenderView') {} __PACKAGE__->meta->make_immutable; 1;
jmcveigh/komodo-tools
templates/Perl/Catalyst/Ufimisms/Oneliners/Controller/Root.pm
Perl
bsd-2-clause
1,210
package Log::FreeSWITCH::Line::Data; # Pragmas. use strict; use warnings; # Modules. use English; use Error::Pure::Always; use Error::Pure qw(err); use Mo qw(builder is required); # Version. our $VERSION = 0.02; has date => ( 'is' => 'ro', 'required' => 1, ); has datetime_obj => ( 'is' => 'ro', 'builder' => '_datetime', ); has file => ( 'is' => 'ro', 'required' => 1, ); has file_line => ( 'is' => 'ro', 'required' => 1, ); has message => ( 'is' => 'ro', ); has raw => ( 'is' => 'rw', ); has time => ( 'is' => 'ro', 'required' => 1, ); has type => ( 'is' => 'ro', 'required' => 1, ); # Create DateTime object. sub _datetime { my $self = shift; eval { require DateTime; }; if ($EVAL_ERROR) { err "Cannot load 'DateTime' class.", 'Error', $EVAL_ERROR; } my ($year, $month, $day) = split m/-/ms, $self->date; my ($hour, $min, $sec_mili) = split m/:/ms, $self->time; my ($sec, $mili) = split m/\./ms, $sec_mili; if (! defined $mili) { $mili = 0; } my $dt = eval { DateTime->new( 'year' => $year, 'month' => $month, 'day' => $day, 'hour' => $hour, 'minute' => $min, 'second' => $sec, 'nanosecond' => $mili * 1000, ); }; if ($EVAL_ERROR) { err 'Cannot create DateTime object.', 'Error', $EVAL_ERROR; } return $dt; } 1; __END__ =pod =encoding utf8 =head1 NAME Log::FreeSWITCH::Line::Data - Data object which represents FreeSWITCH log line. =head1 SYNOPSIS use Log::FreeSWITCH::Line::Data; my $obj = Log::FreeSWITCH::Line::Data->new(%params); my $date = $obj->date; my $datetime_o = $obj->datetime_obj; my $file = $obj->file; my $file_line = $obj->file_line; my $message = $obj->message; my $raw = $obj->raw($raw); my $time = $obj->time; my $type = $obj->type; =head1 METHODS =over 8 =item C<new(%params)> Constructor. =over 8 =item * C<date> Date of log entry. Format of date is 'YYYY-MM-DD'. It is required. =item * C<file> File in log entry. It is required. =item * C<file_line> File line in log entry. It is required. =item * C<message> Log message. =item * C<raw> Raw FreeSWITCH log entry. =item * C<time> Time of log entry. Format of time is 'HH:MM:SS'. It is required. =item * C<type> Type of log entry. It is required. =back =item C<date()> Get log entry date. Returns string with date in 'YYYY-MM-DD' format. =item C<datetime_obj()> Get DateTime object. Returns DateTime object. =item C<file()> Get file in log entry. Returns string. =item C<file_line()> Get file line in log entry. Returns string. =item C<message()> Get log message. Returns string. =item C<raw($raw)> Get or set raw FreeSWITCH log entry. Returns string. =item C<time()> Get log entry time. Returns string with time in 'HH:MM:SS' format. =item C<type()> Get log entry type. Returns string. =back =head1 ERRORS new(): date required file required file_line required time required type required datetime_obj(): Cannot create DateTime object. Error: %s Cannot load 'DateTime' class. Error: %s =head1 EXAMPLE # Pragmas. use strict; use warnings; # Module. use Log::FreeSWITCH::Line::Data; # Object. my $data_o = Log::FreeSWITCH::Line::Data->new( 'date' => '2014-07-01', 'file' => 'sofia.c', 'file_line' => 4045, 'message' => 'inbound-codec-prefs [PCMA]', 'time' => '13:37:53.973562', 'type' => 'DEBUG', ); # Print out informations. print 'Date: '.$data_o->date."\n"; # Output: # Date: 2014-07-01 =head1 DEPENDENCIES L<DateTime>, L<English>, L<Error::Pure::Always>, L<Error::Pure>, L<Mo>. =head1 SEE ALSO L<Log::FreeSWITCH::Line::Data>. =head1 REPOSITORY L<https://github.com/tupinek/Log-FreeSWITCH-Line> =head1 AUTHOR Michal Špaček L<mailto:skim@cpan.org> L<http://skim.cz> =head1 LICENSE AND COPYRIGHT © 2014-2015 Michal Špaček BSD 2-Clause License =head1 VERSION 0.02 =cut
gitpan/Log-FreeSWITCH-Line
Line/Data.pm
Perl
bsd-2-clause
3,995
package CoGe::Builder::Methylation::Metaplot; use v5.14; use strict; use warnings; use Data::Dumper qw(Dumper); use File::Spec::Functions qw(catfile); use CoGe::Accessory::Web qw(get_defaults); use CoGe::Core::Storage qw(get_workflow_paths); use CoGe::Builder::CommonTasks qw(create_gff_generation_job add_metadata_to_results_job); our $CONF = CoGe::Accessory::Web::get_defaults(); BEGIN { use vars qw ($VERSION @ISA @EXPORT @EXPORT_OK); require Exporter; $VERSION = 0.1; @ISA = qw(Exporter); @EXPORT = qw(build); } sub build { my $opts = shift; my $genome = $opts->{genome}; my $user = $opts->{user}; my $bam_file = $opts->{bam_file}; # path to sorted & indexed bam file my $experiment_id = $opts->{experiment_id}; # for when called from ExperimentView # my $metadata = $opts->{metadata}; # my $additional_metadata = $opts->{additional_metadata}; my $wid = $opts->{wid}; my $methylation_params = $opts->{methylation_params}; my $metaplot_params = $methylation_params->{metaplot_params}; unless ($genome && $user && $bam_file && $wid && $methylation_params && $metaplot_params) { print STDERR " CoGe::Builder::Methylation::Metaplot ERROR, missing inputs: ", ($genome ? '' : ' genome '), ($user ? '' : ' user '), ($bam_file ? '' : ' bam_file '), ($wid ? '' : ' wid '), ($methylation_params ? '' : ' methylation_params '), ($metaplot_params ? '' : ' metaplot_params '), "\n"; return; } # Setup paths my ($staging_dir, $result_dir) = get_workflow_paths($user->name, $wid); # Make sure genome is annotated as is required by metaplot script my $isAnnotated = $genome->has_gene_features; unless ($isAnnotated) { print STDERR "CoGe::Builder::Methylation::Metaplot ERROR, genome must be annotated to generate metaplot\n"; return; } # # Build the workflow # my (@tasks, @done_files); # Generate cached gff my $gff_task = create_gff_generation_job( gid => $genome->id, organism_name => $genome->organism->name ); my $gff_file = $gff_task->{outputs}->[0]; push @tasks, $gff_task; # Generate metaplot my $metaplot_task = create_metaplot_job( bam_file => $bam_file, gff_file => $gff_file, outer => $metaplot_params->{outer}, inner => $metaplot_params->{inner}, window_size => $metaplot_params->{window}, feat_type => 'gene', staging_dir => $staging_dir ); push @done_files, @{$metaplot_task->{outputs}}; push @tasks, $metaplot_task; # Add metadata my $annotations = generate_additional_metadata($metaplot_params, $metaplot_task->{outputs}[1]); my $metadata_task = add_metadata_to_results_job( user => $user, wid => $wid, annotations => $annotations, staging_dir => $staging_dir, done_files => \@done_files, item_id => $experiment_id, item_type => 'experiment', locked => 0 ); push @tasks, $metadata_task; return { tasks => \@tasks, done_files => \@done_files }; } sub generate_additional_metadata { my $metaplot_params = shift; my $metaplot_image_path = shift; my @annotations; push @annotations, "$metaplot_image_path|||metaplot|parameters: " . join(' ', map { $_.' '.$metaplot_params->{$_} } ('outer', 'inner', 'window')); return \@annotations; } sub create_metaplot_job { my %opts = @_; my $bam_file = $opts{bam_file}; my $gff_file = $opts{gff_file}; my $outer = $opts{outer} // 2000; my $inner = $opts{inner} // 5000; my $window_size = $opts{window} // 100; my $feat_type = $opts{feat_type}; my $staging_dir = $opts{staging_dir}; my $cmd = catfile($CONF->{SCRIPTDIR}, 'methylation', 'makeMetaplot.pl'); $cmd = 'nice ' . $cmd; my $output_name = 'metaplot'; return { cmd => $cmd, script => undef, args => [ ['-o', $output_name, 0], ['-gff', $gff_file, 0], ['-outside', $outer, 0], ['-inside', $inner, 0], ['-w', $window_size, 0], ['-outRange', '', 0], ['-featType', $feat_type, 0], ['-cpu', 8, 0], ['-quiet', '', 0], # disable frequent printing of feature ID ['-bam', $bam_file, 0] ], inputs => [ $bam_file, $bam_file . '.bai', $gff_file ], outputs => [ catfile($staging_dir, "$output_name.tab"), catfile($staging_dir, "$output_name.png") ], description => "Generating metaplot" }; } 1;
asherkhb/coge
modules/Pipelines/lib/CoGe/Builder/Methylation/Metaplot.pm
Perl
bsd-2-clause
4,806
package Dicom::File::Detect; # Pragmas. use base qw(Exporter); use strict; use warnings; # Modules. use Error::Pure qw(err); use Readonly; # Constants. Readonly::Array our @EXPORT => qw(dicom_detect_file); Readonly::Scalar our $DCM_MAGIC => qw{DICM}; # Version. our $VERSION = 0.04; # Detect DICOM file. sub dicom_detect_file { my $file = shift; my $dcm_flag = 0; open my $fh, '<', $file or err "Cannot open file '$file'."; my $seek = seek $fh, 128, 0; my $magic; my $read = read $fh, $magic, 4; close $fh or err "Cannot close file '$file'."; if ($magic eq $DCM_MAGIC) { return 1; } else { return 0; } } 1; __END__ =pod =encoding utf8 =head1 NAME Dicom::File::Detect - Detect DICOM file through magic string. =head1 SYNOPSIS use Dicom::File::Detect qw(dicom_detect_file); my $dcm_flag = dicom_detect_file($file); =head1 DESCRIPTION This Perl module detect DICOM file through magic string. DICOM (Digital Imaging and Communications in Medicine) is a standard for handling, storing, printing, and transmitting information in medical imaging. See L<DICOM on Wikipedia|https://en.wikipedia.org/wiki/DICOM>. =head1 SUBROUTINES =over 8 =item C<dicom_detect_file($file)> Detect DICOM file. Returns 1/0. =back =head1 ERRORS dicom_detect_file(): Cannot close file '%s'. Cannot open file '%s'. =head1 EXAMPLE1 # Pragmas. use strict; use warnings; # Modules. use Dicom::File::Detect qw(dicom_detect_file); use File::Temp qw(tempfile); use IO::Barf qw(barf); use MIME::Base64; # Data in base64. my $data = <<'END'; AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAABESUNNCg== END # Temp file. my (undef, $temp_file) = tempfile(); # Save data to file. barf($temp_file, decode_base64($data)); # Check file. my $dcm_flag = dicom_detect_file($temp_file); # Print out. if ($dcm_flag) { print "File '$temp_file' is DICOM file.\n"; } else { print "File '$temp_file' isn't DICOM file.\n"; } # Output like: # File '%s' is DICOM file. =head1 EXAMPLE2 # Pragmas. use strict; use warnings; # Modules. use Dicom::File::Detect qw(dicom_detect_file); # Arguments. if (@ARGV < 1) { print STDERR "Usage: $0 file\n"; exit 1; } my $file = $ARGV[0]; # Check file. my $dcm_flag = dicom_detect_file($file); # Print out. if ($dcm_flag) { print "File '$file' is DICOM file.\n"; } else { print "File '$file' isn't DICOM file.\n"; } # Output: # Usage: dicom-detect-file file =head1 DEPENDENCIES L<Error::Pure>, L<Exporter>, L<Readonly>. =head1 SEE ALSO =over =item L<File::Find::Rule::Dicom> Common rules for searching for DICOM things. =item L<Task::Dicom> Install the Dicom modules. =back =head1 REPOSITORY L<https://github.com/tupinek/Dicom-File-Detect> =head1 AUTHOR Michal Špaček L<mailto:skim@cpan.org> L<http://skim.cz> =head1 LICENSE AND COPYRIGHT © 2014-2015 Michal Špaček BSD 2-Clause License =head1 VERSION 0.04 =cut
tupinek/Dicom-File-Detect
Detect.pm
Perl
bsd-2-clause
3,110
/* $Id$ Part of SWI-Prolog Author: Jan Wielemaker E-mail: wielemak@science.uva.nl WWW: http://www.swi-prolog.org Copyright (C): 2004-2006, University of Amsterdam This program 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. This program 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. 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA As a special exception, if you link this library with other files, compiled with a Free Software compiler, to produce an executable, this library does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. */ :- module(sparql_runtime, [ sparql_true/1, sparql_eval/2 ]). :- use_module(library('semweb/rdf_db')). :- use_module(library(xsdp_types)). :- discontiguous term_expansion/2. :- multifile(op/2). %% sparql_true(+Term) % % Generated from FILTER Term, where Term must be converted to a % boolean as 'Effective Boolean Value'. sparql_true(Term) :- typed_eval(boolean, Term, Result), !, true(Result). true(boolean(true)). %% eval(+Term, -Result) eval(Var, unbound(Var)) :- var(Var), !. % necessary since we have numerics as annotation values for the fuzzy case eval(F, Result) :- float(F), !, atom_number(FA, F), eval_literal(type('http://www.w3.org/2001/XMLSchema#decimal',FA),Result). % necessary since we have numerics as annotation values for the fuzzy case eval(I, Result) :- integer(I), !, atom_number(IA, I), eval_literal(type('http://www.w3.org/2001/XMLSchema#integer',IA), Result). eval(literal(Literal), Result) :- !, eval_literal(Literal, Result). eval(Atom, iri(Atom)) :- atom(Atom), !. eval(Term, Result) :- sparql_op(Term, Types), !, Term =.. [Op|Args0], eval_args(Args0, Types, Args), EvalTerm =.. [Op|Args], op(EvalTerm, Result). eval(function(Term), Result) :- !, ( xsd_cast(Term, Type, Value) -> eval_cast(Type, Value, Result) ; eval_function(Term, Result) ). eval(Term, Term). % Result of sub-eval eval_args([], [], []). eval_args([H0|T0], [Type0|Types], [H|T]) :- ( typed_eval(Type0, H0, H) -> true ; H = boolean(error) ), eval_args(T0, Types, T). %% eval(+Type, +Term, -Result) % % Evaluate Term, converting the resulting argument to Type. typed_eval(no_eval, Term, Term). typed_eval(any, Term, Result) :- eval(Term, Result). typed_eval(simple_literal, Term, Result) :- eval(Term, Result). typed_eval(boolean, Term, Result) :- eval(Term, Result0), effective_boolean_value(Result0, Result). typed_eval(numeric, Term, Result) :- eval(Term, Eval), ( Eval = numeric(_,_) -> Result = Eval ; throw(error(type_error(numeric, Result), _)) ). eval_literal(type(Type, Atom), Value) :- !, eval_typed_literal(Type, Atom, Value). eval_literal(lang(Lang, Atom), lang(Lang, Atom)) :- !. eval_literal(Atom, simple_literal(Atom)) :- atom(Atom), !. eval_typed_literal(Type, Atom, numeric(Type, Value)) :- xsdp_numeric_uri(Type, Generic), !, numeric_literal_value(Generic, Atom, Value). eval_typed_literal(Type, Atom, boolean(Atom)) :- rdf_equal(Type, xsd:boolean), !. eval_typed_literal(Type, Atom, string(Atom)) :- rdf_equal(Type, xsd:string), !. eval_typed_literal(Type, Atom, date_time(Atom)) :- rdf_equal(Type, xsd:dateTime), !. eval_typed_literal(Type, Atom, typed_literal(Type, Atom)). %% numeric_literal_value(+Literal, -Value) is semidet. % % Convert a SPARQL numeric literal into its value for the purpose % of comparison-by-value. % % @tbd Move this into the rdf_db library. There we can achieve % better performance and we can do more efficient % matching. numeric_literal_value(Type, Text, Value) :- rdf_equal(Type, xsd:integer), !, catch(atom_number(Text, Value), _, fail), integer(Value). numeric_literal_value(Type, Text, Value) :- rdf_equal(Type, xsd:decimal), !, catch(atom_number(Text, Value), _, fail). numeric_literal_value(_, Text, Value) :- catch(atom_number(Text, Value), _, fail), !. numeric_literal_value(_, Text, Value) :- catch(rdf_text_to_float(Text, Value), _, fail). rdf_text_to_float(Text, Value) :- atom_codes(Text, Codes), optional_sign(Codes, Rest, Sign), ( Rest = [0'.|_] -> number_codes(NonnegValue, [0'0|Rest]) ; last(Rest, 0'.) -> append(Rest, [0'0], NonnegCodes), number_codes(NonnegCodes, NonnegValue) ), Value is NonnegValue*Sign. optional_sign([0'+|Rest], Rest, 1) :- !. optional_sign([0'-|Rest], Rest, -1) :- !. optional_sign(Rest, Rest, 1). %% op(+Operator, -Result) is semidet. % % @param Operator Term of the format Op(Arg...) where each Arg % is embedded in its type. % @param Result Result-value, embedded in its type. % SPARQL Unary operators op(not(boolean(X)), boolean(Result)) :- not(X, Result). op(+(numeric(Type, X)), numeric(Type, X)). op(-(numeric(Type, X)), numeric(Type, Result)) :- Result is -X. % SPARQL Tests, defined in section 11.4 op(bound(X), boolean(Result)) :- (bound(X) -> Result = true ; Result = false). op(isiri(X), boolean(Result)) :- (isiri(X) -> Result = true ; Result = false). op(isuri(X), boolean(Result)) :- (isiri(X) -> Result = true ; Result = false). op(isblank(X), boolean(Result)) :- (isblank(X) -> Result = true ; Result = false). op(isliteral(X), boolean(Result)) :- (isliteral(X) -> Result = true ; Result = false). % SPARQL Accessors op(str(X), simple_literal(Str)) :- str(X, Str). op(lang(X), simple_literal(Lang)) :- lang(X, Lang). op(datatype(X), Type) :- datatype(X, Type). % SPARQL Binary operators % Logical connectives, defined in section 11.4 op(and(boolean(A), boolean(B)), boolean(Result)) :- sparql_and(A, B, Result). op(or(boolean(A), boolean(B)), boolean(Result)) :- sparql_or(A, B, Result). % XPath Tests op(numeric(_, X) = numeric(_, Y), boolean(Result)) :- (X =:= Y -> Result = true ; Result = false). op(date_time(X) = date_time(Y), boolean(Result)) :- (X == Y -> Result = true ; Result = false). op(numeric(_, X) \= numeric(_, Y), boolean(Result)) :- (X =\= Y -> Result = true ; Result = false). op(date_time(X) \= date_time(Y), boolean(Result)) :- (X \== Y -> Result = true ; Result = false). %< op(numeric(_, X) < numeric(_, Y), boolean(Result)) :- (X < Y -> Result = true ; Result = false). op(simple_literal(X) < simple_literal(Y), boolean(Result)) :- (X @< Y -> Result = true ; Result = false). op(string(X) < string(Y), boolean(Result)) :- (X @< Y -> Result = true ; Result = false). op(date_time(X) < date_time(Y), boolean(Result)) :- (X @< Y -> Result = true ; Result = false). %> op(numeric(_, X) > numeric(_, Y), boolean(Result)) :- (X > Y -> Result = true ; Result = false). op(simple_literal(X) > simple_literal(Y), boolean(Result)) :- (X @> Y -> Result = true ; Result = false). op(string(X) > string(Y), boolean(Result)) :- (X @> Y -> Result = true ; Result = false). op(date_time(X) > date_time(Y), boolean(Result)) :- (X @> Y -> Result = true ; Result = false). %=< op(numeric(_, X) =< numeric(_, Y), boolean(Result)) :- (X =< Y -> Result = true ; Result = false). op(simple_literal(X) =< simple_literal(Y), boolean(Result)) :- (X @=< Y -> Result = true ; Result = false). op(string(X) =< string(Y), boolean(Result)) :- (X @=< Y -> Result = true ; Result = false). op(date_time(X) =< date_time(Y), boolean(Result)) :- (X @=< Y -> Result = true ; Result = false). %>= op(numeric(_, X) >= numeric(_, Y), boolean(Result)) :- (X >= Y -> Result = true ; Result = false). op(simple_literal(X) >= simple_literal(Y), boolean(Result)) :- (X @>= Y -> Result = true ; Result = false). op(string(X) >= string(Y), boolean(Result)) :- (X @>= Y -> Result = true ; Result = false). op(date_time(X) >= date_time(Y), boolean(Result)) :- (X @>= Y -> Result = true ; Result = false). op(numeric(TX, X) * numeric(TY, Y), numeric(Type, Result)) :- Result is X * Y, combine_types(TX, TY, Type). op(numeric(TX, X) / numeric(TY, Y), numeric(Type, Result)) :- Result is X / Y, combine_types_div(TX, TY, Type). op(numeric(TX, X) + numeric(TY, Y), numeric(Type, Result)) :- Result is X + Y, combine_types(TX, TY, Type). op(numeric(TX, X) - numeric(TY, Y), numeric(Type, Result)) :- Result is X - Y, combine_types(TX, TY, Type). % SPARQL Tests, defined in section 11.4 op(X = Y, Result) :- rdf_equal(X, Y, Result). op(X \= Y, boolean(Result)) :- rdf_equal(X, Y, boolean(R0)), not(R0, Result). op(langmatches(simple_literal(Lang), simple_literal(Pat)), boolean(Result)) :- (langmatches(Lang, Pat) -> Result = true ; Result = false). op(regex(simple_literal(Pat), simple_literal(String)), boolean(Result)) :- (regex(Pat, String, '') -> Result = true ; Result = false). op(regex(simple_literal(Pat), simple_literal(String), simple_literal(Flags)), boolean(Result)) :- (regex(Pat, String, Flags) -> Result = true ; Result = false). % % cannot be done here due to the use of the clause predicate to find all the op's % % check for domain specific functions % op(Op, Result) :- % ardf:bb_get(domain, Dom), nonvar(Dom), % catch(Dom:op(Op, Result), _E, false). % Numeric types follows the Xpath definitions of % http://www.w3.org/TR/xpath-functions/#numeric-functions % TBD: %% combine_types_div(+TypeLeft, +TypeRight, -Type) combine_types_div(TX, TY, T) :- rdf_equal(xsd:integer, IntType), xsdp_numeric_uri(TX, IntType), xsdp_numeric_uri(TY, IntType), !, rdf_equal(xsd:decimal, T). combine_types_div(TX, TY, T) :- combine_types(TX, TY, T). %% combine_types(+TypeLeft, +TypeRight, -Type) %combine_types(T, T, T) :- !. combine_types(TL, TR, T) :- xsdp_numeric_uri(TL, STL), xsdp_numeric_uri(TR, STR), promote_types(STL, STR, T). promote_types(TL, TR, T) :- type_index(TL, IL), type_index(TR, IR), TI is max(IL, IR), type_index(T, TI), !. term_expansion(type_index(NS:Local, I), type_index(URI, I)) :- rdf_global_id(NS:Local, URI). type_index(xsd:integer, 1). type_index(xsd:decimal, 2). type_index(xsd:float, 3). type_index(xsd:double, 4). %% rdf_equal(+RDFTerm, +RDFTerm, -Boolean) % % RDF Term equivalence. Described as lexical equivalence, except % where we have the logic to do value equivalence. rdf_equal(X, X, boolean(true)) :- !. rdf_equal(boolean(A), boolean(B), boolean(Eq)) :- !, eq_bool(A, B, Eq). rdf_equal(numeric(_, A), numeric(_, B), boolean(Eq)) :- !, (A =:= B -> Eq = true ; Eq = false). rdf_equal(_, _, boolean(false)). eq_bool(X, X, true) :- !. eq_bool(true, false, false) :- !. eq_bool(false, true, false) :- !. eq_bool(X, Y, true) :- boolean_value(X, V1), boolean_value(Y, V2), V1 == V2, !. eq_bool(_, _, false). %% boolean_value(+Content, -Bool) % % Convert the value from literal(xsd:boolean, Content) into % either 'true' or 'false'. boolean_value(true, true) :- !. boolean_value(false, false) :- !. boolean_value('0', false) :- !. boolean_value('', false) :- !. boolean_value(False, false) :- downcase_atom(False, false), !. boolean_value(_, true). :- dynamic sparql_op/2. % +Term, -Types make_op_declarations :- retractall(sparql_op(_,_)), findall(Head, clause(op(Head, _), _), Heads0), sort(Heads0, Heads), make_op_declarations(Heads). make_op_declarations([]). make_op_declarations([H0|T0]) :- functor(H0, Op, Arity), functor(G, Op, Arity), same_functor(G, T0, T1, T2), make_op_declaration([H0|T1]), make_op_declarations(T2). same_functor(F, [H|T0], [H|T], L) :- \+ \+ F = H, !, same_functor(F, T0, T, L). same_functor(_, L, [], L). make_op_declaration([Op|T]) :- functor(Op, Name, Arity), functor(G, Name, Arity), Op =.. [Name|Args], make_types(Args, 1, T, Types), assert(sparql_op(G, Types)). make_types([], _, _, []). make_types([H0|T0], I, Alt, [H|T]) :- alt_types(Alt, I, AT), list_to_set([H0|AT], Types), make_type(Types, H), I2 is I + 1, make_types(T0, I2, Alt, T). alt_types([], _, []). alt_types([H0|T0], I, [H|T]) :- arg(I, H0, H), alt_types(T0, I, T). make_type([T], no_eval) :- var(T), !. make_type([boolean(_)], boolean) :- !. make_type([numeric(_, _)], numeric) :- !. make_type([simple_literal(_)], simple_literal) :- !. make_type(_, any). :- make_op_declarations. /******************************* * CASTS * *******************************/ %% xsd_cast(+Term, -Type, -Arg) % % Deals with xsd:dateTime(?a), casting ?a to the XML Schema type % dateTime. Supported types are the numeric types, xsd:boolean and % xsd:dateTime. term_expansion(xsd_casts, Clauses) :- findall(Clause, xsd_cast_clause(Clause), Clauses). xsd_cast_clause(xsd_cast(Term, Type, Arg)) :- ( xsdp_numeric_uri(Type, _) ; rdf_equal(xsd:dateTime, Type) ; rdf_equal(xsd:boolean, Type) ), Term =.. [Type,Arg]. xsd_casts. %% eval_cast(+Type, +Value, -Result) % % Case Value to Type, resulting in a typed literal. Can we only % case simple literals? eval_cast(Type, literal(Value), Result) :- atom(Value), !, eval_typed_literal(Type, Value, Result). %% eval_function(+Term, -Result) % % Eval user-defined function. User-defined functions are of the % form sparql:function(Term, Result). eval_function(Term0, Result) :- Term0 =.. [F|Args0], eval_args(Args0, Args), Term =.. [F|Args], sparql:function(Term, Result0), !, eval(Result0, Result). eval_function(Term, boolean(error)) :- functor(Term, Name, Arity), functor(Gen, Name, Arity), clause(sparql:function(Gen, _Result), _Body), !. eval_function(Term, _) :- functor(Term, Name, Arity), throw(error(existence_error(sparql_function, Name/Arity), _)). eval_args([], []). eval_args([H0|T0], [H|T]) :- sparql_eval(H0, H), eval_args(T0, T). /******************************* * SUPPORT PREDICATES * *******************************/ %% not(+Bool, -Negated) not(true, false). not(false, true). %% bound(X) % % Does not evaluate args. If the argument is a function it % is always bound. bound(X) :- nonvar(X). %% str(+RDFTerm, -Atom) % % Extract lexical representation from RDFTerm. str(Var, _) :- var(Var), !, fail. str(literal(X), Str) :- !, str_literal(X, Str). str(IRI, IRI) :- atom(IRI), !, \+ rdf_is_bnode(IRI). str(Expr, Str) :- eval(Expr, Value), str_value(Value, Str). str_value(simple_literal(X), X) :- !. str_value(boolean(X), X) :- !. str_value(string(X), X) :- !. str_value(iri(IRI), IRI) :- !. str_literal(type(_, Str), Str) :- !. str_literal(lang(_, Str), Str) :- !. str_literal(Str, Str). %% lang(+RDFTerm, -Lang) % % Extract language specification from an RDFTerm lang(0, _) :- !, fail. % catch variables. lang(lang(Lang, _), Lang) :- !. lang(literal(lang(Lang, _)), Lang) :- !. lang(literal(_), ''). % Fail on typed? %% datatype(+RDFTerm, -IRI) % % Extract type specification from an RDFTerm datatype(0, _) :- !, fail. datatype(literal(type(Type, _)), iri(Type)) :- !. datatype(numeric(Type, _), iri(Type)) :- !. datatype(boolean(_), iri(Type)) :- !, rdf_equal(xsd:boolean, Type). datatype(Expr, Type) :- eval(Expr, Value), Value \== Expr, datatype(Value, Type). %% sparql_and(+A, +B, -Result) sparql_and(true, true, true) :- !. sparql_and(true, error, error) :- !. sparql_and(error, true, error) :- !. sparql_and(_, _, false). %% sparql_or(+A, +B, -Result) sparql_or(true, _, true) :- !. sparql_or(_, true, true) :- !. sparql_or(false, false, false) :- !. sparql_or(_, _, error). %% langmatches(+Lang, +Pattern) % % Section 11.4.11 function LangMatches. This is slow. Guess we % better move this to the RDF library. Note that none of the % functions return a language qualified literal and we therefore % we only have to consider the case where the argument is a % variable also appearing in the object-field of a rdf/3 call. langmatches('', _) :- !, fail. langmatches(_, *). langmatches(Lang, Pattern) :- atom_codes(Lang, LC), atom_codes(Pattern, PC), langmatches_codes(PC, LC). langmatches_codes([], []) :- !. langmatches_codes([], [0'-|_]) :- !. langmatches_codes([H|TP], [H|TC]) :- !, langmatches_codes(TP, TC). langmatches_codes([HP|TP], [HC|TC]) :- !, code_type(L, to_lower(HP)), code_type(L, to_lower(HC)), langmatches_codes(TP, TC). %% isiri(+IRI) % % True if IRI is an IRI. We get the argument un-evaluated. isiri(IRI) :- atom(IRI), !, \+ rdf_is_bnode(IRI). isiri(literal(_)) :- !, fail. isiri(Expr) :- eval(Expr, Value), Value = iri(IRI), \+ rdf_is_bnode(IRI). isblank(IRI) :- atom(IRI), !, rdf_is_bnode(IRI). isblank(literal(_)) :- !, fail. isblank(Expr) :- eval(Expr, Value), Value = iri(IRI), rdf_is_bnode(IRI). isliteral(literal(_)) :- !. isliteral(Atom) :- atom(Atom), !, fail. isliteral(Expr) :- eval(Expr, Value), Value \= iri(_). %% regex(+String, +Pattern, +Flags) % % TBD: % - Avoid XPCE % - Complete flags :- dynamic pattern_cache/3. % Pattern, Flags, Regex regex(String, Pattern, Flags) :- pattern_cache(Pattern, Flags, Regex), !, send(Regex, search, string(String)). regex(String, Pattern, Flags) :- make_regex(Pattern, Flags, Regex), send(Regex, lock_object, @(on)), asserta(pattern_cache(Pattern, Flags, Regex)), send(Regex, search, string(String)). make_regex(Pattern, i, Regex) :- !, new(Regex, regex(Pattern, @(off))). make_regex(Pattern, _, Regex) :- !, new(Regex, regex(Pattern)). %% effective_boolean_value(+Expr, -Bool) % % See SPARQL document, section 11.2.2: Effecitive Boolean Value effective_boolean_value(boolean(X), boolean(True)) :- !, True = X. effective_boolean_value(string(X), boolean(True)) :- !, (X == '' -> True = false ; True = true). effective_boolean_value(simple_literal(X), boolean(True)) :- !, (X == '' -> True = false ; True = true). effective_boolean_value(numeric(_, X), boolean(True)) :- !, (X =:= 0 -> True = false ; True = true). effective_boolean_value(_, boolean(error)). %% sparql_eval(+Expr, -Results) % % Evaluate an expression. sparql_eval(Expr, Expr) :- is_rdf(Expr), !. sparql_eval(Expr, Result) :- eval(Expr, Result0), to_rdf(Result0, Result). to_rdf(numeric(Type, Value), literal(type(Type, Atom))) :- atom_number(Atom, Value). to_rdf(boolean(Val), literal(Type, Val)) :- rdf_equal(xsd:boolean, Type). to_rdf(type(T, Val), literal(type(T, Val))). to_rdf(simple_literal(L), literal(L)). to_rdf(iri(IRI), IRI). %% is_rdf(+Term) % % True if Term is a valid RDF term. is_rdf(IRI) :- atom(IRI). is_rdf(Var) :- var(Var), !, fail. is_rdf(literal(_)).
nunolopes/anql
src/anql/sparql_runtime.pl
Perl
bsd-3-clause
18,969
package Net::Braintree::ErrorCodes::MerchantAccount::Individual; use strict; use constant FirstNameIsRequired => "82637"; use constant LastNameIsRequired => "82638"; use constant DateOfBirthIsRequired => "82639"; use constant SsnIsInvalid => "82642"; use constant EmailIsInvalid => "82643"; use constant FirstNameIsInvalid => "82644"; use constant LastNameIsInvalid => "82645"; use constant PhoneIsInvalid => "82656"; use constant DateOfBirthIsInvalid => "82666"; use constant EmailIsRequired => "82667"; 1;
braintree/braintree_perl
lib/Net/Braintree/ErrorCodes/MerchantAccount/Individual.pm
Perl
mit
562
=head1 AmiGO::WebApp::FacetMatrix ... =cut package AmiGO::WebApp::FacetMatrix; use base 'AmiGO::WebApp'; use Clone; use Data::Dumper; use CGI::Application::Plugin::Session; use CGI::Application::Plugin::TT; use AmiGO::Input; use AmiGO::External::HTML::Wiki::BBOPJS; ## sub setup { my $self = shift; # ## Configure how the session stuff is going to be handled when and # ## if it is necessary. $self->{STATELESS} = 1; # $self->{STATELESS} = 0; # $self->session_config(CGI_SESSION_OPTIONS => # ["driver:File", # $self->query, # {Directory=> # $self->{CORE}->amigo_env('AMIGO_SESSIONS_ROOT_DIR')} # ], # COOKIE_PARAMS => {-path => '/'}, # SEND_COOKIE => 1); # ## Templates. # $self->tt_include_path($self->{CORE}->amigo_env('AMIGO_ROOT') . # '/templates/html'); $self->mode_param('mode'); $self->start_mode('facet_matrix'); $self->error_mode('mode_fatal'); $self->run_modes( 'facet_matrix' => 'mode_facet_matrix', 'AUTOLOAD' => 'mode_exception' ); } ## Maybe how things should look in this framework? sub mode_facet_matrix { my $self = shift; ## Incoming template. my $i = AmiGO::Input->new($self->query()); my $params = $i->input_profile('facet_matrix'); $self->_common_params_settings($params); ## my $facet1 = $params->{facet1}; my $facet2 = $params->{facet2}; my $manager = $params->{manager}; if( ! $facet1 ){ $self->add_mq('warning', "The parameter \"facet1\" needs to be defined."); } if( ! $facet2 ){ $self->add_mq('warning', "The parameter \"facet2\" needs to be defined."); } if( ! $manager ){ $self->add_mq('warning', "The parameter \"manager\" needs to be defined."); } ## Page settings. $self->set_template_parameter('page_title', 'Facet Matrix'); $self->set_template_parameter('content_title', #'Facet Matrix: Compare Facet Counts'); 'Compare Facet Counts'); ## Only attempt launch if everything is fine. if( $facet1 && $facet2 && $manager ){ my $prep = { css_library => [ #'standard', 'com.bootstrap', 'com.jquery.jqamigo.custom', 'amigo', 'bbop' ], javascript_library => [ 'org.d3', 'com.jquery', 'com.bootstrap', 'com.jquery-ui', 'com.jquery.tablesorter' ], javascript => [ $self->{JS}->make_var('global_facet1', $facet1), $self->{JS}->make_var('global_facet2', $facet2), $self->{JS}->make_var('global_manager', $manager), $self->{JS}->get_lib('GeneralSearchForwarding.js'), $self->{JS}->get_lib('FacetMatrix.js') ], content => [ 'pages/facet_matrix.tmpl' ] }; $self->add_template_bulk($prep); $output = $self->generate_template_page_with(); return $output; }else{ return $self->mode_fatal("Not enough information to bootstrap process."); } } 1;
geneontology/amigo
perl/lib/AmiGO/WebApp/FacetMatrix.pm
Perl
bsd-3-clause
2,866
#! /usr/local/bin/perl -w # $Id: m68k-iset-expand.pl,v 1.5 2007/08/25 21:14:29 fredette Exp $ # m68k-inst-expand.pl - expands the m68k instruction templates into # full instruction word patterns and their decodings: # # Copyright (c) 2002, 2003 Matt Fredette # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. 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. # 3. All advertising materials mentioning features or use of this software # must display the following acknowledgement: # This product includes software developed by Matt Fredette. # 4. The name of the author may not be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. # # globals: $debug = 0; @threefield = ("000", "001", "010", "011", "100", "101", "110", "111"); # our single command line argument is the CPU name: if (@ARGV != 1) { print STDERR "usage: $0 CPU-NAME\n"; exit(1); } $cpu_name = shift(@ARGV); print "cpu-begin $cpu_name\n"; # to silence perl -w: undef($field_q); # loop over the instruction set on standard input: $pass = 1; for($line = 1; defined($_ = <STDIN>); $line++) { chomp; # split by spaces: @tokens = split(/[,\s]+/, $_); # strip comments: for ($token_i = 0; $token_i < @tokens; $token_i++) { splice(@tokens, $token_i) if ($tokens[$token_i] =~ /^\!/); } # skip blank lines: next if (@tokens == 0); # handle the preprocessor. this is the dumbest preprocessor ever: if ($tokens[0] eq ".if") { $pass = 0; foreach $token (@tokens) { $pass = 1 if ($token eq $cpu_name); } next; } elsif ($tokens[0] eq ".endif") { $pass = 1; next; } next if (!$pass); # handle an EAX category. an EAX category defines valid # combinations of an EA "mode" and "reg" values found in an # instruction patterns "x" field. see linear pp 60 of M68000PM.ps # for a list of all possible mode and reg combinations. # # different combinations are valid depending on the instruction # and operand being described, however most instructions use one # of a small handful of common combinations. # # an EA category is defined as: # # eax-cat NAME DEFAULT-CYCLES COMBINATIONS # # NAME is a user-assigned name for the category # # DEFAULT-CYCLES specifies the default memory cycle behavior # for this category of effective address. specific later uses # of this category may still override this default. this is # one of "un", "ro", "wo", or "rw", for no cycles, read-only, # write-only, and read-write, respectively # # COMBINATIONS is a string of "y" and "n" characters indicating # which mode and reg combinations are valid. positions zero # through six in the string correspond to mode values zero # through six, and positions seven through 14 correspond to # mode value 7, reg values zero through seven: # if ($tokens[0] eq "eax-cat") { # get the category definition: $eax_cat_name = $tokens[1]; $eax_cat_cycles_default = $tokens[2]; @eax_cat_modes = split(//, $tokens[3]); # expand this category once for each possible operand size, # remembering what operand each valid combination of mode and # reg means: foreach $eax_size (0, 8, 16, 32) { @eax_cat_fields = (); @eay_cat_fields = (); for ($mode = 0; $mode < @threefield; $mode++) { for ($reg = 0; $reg < @threefield; $reg++) { # EXCEPTION: 8-bit address register direct is always # illegal: next if ($eax_size == 8 && $mode == 1); if ($eax_cat_modes[$mode + ($mode < 7 ? 0 : $reg)] eq "y") { undef($field_x_value); undef($field_y_value); if ($mode == 0) { # data register direct: $field_x_value = "\%d${reg}.${eax_size}"; } elsif ($mode == 1) { # address register direct: $field_x_value = "\%a${reg}.${eax_size}"; } elsif ($mode == 7 && $reg == 4) { # immediate: $field_x_value = "imm.${eax_size}"; } elsif ($eax_size == 0) { # unsized, effective address complex: $field_x_value = "eax.32"; } else { $field_x_value = "memx.${eax_size}.$eax_cat_cycles_default"; $field_y_value = "memy.${eax_size}.$eax_cat_cycles_default"; } $field_y_value = $field_x_value if (!defined($field_y_value)); push(@eax_cat_fields, "$threefield[$mode]$threefield[$reg]/$field_x_value"); push(@eay_cat_fields, "$threefield[$reg]$threefield[$mode]/$field_y_value"); } } } eval("\@eax_${eax_cat_name}${eax_size} = \@eax_cat_fields;"); eval("\@eay_${eax_cat_name}${eax_size} = \@eay_cat_fields;"); } next; } # handle a "specop" line. some instructions have a separate opcode # word that needs to be read and decoded specially. we expand # any .s suffixes on the instruction names but otherwise pass # this line on untouched: # if ($tokens[0] eq "specop") { foreach $token (@tokens) { $token = "${1}8 ${1}16 ${1}32" if ($token =~ /^(\S+)\.s$/); } print join(" ", @tokens)."\n"; next; } # form the instruction template from the first four tokens: $template = join("", splice(@tokens, 0, 4)); # the next token is the function: $func = shift(@tokens); # the remaining tokens are the arguments: @args = @tokens; undef(@tokens); print "template $template, func $func, args: ".join(" ", @args)."\n" if ($debug); # break this template down into fields and sanity-check them. # we work from the leftmost position in the template (the most # significant bit, bit 15) to the rightmost position. # @fields = ("root"); for ($field_start = 15; $field_start >= 0; $field_start = $field_end - 1) { # find the extent of this field. a wildcard field (indicated # by the "?" character, which is internally rewritten to the "w" # character) is always a single bit wide, otherwise a constant # field ends right before a non-constant bit, and any other field # ends when it ends: # $field_char = substr($template, 15 - $field_start, 1); $field_char =~ tr/\?/w/; for ($field_end = $field_start; $field_end >= 0; $field_end--) { # get the next field character: $field_char_next = substr($template, 15 - ($field_end - 1), 1); $field_char_next =~ tr/\?/w/; # stop if this is the first character of the next field: last if ($field_char eq "w" || ($field_char =~ /[01]/ ? $field_char_next !~ /[01]/ : $field_char_next ne $field_char)); } # save this field: push (@fields, ($field_char =~ /[01]/ ? substr($template, 15 - $field_start, $field_start - $field_end + 1) : $field_char)); # sanity check this field. some fields must be a fixed size, # some fields must be used by some argument: # $field_size = $field_start - $field_end + 1; print "$#fields: $field_char-field from $field_start to $field_end" if ($debug); if ($field_char =~ /[01w]/) { # constant and wildcard fields can have any size } elsif ($field_char =~ /[sS]/) { # operand-size fields must be size two: die "stdin:$line: $field_char field must be size two\n" if ($field_size != 2); } elsif ($field_char =~ /[xy]/) { # effective address fields must be size six: die "stdin:$line: $field_char field must be size six\n" if ($field_size != 6); # effective address fields must be used by some argument: for ($arg_i = 0; $arg_i < @args; $arg_i++) { last if ($args[$arg_i] =~ /^$field_char([sS]|(\d+))\//); } die "stdin:$line: $field_char field not used by any argument\n" if ($arg_i == @args); print ", arg #$arg_i" if ($debug); eval("\$field_${field_char}_arg = $arg_i;"); } elsif ($field_char =~ /[daDAq]/) { # register and small-immediate fields must be size three: die "stdin:$line: $field_char field must be size three\n" if ($field_size != 3); } elsif ($field_char eq "c") { # condition code fields must be size four: die "stdin:$line: c field must be size four\n" if ($field_size != 4); } else { die "stdin:$line: unknown field type $field_char\n"; } print "\n" if ($debug); } print "fields: ".join(" ", @fields)."\n" if ($debug); # recursively go over the fields of this template, forming real, # legal instruction patterns, and their full decoding: $field_depth = 0; undef(@field_n0_values); @field_n0_values = (""); @pattern_stack = (""); @instruction_stack = (""); print "root\n" if ($debug); $pattern = ""; $instruction = ""; for (;;) { # find the next field value, popping the stack as needed, and # form the next pattern: for (; !defined($field_value = eval("shift(\@field_n${field_depth}_values)")); ) { eval("undef(\$field_$fields[$field_depth]);"); last if (--$field_depth < 0); $field_type = $fields[$field_depth]; pop(@pattern_stack); pop(@instruction_stack); } last if ($field_depth < 0); ($pattern_part, $field_value, $instruction_part) = split(/\//, $field_value, 3); $pattern_part = "" if (!defined($pattern_part)); $field_value = $pattern_part if (!defined($field_value) || $field_value eq ""); $instruction_part = "" if (!defined($instruction_part)); $pattern = $pattern_stack[$field_depth].$pattern_part; $instruction = $instruction_stack[$field_depth].$instruction_part; eval("\$field_$fields[$field_depth] = \"$field_value\";"); # if we don't have a complete pattern, descend into the # next field and expand it: if ($field_depth < $#fields) { $field_type = $fields[++$field_depth]; push(@pattern_stack, $pattern); push(@instruction_stack, $instruction); @field_values = (); # a constant field: if ($field_type =~ /^[01]/) { @field_values = ($field_type); } # a wildcard field: elsif ($field_type eq "w") { @field_values = ("0", "1"); } # a size field: elsif ($field_type eq "s") { @field_values = ("00/8", "01/16", "10/32"); } # the wacko size field: elsif ($field_type eq "S") { @field_values = ("01/8", "11/16", "10/32"); } # an eax or eay field: elsif ($field_type =~ /[xy]/) { # take apart the argument: $arg_i = eval("\$field_${field_type}_arg;"); die "stdin:$line: $args[$arg_i] is a bad EA argument\n" unless ($args[$arg_i] =~ /^${field_type}([sS]|(\d+))\/([^\/]+)(\/(\S\S))?$/); ($eax_size, $eax_cat_name, $eax_arg_cycles) = ($1, $3, $5); # if the EA size depends on a size field, get it: if ($eax_size =~ /[sS]/) { die "stdin:$line: $args[$arg_i] argument with no size field?\n" if (!defined($eax_size = eval("\$field_$eax_size;"))); } # get the field values: eval("\@field_values = \@ea${field_type}_${eax_cat_name}${eax_size};"); # if this argument is overriding the default cycles on the # EA category, enforce the override on the field values: if (defined($eax_arg_cycles) && $eax_arg_cycles ne "") { foreach $field_value (@field_values) { $field_value =~ s/\.(un|ro|wo|rw)$/\.$eax_arg_cycles/; } } } # a register field: elsif ($field_type =~ /[daDA]/) { @field_values = ("000/0", "001/1", "010/2", "011/3", "100/4", "101/5", "110/6", "111/7"); } # a quick constant field: elsif ($field_type eq "q") { @field_values = ("000/8", "001/1", "010/2", "011/3", "100/4", "101/5", "110/6", "111/7"); } # a condition code field: elsif ($field_type eq "c") { @field_values = ("0000/t", "0001/f", "0010/hi", "0011/ls", "0100/cc", "0101/cs", "0110/ne", "0111/eq", "1000/vc", "1001/vs", "1010/pl", "1011/mi", "1100/ge", "1101/lt", "1110/gt", "1111/le"); } # this field must have some values: die "stdin:$line: $field_type-field has no values\n" if (@field_values == 0); print "".(" " x $field_depth)."$field_type-field values: ".join(" ", @field_values)."\n" if ($debug); eval("\@field_n${field_depth}_values = \@field_values;"); # loop to pick up the first value from this depth, # and possibly continue descending: next; } # EXCEPTION: a move of an address register to a predecrement # or postincrement EA with that same address register, must # store the original value of the address register. since the # predecrement and postincrement code in the executer updates # the address register before the move has happened, we wrap # the normal move function in another that gives an op1 # argument that is the original value of the address register: if ($func =~ /^move_srp[di]\.S/) { $func = 'move.S'; } if ($func eq 'move.S' && substr($pattern, (15 - 5), 6) eq '001'.substr($pattern, (15 - 11), 3)) { if (substr($pattern, (15 - 8), 3) eq '100') { $func = 'move_srpd.S'; } elsif (substr($pattern, (15 - 8), 3) eq '011') { $func = 'move_srpi.S'; } } # the function name: if ($func =~ /^(.*)\.([sS])$/) { die "stdin:$line: $func with no size field?\n" if (!defined($_ = eval("\$field_$2;"))); $instruction .= " func=$1$_"; } else { $instruction .= " func=$func"; } # handle the arguments: for ($arg_i = 0; $arg_i < @args ; $arg_i++) { $arg = $args[$arg_i]; # replace any .s with the s-field: $arg = "$1.$field_s" if ($arg =~ /^(.*)\.s$/); $arg = "$1.$field_S" if ($arg =~ /^(.*)\.S$/); # an immediate argument: $arg = "#$field_s" if ($arg eq "#s"); $arg = "#$field_S" if ($arg eq "#S"); if ($arg =~ /^\#(\d+)$/ || $arg =~ /^\#(16S32)$/) { $instruction .= " imm_size=$1 imm_operand=$arg_i"; } # an EA argument: elsif ($arg =~ /^([xy])/) { $field_type = $1; $field_value = eval("\$field_${field_type};"); if ($field_value =~ /^mem${field_type}\.(\d+)\.(\S\S)$/) { die "stdin:$line: unsized ea${field_type} memory argument $field_value (internal error?)\n" if ($1 == 0); die "stdin:$line: ea${field_type} memory argument with no cycles (internal error?)\n" if ($2 eq "un"); $instruction .= " ea${field_type}_size=$1 ea${field_type}_cycles=$2"; $field_value = "mem${field_type}.$1"; } elsif ($field_value =~ /^imm\.(\d+)$/) { $instruction .= " imm_size=$1 imm_operand=$arg_i"; $field_value = ""; } elsif ($field_value eq "eax.32") { $instruction .= " eax_size=UNSIZED"; } $instruction .= " op${arg_i}=$field_value" if ($field_value ne ""); } # a register argument: elsif ($arg =~ /^\%([daDA])(\.\d+)$/) { $field_type = $1; $reg = $field_type; $reg =~ tr/A-Z/a-d/; $instruction .= " op${arg_i}=\%$reg".eval("\$field_$1;").$2; } # a register number argument: elsif ($arg =~ /^\#([daDa])/) { $field_type = $1; $instruction .= " op${arg_i}=imm".eval("\$field_$1;").".32"; } # a quick integer argument: elsif ($arg =~ /^\#q\.(\d+)/) { $instruction .= " op${arg_i}=imm${field_q}.$1"; } # a hard-coded immediate argument: elsif ($arg =~ /^\#(\d+)\.(\d+)/) { $instruction .= " op${arg_i}=imm$1.$2"; } # handle a dummy argument: elsif ($arg eq "X") { } else { die "stdin:$line: argument type $arg unknown\n"; } } # we have a complete pattern and decoded instruction: print "$pattern$instruction\n"; } } print "cpu-end $cpu_name\n"; # done: exit(0);
DavidGriffith/tme
ic/m68k/m68k-iset-expand.pl
Perl
bsd-3-clause
16,532
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 8.0.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'; V108 64341 64342 64345 64346 64349 64350 64353 64354 64357 64358 64361 64362 64365 64366 64369 64370 64373 64374 64377 64378 64381 64382 64385 64386 64401 64402 64405 64406 64409 64410 64413 64414 64419 64420 64425 64426 64429 64430 64470 64471 64487 64488 64489 64490 64511 64512 64735 64757 64820 64828 65137 65138 65143 65144 65145 65146 65147 65148 65149 65150 65151 65152 65164 65165 65170 65171 65176 65177 65180 65181 65184 65185 65188 65189 65192 65193 65204 65205 65208 65209 65212 65213 65216 65217 65220 65221 65224 65225 65228 65229 65232 65233 65236 65237 65240 65241 65244 65245 65248 65249 65252 65253 65256 65257 65260 65261 65268 65269 END
operepo/ope
bin/usr/share/perl5/core_perl/unicore/lib/Dt/Med.pl
Perl
mit
1,139
# 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. # package ModPerl::BuildMM; use strict; use warnings; use ExtUtils::MakeMaker (); use Cwd (); use File::Spec::Functions qw(catdir catfile splitdir); use File::Basename; use File::Find; use Apache2::Build (); use ModPerl::MM; use constant WIN32 => Apache2::Build::WIN32; use constant CYGWIN => Apache2::Build::CYGWIN; our %PM; #add files to installation # MM methods that this package overrides no strict 'refs'; my $stash = \%{__PACKAGE__ . '::MY::'}; my @methods = grep *{$stash->{$_}}{CODE}, keys %$stash; ModPerl::MM::override_eu_mm_mv_all_methods(@methods); use strict 'refs'; my $apache_test_dir = catdir Cwd::getcwd(), "Apache-Test", "lib"; #to override MakeMaker MOD_INSTALL macro sub mod_install { q{$(PERL) -I$(INST_LIB) -I$(PERL_LIB) \\}."\n" . qq{-I$apache_test_dir -MModPerl::BuildMM \\}."\n" . q{-e "ExtUtils::Install::install({@ARGV},'$(VERBINST)',0,'$(UNINST)');"}."\n"; } my $build; sub build_config { my $key = shift; $build ||= Apache2::Build->build_config; return $build unless $key; $build->{$key}; } #the parent WriteMakefile moves MY:: methods into a different class #so alias them each time WriteMakefile is called in a subdir sub my_import { no strict 'refs'; my $stash = \%{__PACKAGE__ . '::MY::'}; for my $sym (keys %$stash) { next unless *{$stash->{$sym}}{CODE}; my $name = "MY::$sym"; undef &$name if defined &$name; *$name = *{$stash->{$sym}}{CODE}; } } sub WriteMakefile { my %args = @_; $build ||= build_config(); ModPerl::MM::my_import(__PACKAGE__); my $inc = $args{INC} || ''; $inc = $args{INC} if $args{INC}; $inc .= " " . $build->inc; if (my $glue_inc = $build->{MP_XS_GLUE_DIR}) { for (split /\s+/, $glue_inc) { $inc .= " -I$_"; } } my $libs; my @libs = (); push @libs, $args{LIBS} if $args{LIBS}; if (Apache2::Build::BUILD_APREXT) { # in order to decouple APR/APR::* from mod_perl.so, # link these modules against the static MP_APR_LIB lib, # rather than the mod_perl lib (which would demand mod_perl.so # be available). For other modules, use mod_perl.lib as # usual. This is done for APR in xs/APR/APR/Makefile.PL. my $name = $args{NAME}; if ($name =~ /^APR::\w+$/) { # For cygwin compatibility, the order of the libs should be # <mod_perl libs> <apache libs> @libs = ($build->mp_apr_lib, $build->apache_libs); } else { @libs = ($build->modperl_libs, $build->apache_libs); } } else { @libs = ($build->modperl_libs, $build->apache_libs); } $libs = join ' ', @libs; my $ccflags; $ccflags = $args{CCFLAGS} if $args{CCFLAGS}; $ccflags = " " . $build->perl_ccopts . $build->ap_ccopts; my $optimize; $optimize = $args{OPTIMIZE} if $args{OPTIMIZE}; $optimize = " " . $build->perl_config('optimize'); my $lddlflags; $lddlflags = $args{LDDLFLAGS} if $args{LDDLFLAGS}; $lddlflags = " " . $build->perl_config('lddlflags'); my %dynamic_lib; %dynamic_lib = %{ $args{dynamic_lib}||{} } if $args{dynamic_lib}; $dynamic_lib{OTHERLDFLAGS} = $build->otherldflags; my @opts = ( INC => $inc, CCFLAGS => $ccflags, OPTIMIZE => $optimize, LDDLFLAGS => $lddlflags, LIBS => $libs, dynamic_lib => \%dynamic_lib, ); my @typemaps; push @typemaps, $args{TYPEMAPS} if $args{TYPEMAPS}; my $pwd = Cwd::fastcwd(); for ('xs', $pwd, "$pwd/..") { my $typemap = $build->file_path("$_/typemap"); if (-e $typemap) { push @typemaps, $typemap; } } push @opts, TYPEMAPS => \@typemaps if @typemaps; my $clean_files = (exists $args{clean} && exists $args{clean}{FILES}) ? $args{clean}{FILES} : ''; $clean_files .= " glue_pods"; # cleanup the dependency target $args{clean}{FILES} = $clean_files; ExtUtils::MakeMaker::WriteMakefile(@opts, %args); } my %always_dynamic = map { $_, 1 } qw(ModPerl::Const Apache2::Const APR::Const APR APR::PerlIO); sub ModPerl::BuildMM::MY::constants { my $self = shift; $build ||= build_config(); #"discover" xs modules. since there is no list hardwired #any module can be unpacked in the mod_perl-2.xx directory #and built static #this stunt also make it possible to leave .xs files where #they are, unlike 1.xx where *.xs live in src/modules/perl #and are copied to subdir/ if DYNAMIC=1 if ($build->{MP_STATIC_EXTS}) { #skip .xs -> .so if we are linking static my $name = $self->{NAME}; unless ($always_dynamic{$name}) { if (my ($xs) = keys %{ $self->{XS} }) { $self->{HAS_LINK_CODE} = 0; print "$name will be linked static\n"; #propagate static xs module to src/modules/perl/Makefile $build->{XS}->{$name} = join '/', Cwd::fastcwd(), $xs; $build->save; } } } $self->MM::constants; } sub ModPerl::BuildMM::MY::top_targets { my $self = shift; my $string = $self->MM::top_targets; return $string; } sub ModPerl::BuildMM::MY::postamble { my $self = shift; my $doc_root = catdir Cwd::getcwd(), "docs", "api"; my @targets = (); # reasons for glueing pods to the respective .pm files: # - manpages will get installed over the mp1 manpages and vice # versa. glueing pods avoids creation of manpages, but may be we # could just tell make to skip manpages creation? # if pods are installed directly they need to be also redirected, # some into Apache2/ others (e.g. Apache2) not # add the code to glue the existing pods to the .pm files in blib. # create a dependency on pm_to_blib subdirs linkext targets to # allow 'make -j' require ExtUtils::MakeMaker; my $mm_ver = $ExtUtils::MakeMaker::VERSION; $mm_ver =~ s/_.*//; # handle dev versions like 6.30_01 my $pm_to_blib = ($mm_ver >= 6.22 && $mm_ver <= 6.25) ? "pm_to_blib.ts" : "pm_to_blib"; my @target = ("glue_pods: $pm_to_blib subdirs linkext"); if (-d $doc_root) { my $build = build_config(); # those living in modperl-2.0/lib are already nicely mapped my %pms = %{ $self->{PM} }; my $cwd = Cwd::getcwd(); my $blib_dir = catdir qw(blib lib); # those autogenerated under WrapXS/ # those living under xs/ # those living under ModPerl-Registry/lib/ my @src = ('WrapXS', 'xs', catdir(qw(ModPerl-Registry lib))); for my $base (@src) { chdir $base; my @files = (); find({ no_chdir => 1, wanted => sub { push @files, $_ if /.pm$/ }, }, "."); chdir $cwd; for (@files) { my $pm = catfile $base, $_; my $blib; if ($base =~ /^(xs|WrapXS)/) { my @segm = splitdir $_; splice @segm, -2, 1; # xs/APR/Const/Const.pm splice @segm, -2, 1 if /APR.pm/; # odd case $blib = catfile $blib_dir, @segm; } else { $blib = catfile $blib_dir, $_; } $pms{$pm} = $blib; } } while (my ($pm, $blib) = each %pms) { $pm =~ s|/\./|/|g; # clean the path $blib =~ s|/\./|/|g; # clean the path my @segm = splitdir $blib; for my $i (1..2) { # try APR.pm and APR/Bucket.pm my $pod = catdir(@segm[-$i .. -1]); $pod =~ s/\.pm/\.pod/; my $podpath = catfile $doc_root, $pod; next unless -r $podpath; push @target, '$(FULLPERL) -I$(INST_LIB) ' . "-I$apache_test_dir -MModPerl::BuildMM " . "-e ModPerl::BuildMM::glue_pod $pm $podpath $blib"; # Win32 doesn't normally install man pages # and Cygwin doesn't allow '::' in file names next if WIN32 || CYGWIN; # manify while we're at it my (undef, $man, undef) = $blib =~ m!(blib/lib/)(.*)(\.pm)!; $man =~ s!/!::!g; push @target, '$(NOECHO) $(POD2MAN_EXE) --section=3 ' . "$podpath \$(INST_MAN3DIR)/$man.\$(MAN3EXT)" } } push @target, $self->{NOECHO} . '$(TOUCH) $@'; } else { # we don't have the docs sub-cvs repository extracted, skip # the docs gluing push @target, $self->{NOECHO} . '$(NOOP)'; } push @targets, join "\n\t", @target; # # next target: cleanup the dependency file # @target = ('glue_pods_clean:'); # push @target, '$(RM_F) glue_pods'; # push @targets, join "\n\t", @target; return join "\n\n", @targets, ''; } sub glue_pod { die "expecting 3 arguments: pm, pod, dst" unless @ARGV == 3; my ($pm, $pod, $dst) = @ARGV; # it's possible that the .pm file is not existing # (e.g. ThreadMutex.pm is not created on unless # $apr_config->{HAS_THREADS}) return unless -e $pm && -e $dst; # have we already glued the doc? exit 0 unless -s $pm == -s $dst; # ExtUtils::Install::pm_to_blib removes the 'w' perms, so we can't # just append the doc there my $orig_mode = (stat $dst)[2]; my $rw_mode = 0666; chmod $rw_mode, $dst or die "Can't chmod $rw_mode $dst: $!"; open my $pod_fh, "<$pod" or die "Can't open $pod: $!"; open my $dst_fh, ">>$dst" or die "Can't open $dst: $!"; print $dst_fh "\n"; # must add one line separation print $dst_fh (<$pod_fh>); close $pod_fh; close $dst_fh; # restore the perms chmod $orig_mode, $dst or die "Can't chmod $orig_mode $dst: $!"; } sub ModPerl::BuildMM::MY::post_initialize { my $self = shift; $build ||= build_config(); my $pm = $self->{PM}; while (my ($k, $v) = each %PM) { if (-e $k) { $pm->{$k} = $v; } } # prefix typemap with Apache2/ so when installed in the # perl-lib-tree it won't be picked by non-mod_perl modules if (exists $pm->{'lib/typemap'} ) { $pm->{'lib/typemap'} = '$(INST_ARCHLIB)/auto/Apache2/typemap'; } ''; } my $apr_config; sub ModPerl::BuildMM::MY::libscan { my ($self, $path) = @_; $apr_config ||= $build->get_apr_config(); if ($path =~ m/(Thread|Global)(Mutex|RWLock)/) { return unless $apr_config->{HAS_THREADS}; } return '' if $path =~ /DummyVersions.pm/; return '' if $path =~ m/\.pl$/; return '' if $path =~ m/~$/; return '' if $path =~ /\B\.svn\b/; $path; } 1;
Distrotech/mod_perl
lib/ModPerl/BuildMM.pm
Perl
apache-2.0
11,752
package Smolder::Upgrade; use warnings; use strict; use File::Spec::Functions qw(catfile); use Smolder; use Smolder::Conf qw(SQLDir); use Smolder::DB; =head1 NAME Smolder::Upgrade - Base class for Smolder upgrade modules =head1 SYNOPSIS use base 'Smolder::Upgrade'; sub pre_db_upgrade {....} sub post_db_upgrade { ... } =head1 DESCRIPTION This module is intended to be used as a parent class for Smolder upgrade modules. =head2 METHODS =head3 new The new() method is a constructor which creates a trivial object from a hash. Your upgrade modules may use this to store state information. =cut # Create a trivial object sub new { my $class = shift; bless({}, $class); } =head3 upgrade This method looks at the current db_version of the database being used and then decides which upgrade modules should be run. Upgrade modules are children of this module and have the following naming pattern: C<Smolder::Upgrade::VX_YZ> where C<X.YZ> is the version number. So for example if the current version is at 1.35 and we are upgrading to 1.67, then any C<Smolder::Upgrade::VX_YZ> modules between those 2 versions are run. =cut sub upgrade { my $self = shift; # don't do anything for dev releases return if $Smolder::VERSION =~ /_/; my $db_version = Smolder::DB->db_Main->selectall_arrayref('SELECT db_version FROM db_version'); $db_version = $db_version->[0]->[0]; if ($db_version < $Smolder::VERSION) { # find applicable upgrade modules warn "Your version of Smolder ($db_version) is out of date. Upgrading to $Smolder::VERSION...\n"; my $upgrade_dir = __FILE__; $upgrade_dir =~ s/\.pm$//; # Find upgrade modules opendir(DIR, $upgrade_dir) || die("Unable to open upgrade directory '$upgrade_dir': $!\n"); my @up_modules; foreach my $file (sort readdir(DIR)) { if ( (-f catfile($upgrade_dir, $file)) && ($file =~ /^V(\d+)\_(\d+)\.pm$/) && ("$1.$2" > $db_version)) { push(@up_modules, $file); } } closedir(DIR); warn " Found " . scalar(@up_modules) . " applicable upgrade modules.\n"; if (@up_modules) { foreach my $mod (@up_modules) { $mod =~ /(.*)\.pm$/; my $class = $1; my ($major, $minor) = ($class =~ /V(\d+)_(\d+)/); $class = "Smolder::Upgrade::$class"; eval "require $class"; die "Can't load $class upgrade class: $@" if $@; $class->new->version_upgrade("$major.$minor"); } } # upgrade the db_version Smolder::DB->db_Main->do('UPDATE db_version SET db_version = ?', undef, $Smolder::VERSION); } } =head3 version_upgrade This method is called by C<upgrade()> for each upgrade version module. It shouldn't be called directly from anyway else except for testing. It performs the following steps: =over =item 1 Call the L<pre_db_upgrade> method . =item 2 Run the SQL upgrade file found in F<sql/upgrade/> that has the same version which is named for this same version. So an upgrade module named F<V1_23> will run the F<upgrade/V1_23.sql> file if it exists. =item 3 Call the L<post_db_upgrade> method. =back =cut sub version_upgrade { my ($self, $version) = @_; $self->pre_db_upgrade(); # find and run the SQL file $version =~ /(\d+)\.(\d+)/; my $file = catfile(SQLDir, 'upgrade', "V$1_$2.sql"); if (-e $file) { warn " Upgrading DB with file '$file'.\n"; Smolder::DB->run_sql_file($file); } else { warn " No SQL file ($file) for version $version. Skipping DB upgrade.\n"; } $self->post_db_upgrade(); # add any new things to the config file my $new_config_stuff = $self->add_to_config(); if ($new_config_stuff) { # write out the new lines my $conf_file = catfile($ENV{SMOLDER_ROOT}, 'conf', 'smolder.conf'); open(CONF, '>>', $conf_file) or die "Unable to open $conf_file: $!"; print CONF $new_config_stuff; close(CONF); } } =head3 pre_db_upgrade This method must be implemented in your subclass. It is called before the SQL upgrade file is run. It receives the L<Smolder::Platform> class for the given platform. =cut sub pre_db_upgrade { my $self = shift; die "pre_db_upgrade() must be implemented in " . ref($self); } =head3 post_db_upgrade This method must be implemented in your subclass. It is called after the SQL upgrade file is run. It receives the L<Smolder::Platform> class for the given platform. =cut sub post_db_upgrade { my $self = shift; die "post_db_upgrade() must be implemented in " . ref($self); } =head3 add_to_config This method will take a given string and add it to the end of the current configuration file. This is useful for adding new required directives with a reasonable default. =cut sub add_to_config { } 1;
mpeters/smolder
lib/Smolder/Upgrade.pm
Perl
bsd-3-clause
5,036
#!/usr/bin/env perl print "Content-Type: text/html\r\n\r\n"; print $ENV{'REMOTE_ADDR'}; if ($ENV{'QUERY_STRING'} eq 'info') { print "\nF:",$ENV{'HTTP_X_FORWARDED_FOR'},"\n"; while (my($key, $value) = each %ENV) { printf "%s => %s\n", $key, $value; } } 0;
kaleb-himes/lighttpd1.4
tests/docroot/www/ip.pl
Perl
bsd-3-clause
263
=pod =head1 NAME SSL_get_client_CA_list, SSL_CTX_get_client_CA_list - get list of client CAs =head1 SYNOPSIS #include <openssl/ssl.h> STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *s); STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *ctx); =head1 DESCRIPTION SSL_CTX_get_client_CA_list() returns the list of client CAs explicitly set for B<ctx> using L<SSL_CTX_set_client_CA_list(3)>. SSL_get_client_CA_list() returns the list of client CAs explicitly set for B<ssl> using SSL_set_client_CA_list() or B<ssl>'s SSL_CTX object with L<SSL_CTX_set_client_CA_list(3)>, when in server mode. In client mode, SSL_get_client_CA_list returns the list of client CAs sent from the server, if any. =head1 RETURN VALUES SSL_CTX_set_client_CA_list() and SSL_set_client_CA_list() do not return diagnostic information. SSL_CTX_add_client_CA() and SSL_add_client_CA() have the following return values: =over 4 =item STACK_OF(X509_NAMES) List of CA names explicitly set (for B<ctx> or in server mode) or send by the server (client mode). =item NULL No client CA list was explicitly set (for B<ctx> or in server mode) or the server did not send a list of CAs (client mode). =back =head1 SEE ALSO L<ssl(3)>, L<SSL_CTX_set_client_CA_list(3)>, L<SSL_CTX_set_client_cert_cb(3)> =head1 COPYRIGHT Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. Licensed under the OpenSSL license (the "License"). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at L<https://www.openssl.org/source/license.html>. =cut
openweave/openweave-core
third_party/openssl/openssl/doc/ssl/SSL_get_client_CA_list.pod
Perl
apache-2.0
1,636
#!/usr/bin/perl # Copyright (C) 2000-2004 Carsten Haitzler, Geoff Harrison and various contributors # # 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 of the Software, its documentation and marketing & publicity # materials, and acknowledgment shall be given in the documentation, materials # and software packages that this Software was used. # # 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 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. # This is a hack of mandrake's "testroller.pl" that shades/unshades all your # pager windows # here we're going to test to see whether we are shading or unshading # the window. if($ARGV[0] eq "1") { $shade = "on"; } elsif($ARGV[0] eq "0") { $shade = "off"; } else { $shade = ""; } # make sure that we're not an internal window in our list @winlist_temp = `eesh window_list`; foreach(@winlist_temp) { chomp; @stuff = split /\s*\:\s*/; # print ">$stuff[0]<>$stuff[1]<\n"; if ($stuff[1] =~ /^Pager-.*/) { push @winlist,$stuff[0] if ($stuff[0]); } } # now we're going to walk through each of these windows and # shade them open IPCPIPE,"| eesh"; foreach $window (@winlist) { print IPCPIPE "win_op $window shade $shade\n"; } close IPCPIPE; # Alternatively, simply do #$ eesh wop Pager* shade [on|off]
burzumishi/e16
sample-scripts/shade-pagers.pl
Perl
mit
2,137
% Empty with aleph loaded :- use_module(library(aleph)). :- aleph. % Settings % Language Bias and Definitions :-begin_bg. % Background knowledge here :- end_bg. :-begin_in_pos. % Positive individuals here :-end_in_pos. :-begin_in_neg. % Negative individuals here :-end_in_neg. :-aleph_read_all. /** <examples> Your example queries go here, e.g. ?- induce(Program). */
TeamSPoon/logicmoo_workspace
packs_web/swish/profiles/40-ALEPH.pl
Perl
mit
386
/* % =================================================================== % File 'mpred_userkb.pl' % Purpose: Emulation of OpenCyc for SWI-Prolog % Maintainer: Douglas Miles % Contact: $Author: dmiles $@users.sourceforge.net ; % Version: 'interface.pl' 1.0.0 % Revision: $Revision: 1.9 $ % Revised At: $Date: 2002/06/27 14:13:20 $ % =================================================================== % File used as storage place for all predicates which change as % the world is run. % % % Dec 13, 2035 % Douglas Miles */ end_of_file. % DWhitten> ... but is there a reason why "Absurdity" is the word used for something that doesn't exist? % SOWA> It's stronger than that. The absurd type is defined by axioms that are contradictory. % Therefore, by definition, nothing of that type can exist. % this commented out so the autoloader doent pick it up %:- if(( ( \+ ((current_prolog_flag(logicmoo_include,Call),Call))) )). :- module(mpred_userkb, [mpred_userkb_file/0]). %:- include('mpred_header.pi'). %:- endif. mpred_userkb_file. % :- '$set_source_module'(baseKB). %% base_kb_pred_list( ?VALUE1) is semidet. % % Base Knowledge Base Predicate List. % :- dynamic(baseKB:base_kb_pred_list/1). baseKB:base_kb_pred_list([ functorDeclares/1, arity/2, abox:(::::)/2, abox:(<-)/2, % (<==)/2, abox:(<==>)/2, abox:(==>)/2, abox:(==>)/1, abox:(nesc)/1, abox:(~)/1, %mpred_f/1, mpred_f/2,mpred_f/3,mpred_f/4,mpred_f/5,mpred_f/6,mpred_f/7, %add_args/15, %naf_in_code/1, %neg_may_naf/1, %tilda_in_code/1, mpred_undo_sys/3, % addTiny_added/1, baseKB:agent_call_command/2, %baseKB:mud_test/2, type_action_info/3, argGenl/3, argIsa/3, argQuotedIsa/3, %lmcache:loaded_external_kbs/1, rtArgsVerbatum/1, %arity/2, asserted_mpred_f/2, asserted_mpred_f/3, asserted_mpred_f/4, asserted_mpred_f/5, asserted_mpred_f/6, asserted_mpred_f/7, asserted_mpred_t/2, asserted_mpred_t/3, asserted_mpred_t/4, asserted_mpred_t/5, asserted_mpred_t/6, asserted_mpred_t/7, call_OnEachLoad/1, coerce_hook/3, completelyAssertedCollection/1, conflict/1, constrain_args_pttp/2, contract_output_proof/2, transitiveViaArg/3, current_world/1, predicateConventionMt/2, %is_never_type/1, %cyckb_t/3, %cycPrepending/2, %cyc_to_plarkc/2, %decided_not_was_isa/2, deduceFromArgTypes/1, default_type_props/3, defnSufficient/2, did_learn_from_name/1, elInverse/2, % baseKB:feature_test/0, formatted_resultIsa/2, function_corisponding_predicate/2, transitiveViaArgInverse/3, genls/2, grid_key/1, hybrid_support/2, if_missing/2, % pfc is_edited_clause/3, is_wrapper_pred/1, % isa/2, ruleRewrite/2, resultIsa/2, % lmcache:isCycAvailable_known/0, isCycUnavailable_known/1, lambda/5, % mpred_select_hook/1, localityOfObject/2, meta_argtypes/1, mpred_action/1, mdefault/1, % pfc % most/1, % pfc mpred_do_and_undo_method/2, %mpred_isa/2, %mpred_manages_unknowns/0, mpred_prop/4, predicateConventionMt/2, mudKeyword/2, mudDescription/2, %never_assert_u/2, %never_assert_u0/2, %never_retract_u/2, %never_assert_u/1, %never_retract_u/1, now_unused/1, %baseKB:only_if_pttp/0, pddlSomethingIsa/2, pfcControlled/1, pfcRHS/1, predCanHaveSingletons/1, prologBuiltin/1, prologDynamic/1,prologHybrid/1,prologKIF/1,prologListValued/1,functorIsMacro/1,prologMultiValued/1,prologNegByFailure/1,prologOrdered/1, prologPTTP/1, prologSideEffects/1, prologSingleValued/1, props/2,rtReformulatorDirectivePredicate/1,pttp1a_wid/3,pttp_builtin/2, % pttp_nnf_pre_clean_functor/3, quasiQuote/1,relationMostInstance/3,resolveConflict/1, rtSymmetricBinaryPredicate/1, resolverConflict_robot/1, retractall_wid/1, search/7, skolem/2,skolem/3, completeExtentEnumerable/1, %use_ideep_swi/0, cycPred/2, cycPlus2/2, predStub/2, singleValuedInArg/2, subFormat/2, support_hilog/2, t/1,t/10,t/11,t/2,t/3,t/4,t/5,t/6,t/7,t/8,t/9, tCol/1, tFarthestReachableItem/1, tFunction/1, tNearestReachableItem/1, rtNotForUnboundPredicates/1, tPred/1, tRegion/1, tAgent/1, tRelation/1, tried_guess_types_from_name/1, tCol/1, ttExpressionType/1, ttRelationType/1, ttTemporalType/1, ttUnverifiableType/1, type_action_info/3, typeProps/2, % vtUnreifiableFunction/1, was_chain_rule/1, wid/3, use_kif/2, never_assert_u/2, prologEquality/1,pfcBcTrigger/1, meta_argtypes/1, % pfcDatabaseTerm/1, pfcControlled/1,pfcWatches/1,pfcMustFC/1,predIsFlag/1,tPred/1,prologMultiValued/1, prologSingleValued/1,functorIsMacro/1,notAssertable/1,prologBuiltin/1,prologDynamic/1,prologOrdered/1,prologNegByFailure/1,prologPTTP/1,prologKIF/1,prologEquality/1,prologPTTP/1, prologSideEffects/1,prologHybrid/1,prologListValued/1]). :- multifile(baseKB:'$exported_op'/3). :- discontiguous baseKB:'$exported_op'/3. :- thread_local(t_l:disable_px/0). :- dynamic(baseKB:use_kif/2). % :- kb_shared(baseKB:use_kif/2). :- multifile(baseKB:safe_wrap/4). :- dynamic(baseKB:safe_wrap/4). :- call_u(true). /* :-dynamic( pm/1). :- dynamic(( argIsa/3, '$bt'/2, %basePFC hs/1, %basePFC hs/1, %basePFC '$nt'/3, %basePFC pk/3, %basePFC '$pt'/3, %basePFC que/1, %basePFC pm/1, %basePFC '$spft'/4, %basePFC tms/1, %basePFC prologSingleValued/1)). */ :- multifile(baseKB:use_cyc_database/0). :- thread_local(baseKB:use_cyc_database/0). /* :- set_defaultAssertMt(baseKB). :- set_fileAssertMt(baseKB). */ %:- '$set_source_module'(baseKB). %:- '$set_typein_module'(baseKB). kb_shared_m(E):- must(with_source_module(baseKB,decl_as(kb_shared,E))). :- multifile(baseKB:predicateConventionMt/2). :- dynamic(baseKB:predicateConventionMt/2). % :- kb_shared(mpred_online:semweb_startup/0). % :- baseKB:base_kb_pred_list([A,B|_List]),rtrace(call(must_maplist(kb_shared_m,[A,B]))). :- baseKB:base_kb_pred_list(List),call(must_maplist(kb_shared_m,List)). % XXXXXXXXXXXXXXXXXXXXXXXXXx % XXXXXXXXXXXXXXXXXXXXXXXXXx % XXXXXXXXXXXXXXXXXXXXXXXXXx % XXXXXXXXXXXXXXXXXXXXXXXXXx :- meta_predicate t(*,?,?), t(*,?,?,?), t(*,?,?,?,?), t(*,?,?,?,?,?), t(*,?,?,?,?,?,?), t(*,?,?,?,?,?,?,?). :- meta_predicate resolveConflict(+), resolveConflict0(+), %mpred_isa(?,1), resolverConflict_robot(+). :- source_location(F,_),set_how_virtualize_file(false,F). %:- '$set_source_module'(baseKB). %% skolem( ?X, ?SK) is semidet. % % Skolem. % skolem(X,SK):-skolem_in_code(X,SK). %% skolem( ?X, ?Vs, ?SK) is semidet. % % Skolem. % skolem(X,Vs,SK):-skolem_in_code(X,Vs,SK). %% current_world( ?VALUE1) is semidet. % % Current World. % current_world(current). resolveConflict(C):- must((resolveConflict0(C), show_if_debug(is_resolved(C)),mpred_remove(conflict(C)))). resolveConflict(C) :- wdmsg("Halting with conflict ~p", [C]), must(mpred_halt(conflict(C))),fail. %% resolveConflict0( ?C) is semidet. % % Resolve Conflict Primary Helper. % resolveConflict0(C) :- forall(must(mpred_negation_w_neg(C,N)),ignore(show_failure(why,(nop(resolveConflict(C)),mpred_why(N))))), ignore(show_failure(why,(nop(resolveConflict(C)),mpred_why(C)))), doall((call_u(resolverConflict_robot(C)),\+ is_resolved(C),!)), is_resolved(C),!. %% resolverConflict_robot( ?N) is semidet. % % Resolver Conflict Robot. % resolverConflict_robot(N) :- forall(must(mpred_negation_w_neg(N,C)),forall(compute_resolve(C,N,TODO),on_x_debug(show_if_debug(TODO)))). resolverConflict_robot(C) :- must((mpred_remove(C),wdmsg("Rem-3 with conflict ~p", [C]),pfc_run,sanity(\+C))). %% never_declare( :TermRule, ?Rule) is semidet. % % Never Declare For User Code. % never_declare(declared(M:F/A),never_declared(M:F/A)):- M:F/A = qrTBox:p/1. never_declare(declared(P),Why):- nonvar(P),functor(P,F,A),F\=(:),F\=(/),never_declare(declared(F/A),Why). never_declare(declared(mpred_run_resume/0),cuz). never_declare(declared(decl_type/1),cuz). never_declare(declared(is_clif/1),cuz). never_declare(declared(_:FA),Why):-nonvar(FA),never_declare(declared(FA),Why). never_declare(_:declared(_:FA),Why):-nonvar(FA),never_declare(declared(FA),Why). never_declare(_:declared(FA),Why):-nonvar(FA),never_declare(declared(FA),Why). %% never_assert_u( :TermRule, ?Rule) is semidet. % % Never Assert For User Code. % :- dynamic((never_assert_u/2)). :- multifile((never_assert_u/2)). % never_assert_u('$pt'(MZ,Pre,Post),head_singletons(Pre,Post)):- head_singletons(Pre,Post). never_assert_u(Rule,is_var(Rule)):- is_ftVar(Rule),!. never_assert_u(Rule,head_singletons(Pre,Post)):- Rule \= (_:-_), once(mpred_rule_hb(Rule,Post,Pre)), head_singletons(Pre,Post). never_assert_u(A,B):-never_assert_u0(A,B),dtrace,never_assert_u0(A,B). % never_assert_u(M:arity(_,_),is_support(arity/2)):- M==pqr,dumpST, dtrace, !. never_assert_u(A,B):-ground(A),never_declare(A,B). never_assert_u(M:Rule,Why):- atom(M),never_assert_u(Rule,Why). /* never_assert_u('$pt'(MZ,_, singleValuedInArg(A, _), (dtrace->rhs([{dtrace}, prologSingleValued(B)]))),singletons):- dtrace,A\=B,dtrace. */ on_modules_changed:-!. on_modules_changed :- forall((current_module(M),M\=user,M\=system,M\=baseKB,M\=abox,\+ baseKB:mtHybrid(M)), (default_module(abox,M)->true;catch(nop(add_import_module(M,abox,start)),E1,dmsg(E1:nop(add_import_module(M,abox,start)))))), forall((current_module(M),M\=user,M\=system,M\=baseKB), (default_module(baseKB,M)->true;catch(nop(add_import_module(M,baseKB,end)),E2,dmsg(E2:add_import_module(M,baseKB,end))))). %:- on_modules_changed. %:- initialization(on_modules_changed). %% never_assert_u0( :TermARG1, ?Why) is semidet. % % Never Assert For User Code Primary Helper. % never_assert_u0(mpred_prop(F,A,pfcPosTrigger),Why):- fail, functor(P,F,A), ignore(predicate_property(M:P,exported)), defined_predicate(M:P), is_static_why(M,P,F,A,R), Why = static(M:P-F/A,R). %:- rtrace. %:- dtrace. %:- ignore(delete_import_module(baseKB,user)). %:- add_import_module(baseKB,lmcode,start). %:- nortrace. %:- quietly. % Pred='$VAR'('Pred'),unnumbervars(mpred_eval_lhs('$pt'(MZ,singleValuedInArg(Pred,_G8263654),(dtrace->rhs([{dtrace},prologSingleValued(Pred)]))),(singleValuedInArg(Pred,_G8263679),{dtrace}==>{dtrace},prologSingleValued(Pred),ax)),UN). % Pred='$VAR'('Pred'),unnumbervars(mpred_eval_lhs('$pt'(MZ,singleValuedInArg(Pred,_G8263654),(dtrace->rhs([{dtrace},prologSingleValued(Pred)]))),(singleValuedInArg(Pred,_G8263679),{dtrace}==>{dtrace},prologSingleValued(Pred),ax)),UN). %:- maybe_add_import_module(tbox,basePFC,end). %:- initialization(maybe_add_import_module(tbox,basePFC,end)). /* BAD IDEAS system:term_expansion(M1:(M2:G),(M1:G)):-atom(M1),M1==M2,!. system:goal_expansion(M1:(M2:G),(M1:G)):-atom(M1),M1==M2,!. system:sub_call_expansion(_:dynamic(_:((M:F)/A)),dynamic(M:F/A)):-atom(M),atom(F),integer(A). */ /* % :- autoload. % ([verbose(false)]). bad_thing_to_do:- doall((clause(baseKB:safe_wrap(F,A,ereq),Body), retract(( baseKB:safe_wrap(F,A,ereq):- Body )), between(0,9,A),ain((arity(F,A),pfcControlled(F),prologHybrid(F))),fail)). % :- doall((current_module(W),import_module(W,system),\+ import_module(W, user), W\==baseKB, add_import_module(lmcode,W,end))). */ :- fixup_exports.
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_base/prolog/logicmoo/typesystem/mpred_userkb.pl
Perl
mit
11,040
#!/usr/bin/perl -wl # CommonAccord - bringing the world to agreement # Written in 2014 by Primavera De Filippi To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. # You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. use warnings; use strict; my %remote; my $remote_cnt = 0; my $path = "./Doc/"; my $orig; sub parse { my($file,$root,$part) = @_; my $f; ref($file) eq "GLOB" ? $f = $file : open $f, $file or die $!; $orig = $f unless $orig; my $content = parse_root($f, $root, $part); if($content) { expand_fields($f, \$content, $part); return($content) } return; } sub parse_root { my ($f, $field, $oldpart) = @_; my $root; seek($f, 0, 0); while(<$f>) { return $root if ($root) = $_ =~ /^\Q$field\E\s*=\s*(.*?)$/; } seek($f, 0, 0); while(<$f>) { my($part,$what, $newfield); # if( (($part, $what) = $_ =~ /^([^=]*)=\[(.+?)\]/) and ($field =~ s/^\Q$part\E//) ) { if( (($part, $what) = $_ =~ /^([^=]*)=\[(.+?)\]/) and ($field =~ /^\Q$part\E/ )) { if ( $part && ($field =~ /^\Q$part\E(.+?)$/) ){ $newfield = $1;} $part = $oldpart . $part if $oldpart; if($what =~ s/^\?//) { if(! $remote{$path.$what}) { $remote_cnt++; `curl '$what' > '$path/tmp$remote_cnt.cmacc'`; $remote{$path.$what} = "$path/tmp$remote_cnt.cmacc"; } $root = parse($remote{$path.$what}, $newfield || $field, $part); } else { $root = parse($path.$what, $newfield || $field, $part); } return $root if $root; } } return $root; } sub expand_fields { my($f,$field,$part) = @_; foreach( $$field =~ /\{([^}]+)\}/g ) { my $ex = $_; my $ox = $part ? $part . $ex : $ex; my $value = parse($orig, $ox); $$field =~ s/\{\Q$ex\E\}/$value/gg if $value; } } my $output = parse($ARGV[0], "Model.Root"); # print $output; # XXX FIX ME XXX This is horrible - but I'm just dead tired :( my %seen; my @arr = $output=~/\{([^}]+)\}/g; @arr = grep { ! $seen{$_}++ } @arr; # select one: # print "$_=\n" foreach @arr; print "$_=<a href='#$_.Sec' class='definedterm'>$_</a>\n" foreach @arr; #clean up the temporary files (remote fetching) `rm $_` for values %remote;
antoinekraska/Cmacc-Paris2
vendor/cmacc-app/openedit-parser.pl
Perl
mit
2,405
sub run { my $options = shift; my $filename = $options; $filename =~ tr/[\-\ ]/_/s; $cmd_line = "cc4x86.exe $options --output-file-name ..\\..\\tests\\visual\\rasterizer\\rasterizer_$filename.asm ..\\..\\tests\\visual\\rasterizer\\rasterizer.c"; print "running '$cmd_line'...\n"; system $cmd_line; } sub assemble { my $filename = shift; chdir("../../tests/visual/rasterizer") or die("chdir: $!"); system("d:\\bin\\msvs2012\\VC\\bin\\ml /Fl /nologo $filename"); chdir("../../../../cc4x86/bin/release/") or die("chdir: $!"); } chdir("../cc4x86/bin/release/") or die("chdir: $!"); run("--xmldump --nocodegen"); run("--noregalloc"); run("--noregalloc --optimize"); run("--noregalloc --optimize --noinline"); run("--noregalloc --optimize --nocopyopt"); run("--noregalloc --nobasicopt"); run(""); run("--optimize"); run("--optimize --noinline"); run("--optimize --nocopyopt"); run("--nobasicopt"); assemble("rasterizer_.asm"); assemble("rasterizer__optimize.asm"); assemble("rasterizer__optimize_noinline.asm"); assemble("rasterizer__optimize_nocopyopt.asm"); chdir("../../tests/visual/rasterizer") or die("chdir: $!"); system("del *.lst"); system("del *.obj"); chdir("../../../../cc4x86/bin/release/") or die("chdir: $!");
artyompal/C-compiler
scripts/make_rasterizer_test.pl
Perl
mit
1,314
#!/usr/local/bin/swipl :- module(logicmoo_swish_unit, [ unit_test_file/1 ]). unit_test_file(O):-source_file_property(Source, modified(_)),unit_from_source(Source,O). unit_from_source(Source,O):- atom_concat(Source,t,O),exists_file(O). unit_from_source(Source,O):- member(T,[test,t]),atom_subst(Source,prolog,T,O),O\=Source,exists_file(O). unit_from_source(Source,O):- member(T,[test,t]),atom_subst(Source,prolog,T,M),atom_concat(M,t,O),O\=Source,exists_file(O). % unit_test_file(O):-source_file_property(Source, modified(_)),atom_concat(Source,t,O),exists_file(O). end_of_file. end_of_file. end_of_file. end_of_file. end_of_file. end_of_file. end_of_file. end_of_file. end_of_file. end_of_file. end_of_file. end_of_file. end_of_file. :- module(logicmoo_cliop, [ start_cliop/0 ]). :- use_module(library(http/thread_httpd)). :- use_module(library(http/http_dispatch)). :- use_module(library(http/http_path)). :- use_module(library(www_browser)). :- if(exists_source(library(uid))). :- use_module(library(uid)). :- endif. /** <module> Isolated startup module for ClioPatria */ :- use_module(library(must_trace)). :- multifile(owl2_model:datatype/1). :- dynamic(owl2_model:datatype/1). :- if(false). :- multifile(owl2_model:datatype/2). :- dynamic(owl2_model:datatype/2). :- meta_predicate(from_http(0)). from_http(G):- stream_property(Main_error,file_no(2)), with_output_to(Main_error, G). :- ignore((stream_property(X,file_no(2)), stream_property(X,alias(Was)), set_stream(X,alias(main_error)), set_stream(X,alias(Was)))). :- meta_predicate(from_http(0)). reexport_from(ReExporter,From:P):- From:export(From:P), ReExporter:import(From:P), ReExporter:export(From:P). :- if(exists_source(library(trill))). :- system:use_module(library(trill)). :- reexport_from(system,trill:end_bdd/1), reexport_from(system,trill:add_var/5), reexport_from(system,trill:and/4), reexport_from(system,trill:em/8), reexport_from(system,trill:randomize/1), reexport_from(system,trill:rand_seed/1), reexport_from(system,trill:or/4), reexport_from(system,trill:ret_prob/3), reexport_from(system,trill:init_test/2), reexport_from(system,trill:end/1), reexport_from(system,trill:end_test/1), reexport_from(system,trill:bdd_not/3), reexport_from(system,trill:zero/2), reexport_from(system,trill:one/2), reexport_from(system,trill:equality/4), reexport_from(system,trill:init_bdd/2), reexport_from(system,trill:init/3). :- dynamic(user:db/1). :- thread_local(user:db/1). :- use_module(library(pita),[]). % :- [pack(trill_on_swish/src/lib/authenticate)]. % :- use_module(library(r/r_sandbox)). :- use_module(library(aleph),[]). :- add_search_path_safe(swish, '/home/prologmud_server/lib/swipl/pack/swish'). :- use_module(library(cplint_r),[]). :- use_module(library(mcintyre)). :- use_module(library(slipcover)). :- use_module(library(lemur),[]). :- use_module(library(auc)). :- use_module(library(matrix)). :- use_module(library(clpr)). :- endif. :- multifile sandbox:safe_primitive/1. sandbox:safe_primitive(nf_r:{_}). :- dynamic http:location/3. :- multifile http:location/3. http:location(root, '/', [priority(1100)]). http:location(swish, root('swish'), [priority(500)]). % http:location(root, '/swish', []). :- endif. :- dmsg("CLIOP Load"). start_cliop :- dmsg("CLIOP Start"), cp_server. %:- initialization(start_cliop). /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This file provides a skeleton startup file. It can be localized by running % ./configure (Unix) % Double-clicking win-config.exe (Windows) After that, the system may be customized by copying or linking customization files from config-available to config-enabled. See config-enabled/README.txt for details. To run the system, do one of the following: * Running for development Run ./run.pl (Unix) or open run.pl by double clicking it (Windows) * Running as Unix daemon (service) See daemon.pl - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ % Setup search path for cliopatria. We add both a relative and absolute % path. The absolute path allow us to start in any directory, while the % relative one ensures that the system remains working when installed on % a device that may be mounted on a different location. add_relative_search_path(Alias, Rel):- absolute_file_name(Rel, Real,[file_type(directory),access(read),file_errors(fail)]), add_relative_search_path0(Alias, Real),!. add_relative_search_path0(Alias, Abs) :- is_absolute_file_name(Abs), exists_directory(Abs), assertz(user:file_search_path(Alias, Abs)),fail. add_relative_search_path0(Alias, Abs) :- is_absolute_file_name(Abs), prolog_load_context(file, Here), relative_file_name(Abs, Here, Rel), assertz(user:file_search_path(Alias, Rel)),fail. add_relative_search_path0(Alias, Rel) :- assertz(user:file_search_path(Alias, Rel)). % Make loading files silent. Comment if you want verbose loading. :- current_prolog_flag(verbose, Verbose), asserta(saved_verbose(Verbose)), set_prolog_flag(verbose, silent). :- add_relative_search_path(cliopatria, pack('ClioPatria')). % :- add_relative_search_path(cpacks, 'cpack'). % :- use_module(library(cplint_r)). /******************************* * LOAD CODE * *******************************/ % Use the ClioPatria help system. May be commented to disable online % help on the source-code. :- use_module(cliopatria('applications/help/load')). % Load ClioPatria itself. Better keep this line. :- use_module(cliopatria(cliopatria)). :- listing(user:file_search_path/2). % Get back normal verbosity of the toplevel. :- ( retract(saved_verbose(Verbose)) -> set_prolog_flag(verbose, Verbose) ; true ). :- if(exists_source(rdfql(sparql_csv_result))). :- use_module(rdfql(sparql_csv_result)). :- endif. cliop_restore :- app_argv('--nocliop'),!. cliop_restore :- must(start_cliop). :- initialization(cliop_restore). :- initialization(cliop_restore,now). :- initialization(cliop_restore,restore). /* :- ['./cpack/trill_on_swish/lib/trill_on_swish/storage_trill_on_swish']. :- ['./cpack/trill_on_swish/lib/trill_on_swish/gitty_trill_on_swish']. */
TeamSPoon/logicmoo_workspace
packs_web/logicmoo_webui/prolog/logicmoo_swish_unit.pl
Perl
mit
6,502
use Dancer2; get '/' => sub { 'Hello' }; __PACKAGE__->to_app;
xsawyerx/dancer-training-notes
03-syntax/02-to_app.pl
Perl
mit
64
# # 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 centreon::common::broadcom::fastpath::snmp::mode::components::fan; use strict; use warnings; my %map_fan_status = ( 1 => 'notpresent', 2 => 'operational', 3 => 'failed', 4 => 'powering', 5 => 'nopower', 6 => 'notpowering', 7 => 'incompatible' ); my $mapping = { boxServicesFanItemState => { oid => '.1.3.6.1.4.1.4413.1.1.43.1.6.1.3', map => \%map_fan_status }, boxServicesFanSpeed => { oid => '.1.3.6.1.4.1.4413.1.1.43.1.6.1.4' } }; my $oid_boxServicesFansEntry = '.1.3.6.1.4.1.4413.1.1.43.1.6.1'; sub load { my ($self) = @_; push @{$self->{request}}, { oid => $oid_boxServicesFansEntry, begin => $mapping->{boxServicesFanItemState}->{oid}, end => $mapping->{boxServicesFanSpeed}->{oid} }; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking fans"); $self->{components}->{fan} = {name => 'fans', total => 0, skip => 0}; return if ($self->check_filter(section => 'fan')); my ($exit, $warn, $crit, $checked); foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$oid_boxServicesFansEntry}})) { next if ($oid !~ /^$mapping->{boxServicesFanItemState}->{oid}\.(.*)$/); my $instance = $1; my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_boxServicesFansEntry}, instance => $instance); next if ($self->check_filter(section => 'fan', instance => $instance)); if ($result->{boxServicesFanItemState} =~ /notpresent/i) { $self->absent_problem(section => 'fan', instance => $instance); next; } $self->{components}->{fan}->{total}++; $self->{output}->output_add( long_msg => sprintf( "fan '%s' status is '%s' [instance = %s, speed = %s]", $instance, $result->{boxServicesFanItemState}, $instance, defined($result->{boxServicesFanSpeed}) ? $result->{boxServicesFanSpeed} : 'unknown' ) ); $exit = $self->get_severity(label => 'default', section => 'fan', value => $result->{boxServicesFanItemState}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add( severity => $exit, short_msg => sprintf("Fan '%s' status is '%s'", $instance, $result->{boxServicesFanItemState}) ); } next if (!defined($result->{boxServicesFanSpeed}) || $result->{boxServicesFanSpeed} !~ /[0-9]+/); ($exit, $warn, $crit, $checked) = $self->get_severity_numeric(section => 'fan', instance => $instance, value => $result->{boxServicesFanSpeed}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add( severity => $exit, short_msg => sprintf("Fan '%s' is '%s' rpm", $instance, $result->{boxServicesFanSpeed}) ); } $self->{output}->perfdata_add( nlabel => 'hardware.fan.speed.rpm', unit => 'rpm', instances => $instance, value => $result->{boxServicesFanSpeed}, warning => $warn, critical => $crit, min => 0 ); } } 1;
Tpo76/centreon-plugins
centreon/common/broadcom/fastpath/snmp/mode/components/fan.pm
Perl
apache-2.0
4,032
package Paws::ElasticTranscoder::DeletePreset; use Moose; has Id => (is => 'ro', isa => 'Str', traits => ['ParamInURI'], uri_name => 'Id', required => 1); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'DeletePreset'); class_has _api_uri => (isa => 'Str', is => 'ro', default => '/2012-09-25/presets/{Id}'); class_has _api_method => (isa => 'Str', is => 'ro', default => 'DELETE'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::ElasticTranscoder::DeletePresetResponse'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::ElasticTranscoder::DeletePreset - Arguments for method DeletePreset on Paws::ElasticTranscoder =head1 DESCRIPTION This class represents the parameters used for calling the method DeletePreset on the Amazon Elastic Transcoder service. Use the attributes of this class as arguments to method DeletePreset. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to DeletePreset. As an example: $service_obj->DeletePreset(Att1 => $value1, Att2 => $value2, ...); Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object. =head1 ATTRIBUTES =head2 B<REQUIRED> Id => Str The identifier of the preset for which you want to get detailed information. =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method DeletePreset in L<Paws::ElasticTranscoder> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/ElasticTranscoder/DeletePreset.pm
Perl
apache-2.0
1,873
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2017] 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 =pod =head1 NAME Bio::EnsEMBL::Compara::PipeConfig::ImportAltAlleGroupsAsHomologies_conf =head1 DESCRIPTION The PipeConfig file for the pipeline that imports alternative alleles as homologies. =cut package Bio::EnsEMBL::Compara::PipeConfig::ImportAltAlleGroupsAsHomologies_conf; use strict; use warnings; use base ('Bio::EnsEMBL::Hive::PipeConfig::EnsemblGeneric_conf'); sub default_options { my ($self) = @_; return { %{$self->SUPER::default_options}, 'host' => 'compara5', # where the pipeline database will be created 'pipeline_name' => 'homology_projections_'.$self->o('rel_with_suffix'), # also used to differentiate submitted processes 'reg_conf' => $self->o('ensembl_cvs_root_dir')."/ensembl-compara/scripts/pipeline/production_reg_conf.pl", #Pipeline capacities: 'import_altalleles_as_homologies_capacity' => '300', 'update_capacity' => '5', }; } sub hive_meta_table { my ($self) = @_; return { %{$self->SUPER::hive_meta_table}, # here we inherit anything from the base class 'hive_use_param_stack' => 1, # switch on the new param_stack mechanism } } sub resource_classes { my ($self) = @_; return { %{$self->SUPER::resource_classes}, # inherit 'default' from the parent class '500Mb_job' => { 'LSF' => ['-C0 -M500 -R"select[mem>500] rusage[mem=500]"', '--reg_conf '.$self->o('reg_conf')], 'LOCAL' => ['', '--reg_conf '.$self->o('reg_conf')] }, 'patch_import' => { 'LSF' => ['-C0 -M250 -R"select[mem>250] rusage[mem=250]"', '--reg_conf '.$self->o('reg_conf')], 'LOCAL' => ['', '--reg_conf '.$self->o('reg_conf')] }, 'patch_import_himem' => { 'LSF' => ['-C0 -M500 -R"select[mem>500] rusage[mem=500]"', '--reg_conf '.$self->o('reg_conf')], 'LOCAL' => ['', '--reg_conf '.$self->o('reg_conf')] }, 'default_w_reg' => { 'LSF' => ['', '--reg_conf '.$self->o('reg_conf')], 'LOCAL' => ['', '--reg_conf '.$self->o('reg_conf')] }, }; } sub pipeline_analyses { my ($self) = @_; return [ { -logic_name => 'offset_tables', -module => 'Bio::EnsEMBL::Compara::RunnableDB::GeneTrees::OffsetTables', -input_ids => [ { 'compara_db' => $self->o('compara_db'), 'db_conn' => '#compara_db#', } ], -parameters => { 'range_index' => 5, }, -flow_into => [ 'species_factory' ], }, { -logic_name => 'species_factory', -module => 'Bio::EnsEMBL::Compara::RunnableDB::GenomeDBFactory', -flow_into => { 2 => [ 'altallegroup_factory' ], }, }, { -logic_name => 'altallegroup_factory', -module => 'Bio::EnsEMBL::Compara::RunnableDB::ObjectFactory', -parameters => { 'call_list' => [ 'compara_dba', 'get_GenomeDBAdaptor', ['fetch_by_dbID', '#genome_db_id#'], 'db_adaptor', 'get_AltAlleleGroupAdaptor', 'fetch_all' ], 'column_names2getters' => { 'alt_allele_group_id' => 'dbID' }, 'reg_conf' => $self->o('reg_conf'), }, -flow_into => { '2->A' => [ 'import_altalleles_as_homologies' ], 'A->1' => [ 'update_member_display_labels' ], }, -rc_name => 'default_w_reg', }, { -logic_name => 'import_altalleles_as_homologies', -module => 'Bio::EnsEMBL::Compara::RunnableDB::ImportAltAlleGroupAsHomologies', -hive_capacity => $self->o('import_altalleles_as_homologies_capacity'), -parameters => { 'mafft_home' => '/software/ensembl/compara/mafft-7.113/', }, -flow_into => { -1 => [ 'import_altalleles_as_homologies_himem' ], # MEMLIMIT }, -rc_name => 'patch_import', }, { -logic_name => 'import_altalleles_as_homologies_himem', -module => 'Bio::EnsEMBL::Compara::RunnableDB::ImportAltAlleGroupAsHomologies', -hive_capacity => $self->o('import_altalleles_as_homologies_capacity'), -parameters => { 'mafft_home' => '/software/ensembl/compara/mafft-7.113/', }, -rc_name => 'patch_import_himem', }, { -logic_name => 'update_member_display_labels', -module => 'Bio::EnsEMBL::Compara::RunnableDB::MemberDisplayLabelUpdater', -analysis_capacity => $self->o('update_capacity'), -parameters => { 'die_if_no_core_adaptor' => 1, 'replace' => 1, 'mode' => 'display_label', 'source_name' => 'ENSEMBLGENE', 'genome_db_ids' => [ '#genome_db_id#' ], }, -flow_into => [ 'update_seq_member_display_labels' ], -rc_name => '500Mb_job', }, { -logic_name => 'update_seq_member_display_labels', -module => 'Bio::EnsEMBL::Compara::RunnableDB::MemberDisplayLabelUpdater', -analysis_capacity => $self->o('update_capacity'), -parameters => { 'die_if_no_core_adaptor' => 1, 'replace' => 1, 'mode' => 'display_label', 'source_name' => 'ENSEMBLPEP', 'genome_db_ids' => [ '#genome_db_id#' ], }, -flow_into => [ 'update_member_descriptions' ], -rc_name => '500Mb_job', }, { -logic_name => 'update_member_descriptions', -module => 'Bio::EnsEMBL::Compara::RunnableDB::MemberDisplayLabelUpdater', -analysis_capacity => $self->o('update_capacity'), -parameters => { 'die_if_no_core_adaptor' => 1, 'replace' => 1, 'mode' => 'description', 'genome_db_ids' => [ '#genome_db_id#' ], }, -rc_name => '500Mb_job', }, ]; } 1;
danstaines/ensembl-compara
modules/Bio/EnsEMBL/Compara/PipeConfig/ImportAltAlleGroupsAsHomologies_conf.pm
Perl
apache-2.0
7,104
use Test::More; use Test::Deep; use Test::Exception; use Search::Elasticsearch::Async; our $JSON_BACKEND; my $utf8_bytes = "彈性搜索"; my $utf8_str = $utf8_bytes; utf8::decode($utf8_str); my $hash = { "foo" => "$utf8_str" }; my $arr = [$hash]; my $json_hash = <<JSON; { "foo" : "$utf8_bytes" } JSON my $json_arr = <<JSON; [ { "foo" : "$utf8_bytes" } ] JSON isa_ok my $s = Search::Elasticsearch::Async->new( serializer => $JSON_BACKEND ) ->transport->serializer, "Search::Elasticsearch::Serializer::$JSON_BACKEND", 'Serializer'; # encode is_pretty( [], undef, 'Enc - No args returns undef' ); is_pretty( [undef], undef, 'Enc - Undef returns undef' ); is_pretty( [''], '', 'Enc - Empty string returns same' ); is_pretty( ['foo'], 'foo', 'Enc - String returns same' ); is_pretty( [$utf8_str], $utf8_bytes, 'Enc - Unicode string returns encoded' ); is_pretty( [$utf8_bytes], $utf8_bytes, 'Enc - Unicode bytes returns same' ); is_pretty( [$hash], $json_hash, 'Enc - Hash returns JSON' ); is_pretty( [$arr], $json_arr, 'Enc - Array returns JSON' ); throws_ok { $s->encode_pretty( \$utf8_str ) } qr/Serializer/, # 'Enc - scalar ref dies'; sub is_pretty { my ( $arg, $expect, $desc ) = @_; my $got = $s->encode_pretty(@$arg); defined $got and $got =~ s/^\s+//gm; defined $expect and $expect =~ s/^\s+//gm; is $got, $expect, $desc; } done_testing;
adjust/elasticsearch-perl
t/20_Serializer_Async/encode_pretty.pl
Perl
apache-2.0
1,497