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
/* Part of Extended Libraries for SWI-Prolog Author: Edison Mera Menendez E-mail: efmera@gmail.com WWW: https://github.com/edisonm/xlibrary Copyright (C): 2016, Process Design Center, Breda, The Netherlands. 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ :- module(safe_prolog_cut_to, [call_decreasing_cp/2, fix_choice/3, safe_prolog_cut_to/1, safe_prolog_cut_to/3 ]). :- meta_predicate call_decreasing_cp(0, ?). safe_prolog_cut_to(CP) :- prolog_current_choice(CPC), safe_prolog_cut_to(CPC, CP, _). safe_prolog_cut_to(CPC, CP, CPF) :- fix_choice(CPC, CP, CPF), prolog_cut_to(CPF). fix_choice(CPC, CP, CPC) :- CPC =< CP, !. fix_choice(CPC, CP, CPF) :- prolog_choice_attribute(CPC, parent, CPP), fix_choice(CPP, CP, CPF). :- thread_local decreasing_cp_db/2. call_decreasing_cp(Call, Arg) :- variant_sha1(Arg, H1), prolog_current_choice(CP1), setup_call_cleanup( assertz(decreasing_cp_db(H1, CP1)), do_call_decreasing_cp(Call, Arg), retractall(decreasing_cp_db(_, _))). do_call_decreasing_cp(Call, Arg) :- ( call(Call), prolog_current_choice(CP2), variant_sha1(Arg, H2), ( clause(decreasing_cp_db(H2, CP), _, Ref), CP2 > CP ->erase(Ref), safe_prolog_cut_to(CP2, CP, CPN) ; CPN = CP2 ), assertz(decreasing_cp_db(H2, CPN)) ).
TeamSPoon/logicmoo_workspace
packs_lib/xlibrary/prolog/safe_prolog_cut_to.pl
Perl
mit
2,775
package eapearson_TestRichReports::eapearson_TestRichReportsClient; use JSON::RPC::Client; use POSIX; use strict; use Data::Dumper; use URI; use Bio::KBase::Exceptions; my $get_time = sub { time, 0 }; eval { require Time::HiRes; $get_time = sub { Time::HiRes::gettimeofday() }; }; use Bio::KBase::AuthToken; # Client version should match Impl version # This is a Semantic Version number, # http://semver.org our $VERSION = "0.1.0"; =head1 NAME eapearson_TestRichReports::eapearson_TestRichReportsClient =head1 DESCRIPTION A KBase module: eapearson_TestRichReports This sample module contains one small method - filter_contigs. =cut sub new { my($class, $url, @args) = @_; my $self = { client => eapearson_TestRichReports::eapearson_TestRichReportsClient::RpcClient->new, url => $url, headers => [], }; chomp($self->{hostname} = `hostname`); $self->{hostname} ||= 'unknown-host'; # # Set up for propagating KBRPC_TAG and KBRPC_METADATA environment variables through # to invoked services. If these values are not set, we create a new tag # and a metadata field with basic information about the invoking script. # if ($ENV{KBRPC_TAG}) { $self->{kbrpc_tag} = $ENV{KBRPC_TAG}; } else { my ($t, $us) = &$get_time(); $us = sprintf("%06d", $us); my $ts = strftime("%Y-%m-%dT%H:%M:%S.${us}Z", gmtime $t); $self->{kbrpc_tag} = "C:$0:$self->{hostname}:$$:$ts"; } push(@{$self->{headers}}, 'Kbrpc-Tag', $self->{kbrpc_tag}); if ($ENV{KBRPC_METADATA}) { $self->{kbrpc_metadata} = $ENV{KBRPC_METADATA}; push(@{$self->{headers}}, 'Kbrpc-Metadata', $self->{kbrpc_metadata}); } if ($ENV{KBRPC_ERROR_DEST}) { $self->{kbrpc_error_dest} = $ENV{KBRPC_ERROR_DEST}; push(@{$self->{headers}}, 'Kbrpc-Errordest', $self->{kbrpc_error_dest}); } # # This module requires authentication. # # We create an auth token, passing through the arguments that we were (hopefully) given. { my $token = Bio::KBase::AuthToken->new(@args); if (!$token->error_message) { $self->{token} = $token->token; $self->{client}->{token} = $token->token; } else { # # All methods in this module require authentication. In this case, if we # don't have a token, we can't continue. # die "Authentication failed: " . $token->error_message; } } my $ua = $self->{client}->ua; my $timeout = $ENV{CDMI_TIMEOUT} || (30 * 60); $ua->timeout($timeout); bless $self, $class; # $self->_validate_version(); return $self; } =head2 generate_report $return = $obj->generate_report($params) =over 4 =item Parameter and return types =begin html <pre> $params is an eapearson_TestRichReports.GenerateReportParams $return is an eapearson_TestRichReports.GenerateReportResults GenerateReportParams is a reference to a hash where the following keys are defined: workspace has a value which is a string direct_html has a value which is a string message has a value which is a string report_index has a value which is an int html_window_height has a value which is a float summary_window_height has a value which is a float html_files has a value which is a reference to a list where each element is an eapearson_TestRichReports.ListItem files has a value which is a reference to a list where each element is an eapearson_TestRichReports.ListItem ListItem is a reference to a hash where the following keys are defined: shock_id has a value which is a string index_name has a value which is a string label has a value which is a string description has a value which is a string GenerateReportResults is a reference to a hash where the following keys are defined: report_name has a value which is a string report_ref has a value which is a string </pre> =end html =begin text $params is an eapearson_TestRichReports.GenerateReportParams $return is an eapearson_TestRichReports.GenerateReportResults GenerateReportParams is a reference to a hash where the following keys are defined: workspace has a value which is a string direct_html has a value which is a string message has a value which is a string report_index has a value which is an int html_window_height has a value which is a float summary_window_height has a value which is a float html_files has a value which is a reference to a list where each element is an eapearson_TestRichReports.ListItem files has a value which is a reference to a list where each element is an eapearson_TestRichReports.ListItem ListItem is a reference to a hash where the following keys are defined: shock_id has a value which is a string index_name has a value which is a string label has a value which is a string description has a value which is a string GenerateReportResults is a reference to a hash where the following keys are defined: report_name has a value which is a string report_ref has a value which is a string =end text =item Description Filter contigs in a ContigSet by DNA length =back =cut sub generate_report { my($self, @args) = @_; # Authentication: required if ((my $n = @args) != 1) { Bio::KBase::Exceptions::ArgumentValidationError->throw(error => "Invalid argument count for function generate_report (received $n, expecting 1)"); } { my($params) = @args; my @_bad_arguments; (ref($params) eq 'HASH') or push(@_bad_arguments, "Invalid type for argument 1 \"params\" (value was \"$params\")"); if (@_bad_arguments) { my $msg = "Invalid arguments passed to generate_report:\n" . join("", map { "\t$_\n" } @_bad_arguments); Bio::KBase::Exceptions::ArgumentValidationError->throw(error => $msg, method_name => 'generate_report'); } } my $url = $self->{url}; my $result = $self->{client}->call($url, $self->{headers}, { method => "eapearson_TestRichReports.generate_report", params => \@args, }); if ($result) { if ($result->is_error) { Bio::KBase::Exceptions::JSONRPC->throw(error => $result->error_message, code => $result->content->{error}->{code}, method_name => 'generate_report', data => $result->content->{error}->{error} # JSON::RPC::ReturnObject only supports JSONRPC 1.1 or 1.O ); } else { return wantarray ? @{$result->result} : $result->result->[0]; } } else { Bio::KBase::Exceptions::HTTP->throw(error => "Error invoking method generate_report", status_line => $self->{client}->status_line, method_name => 'generate_report', ); } } sub status { my($self, @args) = @_; if ((my $n = @args) != 0) { Bio::KBase::Exceptions::ArgumentValidationError->throw(error => "Invalid argument count for function status (received $n, expecting 0)"); } my $url = $self->{url}; my $result = $self->{client}->call($url, $self->{headers}, { method => "eapearson_TestRichReports.status", params => \@args, }); if ($result) { if ($result->is_error) { Bio::KBase::Exceptions::JSONRPC->throw(error => $result->error_message, code => $result->content->{error}->{code}, method_name => 'status', data => $result->content->{error}->{error} # JSON::RPC::ReturnObject only supports JSONRPC 1.1 or 1.O ); } else { return wantarray ? @{$result->result} : $result->result->[0]; } } else { Bio::KBase::Exceptions::HTTP->throw(error => "Error invoking method status", status_line => $self->{client}->status_line, method_name => 'status', ); } } sub version { my ($self) = @_; my $result = $self->{client}->call($self->{url}, $self->{headers}, { method => "eapearson_TestRichReports.version", params => [], }); if ($result) { if ($result->is_error) { Bio::KBase::Exceptions::JSONRPC->throw( error => $result->error_message, code => $result->content->{code}, method_name => 'generate_report', ); } else { return wantarray ? @{$result->result} : $result->result->[0]; } } else { Bio::KBase::Exceptions::HTTP->throw( error => "Error invoking method generate_report", status_line => $self->{client}->status_line, method_name => 'generate_report', ); } } sub _validate_version { my ($self) = @_; my $svr_version = $self->version(); my $client_version = $VERSION; my ($cMajor, $cMinor) = split(/\./, $client_version); my ($sMajor, $sMinor) = split(/\./, $svr_version); if ($sMajor != $cMajor) { Bio::KBase::Exceptions::ClientServerIncompatible->throw( error => "Major version numbers differ.", server_version => $svr_version, client_version => $client_version ); } if ($sMinor < $cMinor) { Bio::KBase::Exceptions::ClientServerIncompatible->throw( error => "Client minor version greater than Server minor version.", server_version => $svr_version, client_version => $client_version ); } if ($sMinor > $cMinor) { warn "New client version available for eapearson_TestRichReports::eapearson_TestRichReportsClient\n"; } if ($sMajor == 0) { warn "eapearson_TestRichReports::eapearson_TestRichReportsClient version is $svr_version. API subject to change.\n"; } } =head1 TYPES =head2 ListItem =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: shock_id has a value which is a string index_name has a value which is a string label has a value which is a string description has a value which is a string </pre> =end html =begin text a reference to a hash where the following keys are defined: shock_id has a value which is a string index_name has a value which is a string label has a value which is a string description has a value which is a string =end text =back =head2 GenerateReportParams =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: workspace has a value which is a string direct_html has a value which is a string message has a value which is a string report_index has a value which is an int html_window_height has a value which is a float summary_window_height has a value which is a float html_files has a value which is a reference to a list where each element is an eapearson_TestRichReports.ListItem files has a value which is a reference to a list where each element is an eapearson_TestRichReports.ListItem </pre> =end html =begin text a reference to a hash where the following keys are defined: workspace has a value which is a string direct_html has a value which is a string message has a value which is a string report_index has a value which is an int html_window_height has a value which is a float summary_window_height has a value which is a float html_files has a value which is a reference to a list where each element is an eapearson_TestRichReports.ListItem files has a value which is a reference to a list where each element is an eapearson_TestRichReports.ListItem =end text =back =head2 GenerateReportResults =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: report_name has a value which is a string report_ref has a value which is a string </pre> =end html =begin text a reference to a hash where the following keys are defined: report_name has a value which is a string report_ref has a value which is a string =end text =back =cut package eapearson_TestRichReports::eapearson_TestRichReportsClient::RpcClient; use base 'JSON::RPC::Client'; use POSIX; use strict; # # Override JSON::RPC::Client::call because it doesn't handle error returns properly. # sub call { my ($self, $uri, $headers, $obj) = @_; my $result; { if ($uri =~ /\?/) { $result = $self->_get($uri); } else { Carp::croak "not hashref." unless (ref $obj eq 'HASH'); $result = $self->_post($uri, $headers, $obj); } } my $service = $obj->{method} =~ /^system\./ if ( $obj ); $self->status_line($result->status_line); if ($result->is_success) { return unless($result->content); # notification? if ($service) { return JSON::RPC::ServiceObject->new($result, $self->json); } return JSON::RPC::ReturnObject->new($result, $self->json); } elsif ($result->content_type eq 'application/json') { return JSON::RPC::ReturnObject->new($result, $self->json); } else { return; } } sub _post { my ($self, $uri, $headers, $obj) = @_; my $json = $self->json; $obj->{version} ||= $self->{version} || '1.1'; if ($obj->{version} eq '1.0') { delete $obj->{version}; if (exists $obj->{id}) { $self->id($obj->{id}) if ($obj->{id}); # if undef, it is notification. } else { $obj->{id} = $self->id || ($self->id('JSON::RPC::Client')); } } else { # $obj->{id} = $self->id if (defined $self->id); # Assign a random number to the id if one hasn't been set $obj->{id} = (defined $self->id) ? $self->id : substr(rand(),2); } my $content = $json->encode($obj); $self->ua->post( $uri, Content_Type => $self->{content_type}, Content => $content, Accept => 'application/json', @$headers, ($self->{token} ? (Authorization => $self->{token}) : ()), ); } 1;
eapearson/eapearson_TestRichReports
lib/eapearson_TestRichReports/eapearson_TestRichReportsClient.pm
Perl
mit
13,915
not_a(c). not_a(d). not_a(e). not_a(f). not_a(g). not_a(h). not_a(i). not_a(k). not_a(l). not_a(m). not_a(n). not_a(p). not_a(q). not_a(r). not_a(s). not_a(t). not_a(v). not_a(w). not_a(y). not_c(a). not_c(d). not_c(e). not_c(f). not_c(g). not_c(h). not_c(i). not_c(k). not_c(l). not_c(m). not_c(n). not_c(p). not_c(q). not_c(r). not_c(s). not_c(t). not_c(v). not_c(w). not_c(y). not_d(a). not_d(c). not_d(e). not_d(f). not_d(g). not_d(h). not_d(i). not_d(k). not_d(l). not_d(m). not_d(n). not_d(p). not_d(q). not_d(r). not_d(s). not_d(t). not_d(v). not_d(w). not_d(y). not_e(a). not_e(c). not_e(d). not_e(f). not_e(g). not_e(h). not_e(i). not_e(k). not_e(l). not_e(m). not_e(n). not_e(p). not_e(q). not_e(r). not_e(s). not_e(t). not_e(v). not_e(w). not_e(y). not_f(a). not_f(c). not_f(d). not_f(e). not_f(g). not_f(h). not_f(i). not_f(k). not_f(l). not_f(m). not_f(n). not_f(p). not_f(q). not_f(r). not_f(s). not_f(t). not_f(v). not_f(w). not_f(y). not_g(a). not_g(c). not_g(d). not_g(e). not_g(f). not_g(h). not_g(i). not_g(k). not_g(l). not_g(m). not_g(n). not_g(p). not_g(q). not_g(r). not_g(s). not_g(t). not_g(v). not_g(w). not_g(y). not_h(a). not_h(c). not_h(d). not_h(e). not_h(f). not_h(g). not_h(i). not_h(k). not_h(l). not_h(m). not_h(n). not_h(p). not_h(q). not_h(r). not_h(s). not_h(t). not_h(v). not_h(w). not_h(y). not_i(a). not_i(c). not_i(d). not_i(e). not_i(f). not_i(g). not_i(h). not_i(k). not_i(l). not_i(m). not_i(n). not_i(p). not_i(q). not_i(r). not_i(s). not_i(t). not_i(v). not_i(w). not_i(y). not_k(a). not_k(c). not_k(d). not_k(e). not_k(f). not_k(g). not_k(h). not_k(i). not_k(l). not_k(m). not_k(n). not_k(p). not_k(q). not_k(r). not_k(s). not_k(t). not_k(v). not_k(w). not_k(y). not_l(a). not_l(c). not_l(d). not_l(e). not_l(f). not_l(g). not_l(h). not_l(i). not_l(k). not_l(m). not_l(n). not_l(p). not_l(q). not_l(r). not_l(s). not_l(t). not_l(v). not_l(w). not_l(y). not_m(a). not_m(c). not_m(d). not_m(e). not_m(f). not_m(g). not_m(h). not_m(i). not_m(k). not_m(l). not_m(n). not_m(p). not_m(q). not_m(r). not_m(s). not_m(t). not_m(v). not_m(w). not_m(y). not_n(a). not_n(c). not_n(d). not_n(e). not_n(f). not_n(g). not_n(h). not_n(i). not_n(k). not_n(l). not_n(m). not_n(p). not_n(q). not_n(r). not_n(s). not_n(t). not_n(v). not_n(w). not_n(y). not_p(a). not_p(c). not_p(d). not_p(e). not_p(f). not_p(g). not_p(h). not_p(i). not_p(k). not_p(l). not_p(m). not_p(n). not_p(q). not_p(r). not_p(s). not_p(t). not_p(v). not_p(w). not_p(y). not_q(a). not_q(c). not_q(d). not_q(e). not_q(f). not_q(g). not_q(h). not_q(i). not_q(k). not_q(l). not_q(m). not_q(n). not_q(p). not_q(r). not_q(s). not_q(t). not_q(v). not_q(w). not_q(y). not_r(a). not_r(c). not_r(d). not_r(e). not_r(f). not_r(g). not_r(h). not_r(i). not_r(k). not_r(l). not_r(m). not_r(n). not_r(p). not_r(q). not_r(s). not_r(t). not_r(v). not_r(w). not_r(y). not_s(a). not_s(c). not_s(d). not_s(e). not_s(f). not_s(g). not_s(h). not_s(i). not_s(k). not_s(l). not_s(m). not_s(n). not_s(p). not_s(q). not_s(r). not_s(t). not_s(v). not_s(w). not_s(y). not_s(a). not_s(c). not_s(d). not_s(e). not_s(f). not_s(g). not_s(h). not_s(i). not_s(k). not_s(l). not_s(m). not_s(n). not_s(p). not_s(q). not_s(r). not_s(s). not_s(v). not_s(w). not_s(y). not_v(a). not_v(c). not_v(d). not_v(e). not_v(f). not_v(g). not_v(h). not_v(i). not_v(k). not_v(l). not_v(m). not_v(n). not_v(p). not_v(q). not_v(r). not_v(s). not_v(t). not_v(w). not_v(y). not_w(a). not_w(c). not_w(d). not_w(e). not_w(f). not_w(g). not_w(h). not_w(i). not_w(k). not_w(l). not_w(m). not_w(n). not_w(p). not_w(q). not_w(r). not_w(s). not_w(t). not_w(v). not_w(y). not_y(a). not_y(c). not_y(d). not_y(e). not_y(f). not_y(g). not_y(h). not_y(i). not_y(k). not_y(l). not_y(m). not_y(n). not_y(p). not_y(q). not_y(r). not_y(s). not_y(t). not_y(v). not_y(w).
JoseCSantos/GILPS
datasets/proteins/nclasses.pl
Perl
mit
3,819
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 12.1.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. Use Unicode::UCD to access the Unicode character data # base. return <<'END'; V28 2689 2692 2693 2702 2703 2706 2707 2729 2730 2737 2738 2740 2741 2746 2748 2758 2759 2762 2763 2766 2768 2769 2784 2788 2790 2802 2809 2816 END
operepo/ope
client_tools/svc/rc/usr/share/perl5/core_perl/unicore/lib/Sc/Gujr.pl
Perl
mit
631
#!/usr/bin/perl # ##################################################### # LaTeX 2 PNG Interface # uses the free texvc script from wikimedia.org # (c) 2006 by Christian "metax." Simon # ##################################################### # Include CGI Lib use CGI qw(:standard); use CGI::Carp qw(fatalsToBrowser); use strict; # Environment constants ###################### # Please change to this fit your server my $_texpaste_root = '/your/path/to/texpaste'; # Edited by the author my $_default_tex_code = 'f(x):=x^2'; # End Environment ############################ chdir($_texpaste_root); # Example LaTeX Code. my $texcode = $_default_tex_code; # Pushed some texcode via GET ? if(param("texcode")) { $texcode = param("texcode") } # HTTP Header print "Content-Type: text/html;\n\n"; # HTML Header print <<"HEAD"; <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="de"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>LaTeX to PNG</title> </head> <body> <h1>LaTeX to PNG Converter</h1> <h2>Einfach LaTeX Code eingeben und Bildadresse des Ergebnis kopieren. Hotlinking erlaubt.</h2> <form action="index.cgi" method="get"> <textarea name="texcode" rows="10" cols="60"> HEAD print $texcode; print <<"MID"; </textarea><br /> <input type="submit" value="Tex2PNG" /> </form><br /><br /> MID # Run texvc Script (Syntax 'texvc $temporary_folder $save_images_to "$latex_code" $charset') # Temporary folder and images folder must be writeable by apache/CGI my $cmdtexcode = $texcode; $cmdtexcode =~ s/[\n\r]/ /gs; $cmdtexcode =~ s/\\/\\\\/gs; $_ = `/usr/local/bin/texvc tmp/ images/ \"$cmdtexcode\" utf-8`; # Extract hash: look for status code and md5 hash m/^.([0-9a-f]{32})/s; my $idm = $1; # print Result if(-e "images/$idm.png") { print "Ergebnis: <img src=\"images/$idm.png\" alt=\"PNG Ergebnis\" style=\"margin-left: 2em;\" /><br /><br />\nLink: <code>http://www.planet-metax.de/texpaste/images/$idm.png</code><br /><br />\nForum Code: <code>[IMG]http://www.planet-metax.de/texpaste/images/$idm.png[/IMG]</code>"; } else { print "Ergebnis: Fehler! (OUTPUT: $_ )<br />"; /^S$/ and print "Syntax Error!"; /^E$/ and print "Lexing Error"; /^F(.*)$/ and print "Unknown Function &bdquo;$1&ldquo;."; } print <<"END"; <address style="font-size: 80%; margin-top: 2em;"><a href="index.txt">(Sourcecode)</a></address> </body> </html> <!-- (c) 2006 by Christian Simon --> END
metaxmx/latex2png
index.pl
Perl
apache-2.0
2,534
# # Copyright 2014 MongoDB, Inc. # # 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 MongoDB::Op::_Update; # Encapsulate an update operation; returns a MongoDB::UpdateResult use version; our $VERSION = 'v1.1.0'; use Moo; use MongoDB::BSON; use MongoDB::UpdateResult; use MongoDB::_Constants; use MongoDB::_Protocol; use MongoDB::_Types qw( Document ); use Types::Standard qw( Bool Str ); use Tie::IxHash; use boolean; use namespace::clean; has db_name => ( is => 'ro', required => 1, isa => Str, ); has coll_name => ( is => 'ro', required => 1, isa => Str, ); has full_name => ( is => 'ro', required => 1, isa => Str, ); has filter => ( is => 'ro', required => 1, isa => Document, ); has update => ( is => 'ro', required => 1, ); has is_replace => ( is => 'ro', required => 1, isa => Bool, ); has multi => ( is => 'ro', required => 1, isa => Bool, ); has upsert => ( is => 'ro', required => 1, isa => Bool, ); with $_ for qw( MongoDB::Role::_PrivateConstructor MongoDB::Role::_WriteOp MongoDB::Role::_UpdatePreEncoder ); # cached my ($true, $false) = (true, false); sub execute { my ( $self, $link ) = @_; my $orig_op = { q => ( ref( $self->filter ) eq 'ARRAY' ? { @{ $self->filter } } : $self->filter ), u => $self->update, multi => $self->multi ? $true : $false, upsert => $self->upsert ? $true : $false, }; return $link->does_write_commands ? ( $self->_send_write_command( $link, [ update => $self->coll_name, updates => [ { %$orig_op, u => $self->_pre_encode_update( $link, $orig_op->{u}, $self->is_replace ), } ], writeConcern => $self->write_concern->as_struct, ], $orig_op, "MongoDB::UpdateResult" )->assert ) : ( $self->_send_legacy_op_with_gle( $link, MongoDB::_Protocol::write_update( $self->full_name, $self->bson_codec->encode_one( $orig_op->{q}, { invalid_chars => '' } ), $self->_pre_encode_update( $link, $orig_op->{u}, $self->is_replace )->{bson}, { upsert => $orig_op->{upsert}, multi => $orig_op->{multi}, }, ), $orig_op, "MongoDB::UpdateResult" )->assert ); } sub _parse_cmd { my ( $self, $res ) = @_; return ( matched_count => ($res->{n} || 0) - @{ $res->{upserted} || [] }, modified_count => $res->{nModified}, upserted_id => $res->{upserted} ? $res->{upserted}[0]{_id} : undef, ); } sub _parse_gle { my ( $self, $res, $orig_doc ) = @_; # For 2.4 and earlier, 'upserted' has _id only if the _id is an OID. # Otherwise, we have to pick it out of the update document or query # document when we see updateExisting is false but the number of docs # affected is 1 my $upserted = $res->{upserted}; if (! defined( $upserted ) && exists( $res->{updatedExisting} ) && !$res->{updatedExisting} && $res->{n} == 1 ) { $upserted = _find_id( $orig_doc->{u} ); $upserted = _find_id( $orig_doc->{q} ) unless defined $upserted; } return ( matched_count => ($upserted ? 0 : $res->{n} || 0), modified_count => undef, upserted_id => $upserted, ); } sub _find_id { my ($doc) = @_; my $type = ref($doc); return ( $type eq 'HASH' ? $doc->{_id} : $type eq 'ARRAY' ? do { my $i; for ( $i = 0; $i < @$doc; $i++ ) { last if $doc->[$i] eq '_id' } $i < $#$doc ? $doc->[ $i + 1 ] : undef; } : $type eq 'Tie::IxHash' ? $doc->FETCH('_id') : $doc->{_id} # hashlike? ); } 1;
gormanb/mongo-perl-driver
lib/MongoDB/Op/_Update.pm
Perl
apache-2.0
4,665
package Paws::StepFunctions::StateMachineListItem; use Moose; has CreationDate => (is => 'ro', isa => 'Str', request_name => 'creationDate', traits => ['NameInRequest'], required => 1); has Name => (is => 'ro', isa => 'Str', request_name => 'name', traits => ['NameInRequest'], required => 1); has StateMachineArn => (is => 'ro', isa => 'Str', request_name => 'stateMachineArn', traits => ['NameInRequest'], required => 1); 1; ### main pod documentation begin ### =head1 NAME Paws::StepFunctions::StateMachineListItem =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::StepFunctions::StateMachineListItem object: $service_obj->Method(Att1 => { CreationDate => $value, ..., StateMachineArn => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::StepFunctions::StateMachineListItem object: $result = $service_obj->Method(...); $result->Att1->CreationDate =head1 DESCRIPTION This class has no description =head1 ATTRIBUTES =head2 B<REQUIRED> CreationDate => Str The date the state machine was created. =head2 B<REQUIRED> Name => Str The name of the state machine. =head2 B<REQUIRED> StateMachineArn => Str The Amazon Resource Name (ARN) that identifies the state machine. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::StepFunctions> =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/StepFunctions/StateMachineListItem.pm
Perl
apache-2.0
1,857
# Copyright 2015 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::centreon::map::jmx::mode::elements; 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 => { "warning:s" => { name => 'warning', }, "critical:s" => { name => 'critical', }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); $self->{output}->option_exit(); } } sub run { my ($self, %options) = @_; # $options{snmp} = snmp object $self->{connector} = $options{custom}; $self->{request} = [ { mbean => "com.centreon.studio.map:name=BusinessElement,type=repo" } ]; my $result = $self->{connector}->get_attributes(request => $self->{request}, nothing_quit => 1); my $elements = $result->{"com.centreon.studio.map:name=BusinessElement,type=repo"}->{LoadedModelCount}; my $exit = $self->{perfdata}->threshold_check(value => $elements, threshold => [ { label => 'critical', exit_litteral => 'critical' }, { label => 'warning', exit_litteral => 'warning'} ]); $self->{output}->output_add(severity => $exit, short_msg => sprintf("Element loaded : %d", $result->{"com.centreon.studio.map:name=BusinessElement,type=repo"}->{LoadedModelCount})); $self->{output}->perfdata_add(label => 'elements', value => $result->{"com.centreon.studio.map:name=BusinessElement,type=repo"}->{LoadedModelCount}, warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), min => 0); $self->{output}->display(); $self->{output}->exit(); } 1; __END__ =head1 MODE Check Centreon Map Open Gates Example: perl centreon_plugins.pl --plugin=apps::centreon::map::jmx::plugin --custommode=jolokia --url=http://10.30.2.22:8080/jolokia-war --mode=elements =over 8 =item B<--warning> Set this threshold if you want a warning if opened gates match condition =item B<--critical> Set this threshold if you want a warning if opened gates match condition =back =cut
bcournaud/centreon-plugins
apps/centreon/map/jmx/mode/elements.pm
Perl
apache-2.0
3,934
package Paws::StepFunctions::StateExitedEventDetails; use Moose; has Name => (is => 'ro', isa => 'Str', request_name => 'name', traits => ['NameInRequest'], required => 1); has Output => (is => 'ro', isa => 'Str', request_name => 'output', traits => ['NameInRequest']); 1; ### main pod documentation begin ### =head1 NAME Paws::StepFunctions::StateExitedEventDetails =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::StepFunctions::StateExitedEventDetails object: $service_obj->Method(Att1 => { Name => $value, ..., Output => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::StepFunctions::StateExitedEventDetails object: $result = $service_obj->Method(...); $result->Att1->Name =head1 DESCRIPTION This class has no description =head1 ATTRIBUTES =head2 B<REQUIRED> Name => Str The name of the state. =head2 Output => Str The JSON output data of the state. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::StepFunctions> =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/StepFunctions/StateExitedEventDetails.pm
Perl
apache-2.0
1,541
false :- main_verifier_error. verifier_error(A,B,C) :- A=0, B=0, C=0. verifier_error(A,B,C) :- A=0, B=1, C=1. verifier_error(A,B,C) :- A=1, B=0, C=1. verifier_error(A,B,C) :- A=1, B=1, C=1. id(A,B,C,D,E) :- A=1, B=1, C=1. id(A,B,C,D,E) :- A=0, B=1, C=1. id(A,B,C,D,E) :- A=0, B=0, C=0. id__1(A) :- true. id___0(A,B) :- id__1(B), B=0, A=0. id__3(A) :- id__1(A), A<0. id__3(A) :- id__1(A), A>0. id___0(A,B) :- id__3(B), id(1,0,0,B+ -1,C), A=C+1. id__split(A,B) :- id___0(A,B). id(A,B,C,D,E) :- A=1, B=0, C=0, id__split(E,D). main_entry :- true. main__un :- main_entry, id(1,0,0,A,B), B=3. main_verifier_error :- main__un.
bishoksan/RAHFT
benchmarks_scp/SVCOMP15/svcomp15-clp/id_o3_false-unreach-call.c.pl
Perl
apache-2.0
750
# # 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 cloud::azure::database::sqlmanagedinstance::mode::health; use base qw(cloud::azure::management::monitor::mode::health); use strict; use warnings; sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); $self->{az_resource_namespace} = 'Microsoft.Sql'; $self->{az_resource_type} = 'managedInstances'; } 1; __END__ =head1 MODE Check Azure SQL Managed Instance health status. =over 8 =item B<--resource> Set resource name or id (Required). =item B<--resource-group> Set resource group (Required if resource's name is used). =item B<--warning-status> Set warning threshold for status (Default: ''). Special variables that can be used: %{status}, %{summary}. =item B<--critical-status> Set critical threshold for status (Default: '%{status} =~ /^Unavailable$/'). Special variables that can be used: %{status}, %{summary}. =item B<--unknown-status> Set unknown threshold for status (Default: '%{status} =~ /^Unknown$/'). Special variables that can be used: %{status}, %{summary}. =item B<--ok-status> Set ok threshold for status (Default: '%{status} =~ /^Available$/'). Special variables that can be used: %{status}, %{summary}. =back =cut
centreon/centreon-plugins
cloud/azure/database/sqlmanagedinstance/mode/health.pm
Perl
apache-2.0
1,971
# $Id: 98_PID20.pm 7089 2014-11-29 10:58:10Z john99sr $ #################################################################################################### # # 98_PID20.pm # The PID device is a loop controller, used to set the value e.g of a heating # valve dependent of the current and desired temperature. # # This module is derived from the contrib/99_PID by Alexander Titzel. # The framework of the module is derived from proposals by betateilchen. # # This file is part of fhem. # # Fhem 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. # # Fhem 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 General Public License # along with fhem. If not, see <http://www.gnu.org/licenses/>. # # # V 1.00.c # 03.12.2013 - bugfix : pidActorLimitUpper wrong assignment # V 1.00.d # 09.12.2013 - verbose-level adjusted # 20.12.2013 - bugfix: actorErrorPos: wrong assignment by pidCalcInterval-attribute, if defined # V 1.00.e # 01.01.2014 - fix: {helper}{actorCommand} assigned to an emptry string if not defined # V 1.00.f # 22.01.2014 fix:pidDeltaTreshold only int was assignable, now even float # V 1.00.g # 29.01.2014 fix:calculation of i-portion is independent from pidCalcInterval # V 1.00.h # 26.02.2014 fix:new logging format; adjusting verbose-levels # # 26.03.2014 (betateilchen) # code review, pod added, removed old version info (will be provided via SVN) # V 1.01 # 19.10.2014 fix in sub PID20_Set : wrong parameter $hash instead of $name, when calling PID20_Calc # V 1.0.0.2 30.10.14 - fix in PID20_Calc when setting $retStr (thanks to Thorsten Pferdekaemper) # V 1.0.0.3 # 20.11.2014 Bug: processing of D-Portion and handling of disable # V 1.0.0.4 # 27.11.2014 Change: all readings are updated cyclically #################################################################################################### package main; use strict; use warnings; use feature qw/say switch/; use vars qw(%defs); use vars qw($readingFnAttributes); use vars qw(%attr); use vars qw(%modules); my $PID20_Version = "1.0.0.4"; sub PID20_Calc($); ######################################## sub PID20_Log($$$) { my ( $hash, $loglevel, $text ) = @_; my $xline = ( caller(0) )[2]; my $xsubroutine = ( caller(1) )[3]; my $sub = ( split( ':', $xsubroutine ) )[2]; $sub = substr( $sub, 6 ); # without PID20 my $instName = ( ref($hash) eq "HASH" ) ? $hash->{NAME} : "PID20"; Log3 $hash, $loglevel, "PID20 $instName: $sub.$xline " . $text; } ######################################## sub PID20_Initialize($) { my ($hash) = @_; $hash->{DefFn} = "PID20_Define"; $hash->{UndefFn} = "PID20_Undef"; $hash->{SetFn} = "PID20_Set"; $hash->{GetFn} = "PID20_Get"; $hash->{NotifyFn} = "PID20_Notify"; $hash->{AttrList} = "pidActorValueDecPlaces:0,1,2,3,4,5 " . "pidActorInterval " . "pidActorTreshold " . "pidActorErrorAction:freeze,errorPos " . "pidActorErrorPos " . "pidActorKeepAlive " . "pidActorLimitLower " . "pidActorLimitUpper " . "pidCalcInterval " . "pidDeltaTreshold " . "pidDesiredName " . "pidFactor_P " . "pidFactor_I " . "pidFactor_D " . "pidMeasuredName " . "pidSensorTimeout " . "pidReverseAction " . "pidUpdateInterval " # . "pidDebugEnable:0,1 "; . "pidDebugSensor:0,1 " . "pidDebugActuation:0,1 " . "pidDebugCalc:0,1 " . "pidDebugDelta:0,1 " . "pidDebugUpdate:0,1 " . "pidDebugNotify:0,1 " . "disable:0,1 " . $readingFnAttributes; } ######################################## sub PID20_TimeDiff($) { my ($strTS) = @_; #my ( $package, $filename, $line ) = caller(0); #print "PID $strTS line $line \n"; my $serTS = ( defined($strTS) && $strTS ne "" ) ? time_str2num($strTS) : gettimeofday(); my $timeDiff = gettimeofday() - $serTS; $timeDiff = 0 if ( $timeDiff < 0 ); return $timeDiff; } ######################################## sub PID20_Define($$$) { my ( $hash, $def ) = @_; my @a = split( "[ \t][ \t]*", $def ); my $name = $a[0]; my $reFloat = '^([\\+,\\-]?\\d+\\.?\d*$)'; # gleitpunkt if ( @a != 4 ) { return "wrong syntax: define <name> PID20 " . "<sensor>:reading:[regexp] <actor>[:cmd] "; } ################### # Sensor my ( $sensor, $reading, $regexp ) = split( ":", $a[2], 3 ); # if sensor unkonwn if ( !$defs{$sensor} ) { my $msg = "$name: Unknown sensor device $sensor specified"; PID20_Log $hash, 1, $msg; return $msg; } # if reading of sender is unkown if ( ReadingsVal( $sensor, $reading, 'unknown' ) eq 'unkown' ) { my $msg = "$name: Unknown reading $reading for sensor device $sensor specified"; PID20_Log $hash, 1, $msg; return $msg; } $hash->{helper}{sensor} = $sensor; # defaults for regexp if ( !$regexp ) { $regexp = $reFloat; } $hash->{helper}{reading} = $reading; $hash->{helper}{regexp} = $regexp; # Actor my ( $actor, $cmd ) = split( ":", $a[3], 2 ); if ( !$defs{$actor} ) { my $msg = "$name: Unknown actor device $actor specified"; PID20_Log $hash, 1, $msg; return $msg; } $hash->{helper}{actor} = $actor; $hash->{helper}{actorCommand} = ( defined($cmd) ) ? $cmd : ""; $hash->{helper}{stopped} = 0; $hash->{helper}{adjust} = ""; $modules{PID20}{defptr}{$name} = $hash; readingsSingleUpdate( $hash, 'state', 'initializing', 1 ); RemoveInternalTimer($name); InternalTimer( gettimeofday() + 10, "PID20_Calc", $name, 0 ); return undef; } ######################################## sub PID20_Undef($$) { my ( $hash, $arg ) = @_; RemoveInternalTimer( $hash->{NAME} ); return undef; } ######################################## # we need a gradient for delta as base for d-portion calculation # sub PID20_Notify($$) { my ( $hash, $dev ) = @_; my $name = $hash->{NAME}; my $sensorName = $hash->{helper}{sensor}; my $DEBUG = AttrVal( $name, 'pidDebugNotify', '0' ) eq '1'; my $disable = AttrVal( $name, 'disable', '0' ); # no action if disabled if ( $disable eq '1' ) { return ""; } return if ( $dev->{NAME} ne $sensorName ); my $sensorReadingName = $hash->{helper}{reading}; my $regexp = $hash->{helper}{regexp}; my $desiredName = AttrVal( $name, 'pidDesiredName', 'desired' ); my $desired = ReadingsVal( $name, $desiredName, undef ); my $max = int( @{ $dev->{CHANGED} } ); PID20_Log $hash, 4, "check $max readings for " . $sensorReadingName; for ( my $i = 0 ; $i < $max ; $i++ ) { my $s = $dev->{CHANGED}[$i]; # continue, if no match with reading-name $s = "" if ( !defined($s) ); PID20_Log $hash, 5, "check event:<$s>"; next if ( $s !~ m/$sensorReadingName/ ); # ---- build difference current - old value # get sensor value my $sensorStr = ReadingsVal( $sensorName, $sensorReadingName, undef ); $sensorStr =~ m/$regexp/; my $sensorValue = $1; # calc difference of delta/deltaOld my $delta = $desired - $sensorValue if ( defined($desired) ); my $deltaOld = ( $hash->{helper}{deltaOld} + 0 ) if ( defined( $hash->{helper}{deltaOld} ) ); my $deltaDiff = ( $delta - $deltaOld ) if ( defined($delta) && defined($deltaOld) ); PID20_Log $hash, 5, "Diff: delta[" . sprintf( "%.2f", $delta ) . "]" . " - deltaOld[" . sprintf( "%.2f", $deltaOld ) . "]" . "= Diff[" . sprintf( "%.2f", $deltaDiff ) . "]" if ($DEBUG); # ----- build difference of timestamps (ok) my $deltaOldTsStr = $hash->{helper}{deltaOldTS}; my $deltaOldTsNum = time_str2num($deltaOldTsStr) if ( defined($deltaOldTsStr) ); my $nowTsNum = gettimeofday(); my $tsDiff = ( $nowTsNum - $deltaOldTsNum ) if ( defined($deltaOldTsNum) && ( ( $nowTsNum - $deltaOldTsNum ) > 0 ) ); PID20_Log $hash, 5, "tsDiff: tsDiff = $tsDiff " if ($DEBUG); # ----- calculate gradient of delta my $deltaGradient = $deltaDiff / $tsDiff if ( defined($deltaDiff) && defined($tsDiff) && ( $tsDiff > 0 ) ); $deltaGradient = 0 if ( !defined($deltaGradient) ); my $sdeltaDiff = ($deltaDiff) ? sprintf( "%.2f", $deltaDiff ) : ""; my $sTSDiff = ($tsDiff) ? sprintf( "%.2f", $tsDiff ) : ""; my $sDeltaGradient = ($deltaGradient) ? sprintf( "%.6f", $deltaGradient ) : ""; PID20_Log $hash, 5, "deltaGradient: (Diff[$sdeltaDiff]" . "/tsDiff[$sTSDiff]" . "=deltaGradient per sec [$sDeltaGradient]" if ($DEBUG); # ----- store results $hash->{helper}{deltaGradient} = $deltaGradient; $hash->{helper}{deltaOld} = $delta; $hash->{helper}{deltaOldTS} = TimeNow(); last; } return ""; } ######################################## sub PID20_Get($@) { my ( $hash, @a ) = @_; my $name = $hash->{NAME}; my $usage = "Unknown argument $a[1], choose one of params:noArg"; return $usage if ( @a < 2 ); my $cmd = lc( $a[1] ); given ($cmd) { when ('params') { my $ret = "Defined parameters for PID20 $name:\n\n"; $ret .= 'Actor name : ' . $hash->{helper}{actor} . "\n"; $ret .= 'Actor cmd : ' . $hash->{helper}{actorCommand} . "\n\n"; $ret .= 'Sensor name : ' . $hash->{helper}{sensor} . "\n"; $ret .= 'Sensor reading : ' . $hash->{helper}{reading} . "\n\n"; $ret .= 'Sensor regexp : ' . $hash->{helper}{regexp} . "\n\n"; $ret .= 'Factor P : ' . $hash->{helper}{factor_P} . "\n"; $ret .= 'Factor I : ' . $hash->{helper}{factor_I} . "\n"; $ret .= 'Factor D : ' . $hash->{helper}{factor_D} . "\n\n"; $ret .= 'Actor lower limit: ' . $hash->{helper}{actorLimitLower} . "\n"; $ret .= 'Actor upper limit: ' . $hash->{helper}{actorLimitUpper} . "\n"; return $ret; } default { return $usage; } } } ######################################## sub PID20_Set($@) { my ( $hash, @a ) = @_; my $name = $hash->{NAME}; my $reFloat = '^([\\+,\\-]?\\d+\\.?\d*$)'; my $usage = "Unknown argument $a[1], choose one of stop:noArg start:noArg restart " . AttrVal( $name, 'pidDesiredName', 'desired' ); return $usage if ( @a < 2 ); my $cmd = lc( $a[1] ); my $desiredName = lc( AttrVal( $name, 'pidDesiredName', 'desired' ) ); #PID20_Log $hash, 3, "name:$name cmd:$cmd $desired:$desired"; given ($cmd) { when ("?") { return $usage; } when ($desiredName) { return "Set " . AttrVal( $name, 'pidDesiredName', 'desired' ) . " needs a <value> parameter" if ( @a != 3 ); my $value = $a[2]; $value = ( $value =~ m/$reFloat/ ) ? $1 : undef; return "value " . $a[2] . " is not a number" if ( !defined($value) ); readingsSingleUpdate( $hash, $cmd, $value, 1 ); PID20_Log $hash, 3, "set $name $cmd $a[2]"; } when ("start") { return "Set start needs a <value> parameter" if ( @a != 2 ); $hash->{helper}{stopped} = 0; } when ("stop") { return "Set stop needs a <value> parameter" if ( @a != 2 ); $hash->{helper}{stopped} = 1; PID20_Calc($name); } when ("restart") { return "Set restart needs a <value> parameter" if ( @a != 3 ); my $value = $a[2]; $value = ( $value =~ m/$reFloat/ ) ? $1 : undef; #PID20_Log $hash, 1, "value:$value"; return "value " . $a[2] . " is not a number" if ( !defined($value) ); $hash->{helper}{stopped} = 0; $hash->{helper}{adjust} = $value; PID20_Log $hash, 3, "set $name $cmd $value"; } when ("calc") # inofficial function, only for debugging purposes { PID20_Calc($name); } default { return $usage; } } return; } ######################################## # disabled = 0 # idle = 1 # processing = 2 # stopped = 3 # alarm = 4 sub PID20_Calc($) { my $reUINT = '^([\\+]?\\d+)$'; # uint without whitespaces my $re01 = '^([0,1])$'; # only 0,1 my $reINT = '^([\\+,\\-]?\\d+$)'; # int my $reFloatpos = '^([\\+]?\\d+\\.?\d*$)'; # gleitpunkt positiv float my $reFloat = '^([\\+,\\-]?\\d+\\.?\d*$)'; # float my ($name) = @_; my $hash = $defs{$name}; my $sensor = $hash->{helper}{sensor}; my $reading = $hash->{helper}{reading}; my $regexp = $hash->{helper}{regexp}; my $DEBUG_Sensor = AttrVal( $name, 'pidDebugSensor', '0' ) eq '1'; my $DEBUG_Actuation = AttrVal( $name, 'pidDebugActuation', '0' ) eq '1'; my $DEBUG_Delta = AttrVal( $name, 'pidDebugDelta', '0' ) eq '1'; my $DEBUG_Calc = AttrVal( $name, 'pidDebugCalc', '0' ) eq '1'; my $DEBUG_Update = AttrVal( $name, 'pidDebugUpdate', '0' ) eq '1'; my $DEBUG = $DEBUG_Sensor || $DEBUG_Actuation || $DEBUG_Calc || $DEBUG_Delta || $DEBUG_Update; my $actuation = ""; my $actuationDone = ReadingsVal( $name, 'actuation', "" ); my $actuationCalc = ReadingsVal( $name, 'actuationCalc', "" ); my $actuationCalcOld = $actuationCalc; my $actorTimestamp = ( $hash->{helper}{actorTimestamp} ) ? $hash->{helper}{actorTimestamp} : FmtDateTime( gettimeofday() - 3600 * 24 ); my $sensorStr = ReadingsVal( $sensor, $reading, "" ); my $sensorValue = ""; my $sensorTS = ReadingsTimestamp( $sensor, $reading, undef ); my $sensorIsAlive = 0; my $iPortion = ReadingsVal( $name, 'p_i', 0 ); my $pPortion = ReadingsVal( $name, 'p_p', "" ); my $dPortion = ReadingsVal( $name, 'p_d', "" ); my $stateStr = ""; my $deltaOld = ReadingsVal( $name, 'delta', 0 ); my $delta = ""; my $deltaGradient = ( $hash->{helper}{deltaGradient} ) ? $hash->{helper}{deltaGradient} : 0; my $calcReq = 0; my $readingUpdateReq = ''; # ---------------- check conditions while (1) { # --------------- retrive values from attributes $hash->{helper}{actorInterval} = ( AttrVal( $name, 'pidActorInterval', 180 ) =~ m/$reUINT/ ) ? $1 : 180; $hash->{helper}{actorThreshold} = ( AttrVal( $name, 'pidActorTreshold', 1 ) =~ m/$reUINT/ ) ? $1 : 1; $hash->{helper}{actorKeepAlive} = ( AttrVal( $name, 'pidActorKeepAlive', 1800 ) =~ m/$reUINT/ ) ? $1 : 1800; $hash->{helper}{actorValueDecPlaces} = ( AttrVal( $name, 'pidActorValueDecPlaces', 0 ) =~ m/$reUINT/ ) ? $1 : 0; $hash->{helper}{actorErrorAction} = ( AttrVal( $name, 'pidActorErrorAction', 'freeze' ) eq 'errorPos' ) ? 'errorPos' : 'freeze'; $hash->{helper}{actorErrorPos} = ( AttrVal( $name, 'pidActorErrorPos', 0 ) =~ m/$reINT/ ) ? $1 : 0; $hash->{helper}{calcInterval} = ( AttrVal( $name, 'pidCalcInterval', 60 ) =~ m/$reUINT/ ) ? $1 : 60; $hash->{helper}{deltaTreshold} = ( AttrVal( $name, 'pidDeltaTreshold', 0 ) =~ m/$reFloatpos/ ) ? $1 : 0; $hash->{helper}{disable} = ( AttrVal( $name, 'disable', 0 ) =~ m/$re01/ ) ? $1 : ''; $hash->{helper}{sensorTimeout} = ( AttrVal( $name, 'pidSensorTimeout', 3600 ) =~ m/$reUINT/ ) ? $1 : 3600; $hash->{helper}{reverseAction} = ( AttrVal( $name, 'pidReverseAction', 0 ) =~ m/$re01/ ) ? $1 : 0; $hash->{helper}{updateInterval} = ( AttrVal( $name, 'pidUpdateInterval', 600 ) =~ m/$reUINT/ ) ? $1 : 600; $hash->{helper}{measuredName} = AttrVal( $name, 'pidMeasuredName', 'measured' ); $hash->{helper}{desiredName} = AttrVal( $name, 'pidDesiredName', 'desired' ); $hash->{helper}{actorLimitLower} = ( AttrVal( $name, 'pidActorLimitLower', 0 ) =~ m/$reFloat/ ) ? $1 : 0; my $actorLimitLower = $hash->{helper}{actorLimitLower}; $hash->{helper}{actorLimitUpper} = ( AttrVal( $name, 'pidActorLimitUpper', 100 ) =~ m/$reFloat/ ) ? $1 : 100; my $actorLimitUpper = $hash->{helper}{actorLimitUpper}; $hash->{helper}{factor_P} = ( AttrVal( $name, 'pidFactor_P', 25 ) =~ m/$reFloatpos/ ) ? $1 : 25; $hash->{helper}{factor_I} = ( AttrVal( $name, 'pidFactor_I', 0.25 ) =~ m/$reFloatpos/ ) ? $1 : 0.25; $hash->{helper}{factor_D} = ( AttrVal( $name, 'pidFactor_D', 0 ) =~ m/$reFloatpos/ ) ? $1 : 0; if ( $hash->{helper}{disable} ) { $stateStr = "disabled"; last; } if ( $hash->{helper}{stopped} ) { $stateStr = "stopped"; last; } my $desired = ReadingsVal( $name, $hash->{helper}{desiredName}, "" ); # sensor found PID20_Log $hash, 2, "--------------------------" if ($DEBUG); PID20_Log $hash, 2, "S1 sensorStr:$sensorStr sensorTS:$sensorTS" if ($DEBUG_Sensor); $stateStr = "alarm - no $reading yet for $sensor" if ( !$sensorStr && !$stateStr ); # sensor alive if ( $sensorStr && $sensorTS ) { my $timeDiff = PID20_TimeDiff($sensorTS); $sensorIsAlive = 1 if ( $timeDiff <= $hash->{helper}{sensorTimeout} ); $sensorStr =~ m/$regexp/; $sensorValue = $1; $sensorValue = "" if ( !defined($sensorValue) ); PID20_Log $hash, 2, "S2 timeOfDay:" . gettimeofday() . " timeDiff:$timeDiff sensorTimeout:" . $hash->{helper}{sensorTimeout} . " --> sensorIsAlive:$sensorIsAlive" if ($DEBUG_Sensor); } # sensor dead $stateStr = "alarm - dead sensor" if ( !$sensorIsAlive && !$stateStr ); # missing desired $stateStr = "alarm - missing desired" if ( $desired eq "" && !$stateStr ); # check delta threshold $delta = ( $desired ne "" && $sensorValue ne "" ) ? $desired - $sensorValue : ""; $calcReq = 1 if ( !$stateStr && $delta ne "" && ( abs($delta) >= abs( $hash->{helper}{deltaTreshold} ) ) ); PID20_Log $hash, 2, "D1 desired[" . ( $desired ne "" ) ? sprintf( "%.1f", $desired ) : "" . "] - sensorValue: [" . ( $sensorValue ne "" ) ? sprintf( "%.1f", $sensorValue ) : "" . "] = delta[" . ( $delta ne "" ) ? sprintf( "%.2f", $delta ) : "" . "] calcReq:$calcReq" if ($DEBUG_Delta); #request for calculation # ---------------- calculation request if ($calcReq) { # reverse action requested my $workDelta = ( $hash->{helper}{reverseAction} == 1 ) ? -$delta : $delta; my $deltaOld = -$deltaOld if ( $hash->{helper}{reverseAction} == 1 ); # calc p-portion $pPortion = $workDelta * $hash->{helper}{factor_P}; # calc d-Portion $dPortion = ($deltaGradient) * $hash->{helper}{calcInterval} * $hash->{helper}{factor_D}; # calc i-portion respecting windUp # freeze i-portion if windUp is active my $isWindup = $actuationCalcOld && ( ( $workDelta > 0 && $actuationCalcOld > $actorLimitUpper ) || ( $workDelta < 0 && $actuationCalcOld < $actorLimitLower ) ); if ( $hash->{helper}{adjust} ne "" ) { $iPortion = $hash->{helper}{adjust} - ( $pPortion + $dPortion ); $iPortion = $actorLimitUpper if ( $iPortion > $actorLimitUpper ); $iPortion = $actorLimitLower if ( $iPortion < $actorLimitLower ); PID20_Log $hash, 5, "adjust request with:" . $hash->{helper}{adjust} . " ==> p_i:$iPortion"; $hash->{helper}{adjust} = ""; } elsif ( !$isWindup ) # integrate only if no windUp { # normalize the intervall to minute=60 seconds $iPortion = $iPortion + $workDelta * $hash->{helper}{factor_I} * $hash->{helper}{calcInterval} / 60; $hash->{helper}{isWindUP} = 0; } $hash->{helper}{isWindUP} = $isWindup; # calc actuation $actuationCalc = $pPortion + $iPortion + $dPortion; PID20_Log $hash, 2, "P1 delta:" . sprintf( "%.2f", $delta ) . " isWindup:$isWindup" if ($DEBUG_Calc); PID20_Log $hash, 2, "P2 pPortion:" . sprintf( "%.2f", $pPortion ) . " iPortion:" . sprintf( "%.2f", $iPortion ) . " dPortion:" . sprintf( "%.2f", $dPortion ) . " actuationCalc:" . sprintf( "%.2f", $actuationCalc ) if ($DEBUG_Calc); } $readingUpdateReq = 1; # in each case update readings # ---------------- acutation request my $noTrouble = ( $desired ne "" && $sensorIsAlive ); # check actor fallback in case of sensor fault if ( !$sensorIsAlive && ( $hash->{helper}{actorErrorAction} eq "errorPos" ) ) { $stateStr .= "- force pid-output to errorPos"; $actuationCalc = $hash->{helper}{actorErrorPos}; $actuationCalc = "" if ( !defined($actuationCalc) ); } # check acutation diff $actuation = $actuationCalc; # limit $actuation $actuation = $actorLimitUpper if ( $actuation ne "" && ( $actuation > $actorLimitUpper ) ); $actuation = $actorLimitLower if ( $actuation ne "" && ( $actuation < $actorLimitLower ) ); # check if round request my $fmt = "%." . $hash->{helper}{actorValueDecPlaces} . "f"; $actuation = sprintf( $fmt, $actuation ) if ( $actuation ne "" ); my $actuationDiff = abs( $actuation - $actuationDone ) if ( $actuation ne "" && $actuationDone ne "" ); PID20_Log $hash, 2, "A1 act:$actuation actDone:$actuationDone " . " actThreshold:" . $hash->{helper}{actorThreshold} . " actDiff:$actuationDiff" if ($DEBUG_Actuation); # check threshold-condition for actuation my $rsTS = $actuationDone ne "" && $actuationDiff >= $hash->{helper}{actorThreshold}; # ...... special handling if acutation is in the black zone between actorLimit and (actorLimit - actorThreshold) # upper range my $rsUp = $actuationDone ne "" && $actuation > $actorLimitUpper - $hash->{helper}{actorThreshold} && $actuationDiff != 0 && $actuation >= $actorLimitUpper; # low range my $rsDown = $actuationDone ne "" && $actuation < $actorLimitLower + $hash->{helper}{actorThreshold} && $actuationDiff != 0 && $actuation <= $actorLimitLower; # upper or lower limit are exceeded my $rsLimit = $actuationDone ne "" && ( $actuationDone < $actorLimitLower || $actuationDone > $actorLimitUpper ); my $actuationByThreshold = ( ( $rsTS || $rsUp || $rsDown ) && $noTrouble ); PID20_Log $hash, 2, "A2 rsTS:$rsTS rsUp:$rsUp rsDown:$rsDown noTrouble:$noTrouble" if ($DEBUG_Actuation); # check time condition for actuation my $actTimeDiff = PID20_TimeDiff($actorTimestamp); # $actorTimestamp is valid in each case my $actuationByTime = ($noTrouble) && ( $actTimeDiff > $hash->{helper}{actorInterval} ); PID20_Log $hash, 2, "A3 actTS:$actorTimestamp" . " actTimeDiff:" . sprintf( "%.2f", $actTimeDiff ) . " actInterval:" . $hash->{helper}{actorInterval} . "-->actByTime:$actuationByTime " if ($DEBUG_Actuation); # check keep alive condition for actuation my $actuationKeepAliveReq = ( $actTimeDiff >= $hash->{helper}{actorKeepAlive} ) if ( defined($actTimeDiff) && $actuation ne "" ); # build total actuation request my $actuationReq = ( ( $actuationByThreshold && $actuationByTime ) || $actuationKeepAliveReq # request by keep alive || $rsLimit # upper or lower limit are exceeded || $actuationDone eq "" # startup condition ) && $actuation ne ""; # acutation is initialized PID20_Log $hash, 2, "A4 (actByTh:$actuationByThreshold && actByTime:$actuationByTime)" . "||actKeepAlive:$actuationKeepAliveReq" . "||rsLimit:$rsLimit=actnReq:$actuationReq" if ($DEBUG_Actuation); # ................ perform output to actor if ($actuationReq) { $readingUpdateReq = 1; # update the readings #build command for fhem PID20_Log $hash, 5, "actor:" . $hash->{helper}{actor} . " actorCommand:" . $hash->{helper}{actorCommand} . " actuation:" . $actuation; my $cmd = sprintf( "set %s %s %g", $hash->{helper}{actor}, $hash->{helper}{actorCommand}, $actuation ); # execute command my $ret; $ret = fhem $cmd; # note timestamp $hash->{helper}{actorTimestamp} = TimeNow(); $actuationDone = $actuation; my $retStr = ""; $retStr = " with return-value:" . $ret if ( defined($ret) && ( $ret ne '' ) ); PID20_Log $hash, 3, "<$cmd> " . $retStr; } my $updateAlive = ( $actuation ne "" ) && PID20_TimeDiff( ReadingsTimestamp( $name, 'actuation', gettimeofday() ) ) >= $hash->{helper}{updateInterval}; # my $updateReq = ( ( $actuationReq || $updateAlive ) && $actuation ne "" ); # PID20_Log $hash, 2, "U1 actReq:$actuationReq updateAlive:$updateAlive --> updateReq:$updateReq" if ($DEBUG_Update); # ---------------- update request if ($readingUpdateReq) { readingsBeginUpdate($hash); readingsBulkUpdate( $hash, $hash->{helper}{desiredName}, $desired ) if ( $desired ne "" ); readingsBulkUpdate( $hash, $hash->{helper}{measuredName}, $sensorValue ) if ( $sensorValue ne "" ); readingsBulkUpdate( $hash, 'p_p', $pPortion ) if ( $pPortion ne "" ); readingsBulkUpdate( $hash, 'p_d', $dPortion ) if ( $dPortion ne "" ); readingsBulkUpdate( $hash, 'p_i', $iPortion ) if ( $iPortion ne "" ); readingsBulkUpdate( $hash, 'actuation', $actuationDone ) if ( $actuationDone ne "" ); readingsBulkUpdate( $hash, 'actuationCalc', $actuationCalc ) if ( $actuationCalc ne "" ); readingsBulkUpdate( $hash, 'delta', $delta ) if ( $delta ne "" ); readingsEndUpdate( $hash, 1 ); PID20_Log $hash, 5, "readings updated"; } last; } # end while # ........ update statePID. $stateStr = "idle" if ( !$stateStr && !$calcReq ); $stateStr = "processing" if ( !$stateStr && $calcReq ); $stateStr = $stateStr . sprintf(" t=%.1f C, act=%.0f %%, (D=%.1f C, p=%.0f, i=%.0f, d=%.0f)", $sensorValue, $actuationDone, $delta, $pPortion, $iPortion, $dPortion ); # HB readingsSingleUpdate( $hash, 'state', $stateStr, 0 ); PID20_Log $hash, 2, "C1 stateStr:$stateStr calcReq:$calcReq" if ($DEBUG_Calc); #......... timer setup my $next = gettimeofday() + $hash->{helper}{calcInterval}; RemoveInternalTimer($name); # prevent multiple timers for same hash InternalTimer( $next, "PID20_Calc", $name, 1 ); #PID20_Log $hash, 2, "InternalTimer next:".FmtDateTime($next)." PID20_Calc name:$name DEBUG_Calc:$DEBUG_Calc"; return; } 1; =pod =begin html <a name="PID20"></a> <h3>PID20</h3> <ul> <a name="PID20define"></a> <b>Define</b> <ul> <br/> <code>define &lt;name&gt; PID20 &lt;sensor[:reading[:regexp]]&gt; &lt;actor:cmd &gt;</code> <br/><br/> This module provides a PID device, using &lt;sensor&gt; and &lt;actor&gt;<br/> </ul> <br/><br/> <a name="PID20set"></a> <b>Set-Commands</b><br/> <ul> <br/> <code>set &lt;name&gt; desired &lt;value&gt;</code> <br/><br/> <ul>Set desired value for PID</ul> <br/> <br/> <code>set &lt;name&gt; start</code> <br/><br/> <ul>Start PID processing again, using frozen values from former stop.</ul> <br/> <br/> <code>set &lt;name&gt; stop</code> <br/><br/> <ul>PID stops processing, freezing all values.</ul> <br/> <br/> <code>set &lt;name&gt; restart &lt;value&gt;</code> <br/><br/> <ul>Same as start, but uses value as start value for actor</ul> <br/> </ul> <br/><br/> <a name="PID20get"></a> <b>Get-Commands</b><br/> <ul> <br/> <code>get &lt;name&gt; params</code> <br/><br/> <ul>Get list containing current parameters.</ul> <br/> </ul> <br/><br/> <a name="PID20attr"></a> <b>Attributes</b><br/><br/> <ul> <li><a href="#readingFnAttributes">readingFnAttributes</a></li> <br/> <li><b>disable</b> - disable the PID device, possible values: 0,1; default: 0</li> <li><b>pidActorValueDecPlaces</b> - number of demicals, possible values: 0..5; default: 0</li> <li><b>pidActorInterval</b> - number of seconds to wait between to commands sent to actor; default: 180</li> <li><b>pidActorTreshold</b> - threshold to be reached before command will be sent to actor; default: 1</li> <li><b>pidActorErrorAction</b> - required action on error, possible values: freeze,errorPos; default: freeze</li> <li><b>pidActorErrorPos</b> - actor's position to be used in case of error; default: 0</li> <li><b>pidActorKeepAlive</b> - number of seconds to force command to be sent to actor; default: 1800</li> <li><b>pidActorLimitLower</b> - lower limit for actor; default: 0</li> <li><b>pidActorLimitUpper</b> - upper limit for actor; default: 100</li> <li><b>pidCalcInterval</b> - interval (seconds) to calculate new pid values; default: 60</li> <li><b>pidDeltaTreshold</b> - if delta < delta-threshold the pid will enter idle state; default: 0</li> <li><b>pidDesiredName</b> - reading's name for desired value; default: desired</li> <li><b>pidFactor_P</b> - P value for PID; default: 25</li> <li><b>pidFactor_I</b> - I value for PID; default: 0.25</li> <li><b>pidFactor_D</b> - D value for PID; default: 0</li> <li><b>pidMeasuredName</b> - reading's name for measured value; default: measured</li> <li><b>pidSensorTimeout</b> - number of seconds to wait before sensor will be recognized n/a; default: 3600</li> <li><b>pidReverseAction</b> - reverse PID operation mode, possible values: 0,1; default: 0</li> <li><b>pidUpdateInterval</b> - number of seconds to wait before an update will be forced for plotting; default: 300</li> </ul> <br/><br/> <b>Generated Readings/Events:</b> <br/><br/> <ul> <li><b>actuation</b> - real actuation set to actor</li> <li><b>actuationCalc</b> - internal actuation calculated without limits</li> <li><b>delta</b> - current difference desired - measured</li> <li><b>desired</b> - desired value</li> <li><b>measured</b> - measured value</li> <li><b>p_p</b> - p value of pid calculation</li> <li><b>p_i</b> - i value of pid calculation</li> <li><b>p_d</b> - d value of pid calculation</li> <li><b>state</b> - current device state</li> <br/> Names for desired and measured readings can be changed by corresponding attributes (see above).<br/> </ul> <br/><br/> <b>Additional information</b><br/><br/> <ul> <li><a href="http://forum.fhem.de/index.php/topic,17067.0.html">Discussion in FHEM forum</a></li><br/> <li><a href="http://www.fhemwiki.de/wiki/PID20_-_Der_PID-Regler">Information in FHEM wiki</a></li><br/> </ul> </ul> =end html
HynekBaran/FHT8V_commander
FHEM/FHEM/98_PID20.HB.pm
Perl
apache-2.0
31,012
use Bio::EnsEMBL::Registry; my $registry = 'Bio::EnsEMBL::Registry'; $registry->load_registry_from_db( -host => 'mysql-ensembl-mirror.ebi.ac.uk', -port => 4240, -user => 'anonymous', ); my $va = $registry->get_adaptor('human', 'variation', 'variation'); my $variation = $va->fetch_by_name('rs699'); print $variation, "\n";
at7/work
api/registry.pl
Perl
apache-2.0
344
# # 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::pvx::restapi::mode::networkuserexperience; use base qw(centreon::plugins::templates::counter); use strict; use warnings; sub prefix_instances_output { my ($self, %options) = @_; return $options{instance_value}->{instance_label} . " '" . $options{instance_value}->{key} . "' "; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'instances', type => 1, cb_prefix_output => 'prefix_instances_output', message_multiple => 'All metrics are ok' }, ]; $self->{maps_counters}->{instances} = [ { label => 'time', nlabel => 'enduser.experience.seconds', set => { key_values => [ { name => 'user_experience' }, { name => 'key' }, { name => 'instance_label' } ], output_template => 'end-user experience: %.3fs', perfdatas => [ { label => 'time', template => '%.3f', min => 0, unit => 's', label_extra_instance => 1, instance_use => 'key' } ] } } ]; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { 'instance:s' => { name => 'instance', default => 'layer' }, 'top:s' => { name => 'top' }, 'filter:s' => { name => 'filter' }, 'from:s' => { name => 'from' } }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); if (!defined($self->{option_results}->{from}) || $self->{option_results}->{from} eq '') { $self->{output}->add_option_msg(short_msg => "Need to specify --from option as a PVQL object."); $self->{output}->option_exit(); } if (!defined($self->{option_results}->{instance}) || $self->{option_results}->{instance} eq '') { $self->{output}->add_option_msg(short_msg => "Need to specify --instance option as a PVQL object."); $self->{output}->option_exit(); } $self->{pvql_timeframe} = defined($self->{option_results}->{timeframe}) ? $self->{option_results}->{timeframe} : 900; } sub manage_selection { my ($self, %options) = @_; my $instance_label = $self->{option_results}->{instance}; $instance_label =~ s/\./ /g; $instance_label =~ s/(\w+)/\u\L$1/g; $self->{instances} = {}; my $apps; if ($self->{option_results}->{instance} =~ /application/) { my $results = $options{custom}->get_endpoint(url_path => '/get-configuration'); $apps = $results->{applications}; } my $results = $options{custom}->query_range( query => 'user.experience', instance => $self->{option_results}->{instance}, top => $self->{option_results}->{top}, filter => $self->{option_results}->{filter}, from => $self->{option_results}->{from}, timeframe => $self->{pvql_timeframe}, ); foreach my $result (@{$results}) { next if (!defined(${$result->{key}}[0])); my $instance; $instance = ${$result->{key}}[0]->{value} if (defined(${$result->{key}}[0]->{value})); $instance = ${$result->{key}}[0]->{status} if (defined(${$result->{key}}[0]->{status})); $self->{instances}->{$instance}->{key} = $instance; $self->{instances}->{$instance}->{key} = $apps->{$instance}->{name} if (defined($apps->{$instance}->{name}) && $self->{option_results}->{instance} =~ /application/); $self->{instances}->{$instance}->{user_experience} = (defined(${$result->{values}}[0]->{value})) ? ${$result->{values}}[0]->{value} : 0; $self->{instances}->{$instance}->{instance_label} = $instance_label; } if (scalar(keys %{$self->{instances}}) <= 0) { $self->{output}->add_option_msg(short_msg => "No instances or results found."); $self->{output}->option_exit(); } } 1; __END__ =head1 MODE Check instances connection metrics. =over 8 =item B<--instance> Filter on a specific instance (Must be a PVQL object, Default: 'layer') (Object 'application' will be mapped with applications name) =item B<--filter> Add a PVQL filter (Example: --filter='application = "mysql"') =item B<--from> Add a PVQL from clause to filter on a specific layer (Example: --from='tcp') =item B<--top> Only search for the top X results. =item B<--warning-time> Threshold warning (s). =item B<--critical-time> Threshold critical (s). =back =cut
centreon/centreon-plugins
apps/pvx/restapi/mode/networkuserexperience.pm
Perl
apache-2.0
5,288
#!/usr/bin/perl # # $Id: //Infrastructure/GitHub/Database/backup_and_sync/backup_scripts/backup_all_dbs.pl#1 $ # # T Dale 2015 # use Sys::Hostname; use strict; use warnings; use Switch; use Getopt::Long; use XML::LibXML; use Data::Dumper; sub fmt{ my( $str, $color ) = @_; my $col_num; switch ($color){ case 'red' {$col_num=31;} case 'green' {$col_num=32;} } return "\033[33;${col_num}m$str\033[0m"; } # # # my $backups_base_dir = ""; my $using_config_file; # # Backup type # my $backup_type=''; my $rman_channels=''; GetOptions ( "type=s" => \$backup_type , "rman_channels=s" => \$rman_channels , "base_dir=s" => \$backups_base_dir ); # # Check inputs # my $full_bk = 'FULL_BACKUP'; my $archives = 'ARCHIVELOGS_ONLY'; my $usage = "USAGE : backup_all_dbs.ph --type <$full_bk|$archives> --rman_channels <INT> --base_dir <Base backup dir>\n\n"; my $datestring = localtime(); print "Started at $datestring\n"; print "Backup base dir : $backups_base_dir\n"; if( !-d $backups_base_dir or $backups_base_dir eq '' ){ print "\nBase directory error\n\n"; print $usage; exit 1; } print "Backup type : $backup_type\n"; if( $backup_type ne $full_bk and $backup_type ne $archives or $backup_type eq '' ){ print "\ntype not in $full_bk or $archives\n\n"; print $usage; exit 2; } print "RMAN Channels : $rman_channels\n"; if( $rman_channels eq '' ){ print "\nrman channels not int or missing\n\n"; print $usage; exit 3; } # # Directories # my $backup_scripts_dir = "$backups_base_dir/scripts"; my $config_file = "$backup_scripts_dir/config/".hostname.".xml"; print "Looking for extra config : $config_file \n"; my $parser; my $config_xml_doc; if( -f $config_file ){ print "Found, Reading xml\n"; $parser = XML::LibXML->new(); $config_xml_doc = $parser->parse_file($config_file); $using_config_file = 1; }else{ print "Extra config file not found : $config_file\n"; $using_config_file = 0; } print "\n"; my $filename = '/etc/oratab'; my $i; my $sync_to_str = ''; my $zip_option_str = ''; open(my $fh , '<' , $filename) or die "Could not open file '$filename' $!"; # # Look through the oratab, an backup each db # while (my $row = <$fh>) { chomp $row; # # Look for oracle sids # if ($row =~ /.*:\/.*:[Y,N]/){ # # Get sid, oracle home and auto start info # my ($sid,$oracle_home,$auto_start) = split /:/, $row; # # ASM instance? # if( $sid eq '+ASM'){ print "ASM instance so skip\n"; }else{ # # Check if this instance is running # print sprintf( '%-10s', $sid ); my $cmd = "ps -aef | grep -v grep | grep -i smon_$sid"; if(`$cmd`) { print fmt('Running','green') . " - Start Backup \n"; # # Get the sync to cmd options # if( $using_config_file ){ $sync_to_str = ''; $sync_to_str = sync_options($sid,$config_xml_doc); print "Sync options : $sync_to_str \n"; $zip_option_str = config_option( $sid, 'compression', $config_xml_doc, 'c' ); print "Compression : $zip_option_str\n"; }else{ $sync_to_str = ''; $zip_option_str = ''; } # # Backup # my $bk_cmd = "$backup_scripts_dir/db_backup.sh -s $sid -b $backups_base_dir -t $backup_type -p $rman_channels" . $zip_option_str . ' ' . $sync_to_str; print "Running : $bk_cmd\n\n"; print "Logs in : $backups_base_dir/logs\n\n"; my $start = time; if(`$bk_cmd`) { # # Check return code # # # Check backup using sql # # # Backup info # my $duration = time - $start; print "Time takes (secs) : $duration\n\n"; }else{ print fmt('BACKUP FAILED!', 'red') . "\n"; } }else{ print "DONT BACKUP $sid - Database " . fmt('NOT RUNNING', 'red') . "\n"; } } } } $datestring = localtime(); print "Finished at $datestring\n"; close $fh; sub xpath{ my ($sid,$element) = @_; return '/db_list/db[@name=\''.$sid.'\']/'.$element; } sub config_option{ my ($sid, $element, $xml_doc, $option_when_found) = @_; my $option = ''; $option = $xml_doc->findvalue( xpath( $sid, $element ) ); if( $option ne '' ){ $option = " -$option_when_found $option"; } return $option; } sub sync_options{ my ($sid, $xml_doc) = @_; my $sync_str = ''; $sync_str .= config_option( $sid, 'rsync_option' , $xml_doc, 'r' ); $sync_str .= ' ' . config_option( $sid, 'sync_to_1' , $xml_doc, 'y' ); $sync_str .= ' ' . config_option( $sid, 'sync_to_1_dir', $xml_doc, 'z' ); $sync_str .= ' ' . config_option( $sid, 'sync_to_2' , $xml_doc, 'g' ); $sync_str .= ' ' . config_option( $sid, 'sync_to_2_dir', $xml_doc, 'h' ); $sync_str .= ' ' . config_option( $sid, 'skip', $xml_doc, 'm' ); return $sync_str; };
Fivium/Oracle-Backup-and-Sync
backup_scripts/backup_all_dbs.pl
Perl
bsd-3-clause
5,604
# raid-lib.pl # Functions for managing RAID BEGIN { push(@INC, ".."); }; use WebminCore; &init_config(); &foreign_require("fdisk"); open(MODE, "$module_config_directory/mode"); chop($raid_mode = <MODE>); close(MODE); %container = ( 'raiddev', 1, 'device', 1 ); # get_raid_levels() # Returns a list of allowed RAID levels sub get_raid_levels { if ($raid_mode eq "mdadm") { return ( 0, 1, 4, 5, 6, 10 ); } else { return ( 0, 1, 4, 5 ); } } # get_mdstat() # Read information about active RAID devices. Returns a hash indexed by # device name (like /dev/md0), with each value being an array reference # containing status level disks blocks resync disk-info sub get_mdstat { # Read the mdstat file local %mdstat; local $lastdev; open(MDSTAT, $config{'mdstat'}); while(<MDSTAT>) { if (/^(md\d+)\s*:\s+(\S+)\s+(\S+)\s+(.*)\s+(\d+)\s+blocks\s*(.*)resync=(\d+)/) { $mdstat{$lastdev = "/dev/$1"} = [ $2, $3, $4, $5, $7, $6 ]; } elsif (/^(md\d+)\s*:\s+(\S+)\s+(\S+)\s+(.*)\s+(\d+)\s+blocks\s*(.*)/) { $mdstat{$lastdev = "/dev/$1"} = [ $2, $3, $4, $5, undef, $6 ]; } elsif (/^(md\d+)\s*:\s+(\S+)\s+(\S+)\s+(.*)/) { $mdstat{$lastdev = "/dev/$1"} = [ $2, $3, $4 ]; $_ = <MDSTAT>; if (/\s+(\d+)\s+blocks\s*(.*)resync=(\d+)/) { $mdstat{$lastdev}->[3] = $1; $mdstat{$lastdev}->[4] = $3; $mdstat{$lastdev}->[5] = $2; } elsif (/\s+(\d+)\s+blocks\s*(.*)/) { $mdstat{$lastdev}->[3] = $1; $mdstat{$lastdev}->[5] = $2; } } } close(MDSTAT); return %mdstat; } # get_raidtab() # Parse the raid config file into a list of devices sub get_raidtab { local ($raiddev, $device, %mdstat); return \@get_raidtab_cache if (scalar(@get_raidtab_cache)); %mdstat = &get_mdstat(); if ($raid_mode eq "raidtools") { # Read the raidtab file local $lnum = 0; open(RAID, $config{'raidtab'}); while(<RAID>) { s/\r|\n//g; s/#.*$//; if (/^\s*(\S+)\s+(\S+)/) { local $dir = { 'name' => lc($1), 'value' => $2, 'line' => $lnum, 'eline' => $lnum }; if ($dir->{'name'} =~ /^(raid|spare|parity|failed)-disk$/) { push(@{$device->{'members'}}, $dir); $device->{'eline'} = $lnum; $raiddev->{'eline'} = $lnum; } elsif ($dir->{'name'} eq 'raiddev') { $dir->{'index'} = scalar(@get_raidtab_cache); push(@get_raidtab_cache, $dir); } else { push(@{$raiddev->{'members'}}, $dir); $raiddev->{'eline'} = $lnum; } if ($dir->{'name'} eq 'device') { $device = $dir; } elsif ($dir->{'name'} eq 'raiddev') { $raiddev = $dir; local $m = $mdstat{$dir->{'value'}}; $dir->{'active'} = $m->[0] =~ /^active/; $dir->{'level'} = $m->[1] =~ /raid(\d+)/ ? $1 : $m->[1]; $dir->{'devices'} = [ map { /(\S+)\[\d+\](\((.)\))?/; $3 eq 'F' ? () : ("/dev/$1") } split(/\s+/, $m->[2]) ]; $dir->{'size'} = $m->[3]; $dir->{'resync'} = $m->[4]; $dir->{'errors'} = &disk_errors($m->[5]); } } $lnum++; } close(RAID); } else { # Fake up the same format from mdadm output local $m; foreach $m (sort { $a cmp $b } keys %mdstat) { local $md = { 'value' => $m, 'members' => [ ], 'index' => scalar(@get_raidtab_cache) }; local $mdstat = $mdstat{$md->{'value'}}; $md->{'active'} = $mdstat->[0] =~ /^active/; $md->{'level'} = $mdstat->[1] =~ /raid(\d+)/ ? $1 : $mdstat->[1]; $md->{'devices'} = [ map { /(\S+)\[\d+\](\((.)\))?/; $3 eq 'F' ? () : (&convert_to_hd("/dev/$1")) } split(/\s+/, $mdstat->[2]) ]; $md->{'size'} = $mdstat->[3]; $md->{'resync'} = $mdstat->[4]; $md->{'errors'} = &disk_errors($mdstat->[5]); open(MDSTAT, "mdadm --detail $m |"); while(<MDSTAT>) { if (/^\s*Raid\s+Level\s*:\s*(\S+)/) { local $lvl = $1; $lvl =~ s/^raid//; push(@{$md->{'members'}}, { 'name' => 'raid-level', 'value' => $lvl }); } elsif (/^\s*Persistence\s*:\s*(.*)/) { push(@{$md->{'members'}}, { 'name' => 'persistent-superblock', 'value' => $1 =~ /is\s+persistent/ }); } elsif (/^\s*State\s*:\s*(.*)/) { $md->{'state'} = $1; } elsif ((/^\s*Rebuild\s+Status\s*:\s*(\d+)\s*\%/) || (/^\s*Reshape\s+Status\s*:\s*(\d+)\s*\%/)) { $md->{'rebuild'} = $1; } elsif (/^\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+|\-)\s+(.*\S)\s+(\/\S+)/) { # A device line local $device = { 'name' => 'device', 'value' => $6, 'members' => [ ] }; push(@{$device->{'members'}}, { 'name' => $5 eq 'spare' ? 'spare-disk' : 'raid-disk', 'value' => $3 }); push(@{$md->{'members'}}, $device); } elsif (/^\s+(Chunk\s+Size|Rounding)\s+:\s+(\d+)/i) { push(@{$md->{'members'}}, { 'name' => 'chunk-size', 'value' => $2 }); } } close(MDSTAT); open(MDSTAT, $config{'mdstat'}); while(<MDSTAT>){ if (/^.*finish=(\S+)min/){ $md->{'remain'} = $1; } if (/^.*speed=(\S+)K/){ $md->{'speed'} = $1; } } close(MDSTAT); push(@get_raidtab_cache, $md); } # Merge in info from mdadm.conf local $lref = &read_file_lines($config{'mdadm'}); foreach my $l (@$lref) { if ($l =~ /^ARRAY\s+(\S+)\s*(.*)/) { local $dev = $1; local %opts = map { split(/=/, $_, 2) } split(/\s+/, $2); local ($md) = grep { $_->{'value'} eq $dev } @get_raidtab_cache; if ($md) { push(@{$md->{'members'}}, { 'name' => 'spare-group', 'value' => $opts{'spare-group'} }); } } } } return \@get_raidtab_cache; } # disk_errors(string) # Converts an mdstat errors string into an array of disk statuses sub disk_errors { if ($_[0] =~ /\[([0-9\/]+)\].*\[([A-Z_]+)\]/i) { local ($idxs, $errs) = ($1, $2); local @idxs = split(/\//, $idxs); local @errs = split(//, $errs); #if (@idxs == @errs) { # return [ map { $errs[$_-1] } @idxs ]; # } return \@errs; } return undef; } sub lock_raid_files { &lock_file($raid_mode eq "raidtools" ? $config{'raidtab'} : $config{'mdadm'}); } sub unlock_raid_files { &unlock_file($raid_mode eq "raidtools" ? $config{'raidtab'} : $config{'mdadm'}); } # create_raid(&raid) # Create a new raid set in the configuration file sub create_raid { if ($raid_mode eq "raidtools") { # Add to /etc/raidtab local $lref = &read_file_lines($config{'raidtab'}); $_[0]->{'line'} = @$lref; push(@$lref, &directive_lines($_[0])); $_[0]->{'eline'} = @$lref - 1; &flush_file_lines(); } else { # Add to /etc/mdadm.conf local ($d, @devices); foreach $d (&find("device", $_[0]->{'members'})) { push(@devices, $d->{'value'}); } local $sg = &find_value("spare-group", $_[0]->{'members'}); local $lref = &read_file_lines($config{'mdadm'}); local $lvl = &find_value('raid-level', $_[0]->{'members'}); $lvl = $lvl =~ /^\d+$/ ? "raid$lvl" : $lvl; push(@$lref, "DEVICE ". join(" ", map { &device_to_volid($_) } @devices)); push(@$lref, "ARRAY $_[0]->{'value'} level=$lvl devices=". join(",", @devices). ($sg ? " spare-group=$sg" : "")); &flush_file_lines(); &update_initramfs(); } } # delete_raid(&raid) # Delete a raid set from the config file sub delete_raid { if ($raid_mode eq "raidtools") { # Remove from /etc/raidtab local $lref = &read_file_lines($config{'raidtab'}); splice(@$lref, $_[0]->{'line'}, $_[0]->{'eline'} - $_[0]->{'line'} + 1); &flush_file_lines($config{'raidtab'}); } else { # Zero out the RAID &system_logged("mdadm --zero-superblock ". "$_[0]->{'value'} >/dev/null 2>&1"); # Zero out component superblocks my @devs = &find('device', $_[0]->{'members'}); foreach $d (@devs) { if (&find('raid-disk', $d->{'members'}) || &find('parity-disk', $d->{'members'}) || &find('spare-disk', $d->{'members'})) { &system_logged("mdadm --zero-superblock ". "$d->{'value'} >/dev/null 2>&1"); } } # Remove from /etc/mdadm.conf local ($d, %devices); foreach $d (&find("device", $_[0]->{'members'})) { $devices{$d->{'value'}} = 1; } local $lref = &read_file_lines($config{'mdadm'}); local $i; for($i=0; $i<@$lref; $i++) { if ($lref->[$i] =~ /^ARRAY\s+(\S+)/ && $1 eq $_[0]->{'value'}) { splice(@$lref, $i--, 1); } elsif ($lref->[$i] =~ /^DEVICE\s+(.*)/) { local @olddevices = split(/\s+/, $1); local @newdevices = grep { !$devices{$_} } @olddevices; if (@newdevices) { $lref->[$i] = "DEVICE ".join(" ", @newdevices); } else { splice(@$lref, $i--, 1); } } } &flush_file_lines($config{'mdadm'}); &update_initramfs(); } } # device_to_volid(device) # Given a device name like /dev/sda1, convert it to a volume ID if possible. # Otherwise return the device name. sub device_to_volid { local ($dev) = @_; return $dev; #return &fdisk::get_volid($dev) || $dev; } # make_raid(&raid, force, [missing], [assume-clean]) # Call mkraid or mdadm to make a raid set for real sub make_raid { if (!-r $_[0]->{'value'} && $_[0]->{'value'} =~ /\/md(\d+)$/) { # Device file is missing - create it now &system_logged("mknod $_[0]->{'value'} b 9 $1"); } if ($raid_mode eq "raidtools") { # Call the raidtools mkraid command local $f = $_[1] ? "--really-force" : ""; local $out = &backquote_logged("mkraid $f $_[0]->{'value'} ". "2>&1 </dev/null"); return $? ? &text($out =~ /force/i ? 'eforce' : 'emkraid', "<pre>$out</pre>") : undef; } else { # Call the complete mdadm command local $lvl = &find_value("raid-level", $_[0]->{'members'}); $lvl =~ s/^raid//; local $chunk = &find_value("chunk-size", $_[0]->{'members'}); local $mode = &find_value("persistent-superblock", $_[0]->{'members'}) ? "create" : "build"; local $layout = &find_value("parity-algorithm", $_[0]->{'members'}); local ($d, @devices, @spares, @parities); foreach $d (&find("device", $_[0]->{'members'})) { if (&find("raid-disk", $d->{'members'})) { push(@devices, $d->{'value'}); } elsif (&find("spare-disk", $d->{'members'})) { push(@spares, $d->{'value'}); } elsif (&find("parity-disk", $d->{'members'})) { push(@parities, $d->{'value'}); } } local $cmd = "mdadm --$mode --level $lvl --chunk $chunk"; if ($_[2]) { push(@devices, "missing"); } $cmd .= " --layout $layout" if ($layout); $cmd .= " --raid-devices ".scalar(@devices); $cmd .= " --spare-devices ".scalar(@spares) if (@spares); $cmd .= " --force" if ($_[1]); $cmd .= " --assume-clean" if ($_[3]); $cmd .= " --run"; $cmd .= " $_[0]->{'value'}"; foreach $d (@devices, @parities, @spares) { $cmd .= " $d"; } local $out = &backquote_logged("$cmd 2>&1 </dev/null"); return $? ? &text('emdadmcreate', "<pre>$out</pre>") : undef; } } # readwrite_raid(&raid) # Set RAID mode to read/write. sub readwrite_raid { local $cmd = "mdadm --readwrite $_[0]->{'value'}"; local $out = &backquote_logged("$cmd 2>&1 </dev/null"); return; } # unmake_raid(&raid) # Shut down a RAID set permanently sub unmake_raid { if ($raid_mode eq "raidtools") { &deactivate_raid($_[0]) if ($_[0]->{'active'}); } else { local $out = &backquote_logged("mdadm --stop $_[0]->{'value'} 2>&1"); &error(&text('emdadmstop', "<tt>$out</tt>")) if ($?); } } # activate_raid(&raid) # Activate a raid set, which has previously been deactivated sub activate_raid { if ($raid_mode eq "raidtools") { local $out = &backquote_logged("raidstart $_[0]->{'value'} 2>&1"); &error(&text('eraidstart', "<tt>$out</tt>")) if ($?); } } # deactivate_raid(&raid) # Deactivate a raid set, without actually deleting it sub deactivate_raid { if ($raid_mode eq "raidtools") { # Just stop the raid set local $out = &backquote_logged("raidstop $_[0]->{'value'} 2>&1"); &error(&text('eraidstop', "<tt>$out</tt>")) if ($?); } } # add_partition(&raid, device) # Adds a device to some RAID set, both in the config file and for real sub add_partition { if ($raid_mode eq "mdadm") { # Call mdadm command to add local $out = &backquote_logged( "mdadm --manage $_[0]->{'value'} --add $_[1] 2>&1"); &error(&text('emdadmadd', "<tt>$out</tt>")) if ($?); # Add device to mdadm.conf local $lref = &read_file_lines($config{'mdadm'}); local ($i, $done_device); for($i=0; $i<@$lref; $i++) { if ($lref->[$i] =~ /^DEVICE\s+/ && !$done_device) { $lref->[$i] .= " $_[1]"; $done_device++; } elsif ($lref->[$i] =~ /^ARRAY\s+(\S+)/ && $1 eq $_[0]->{'value'}) { $lref->[$i] =~ s/(\s)devices=(\S+)/${1}devices=${2},$_[1]/; } } &flush_file_lines(); &update_initramfs(); } } # grow(&raid, totaldisks) # Grows a RAID set to contain totaldisks active partitions sub grow { if ($raid_mode eq "mdadm") { # Call mdadm command to add $cmd="mdadm --grow $_[0]->{'value'} -n $_[1] 2>&1"; local $out = &backquote_logged( $cmd); &error(&text('emdadmgrow', "<tt>'$cmd' -> $out</tt>")) if ($?); } } # convert_raid(&raid, oldcount, newcount, level) # Converts a RAID set to a defferent level RAID set sub convert_raid { if ($raid_mode eq "mdadm") { if ($_[2]) { # Call mdadm command to convert $cmd="mdadm --grow $_[0]->{'value'} --level $_[3]"; $grow_by = $_[2] - $_[1]; if ($grow_by == 1) { $raid_device_short = $_[0]->{'value'}; $raid_device_short =~ s/\/dev\///; $date = `date \+\%Y\%m\%d-\%H\%M`; chomp($date); $cmd .= " --backup-file /tmp/convert-$raid_device_short-$date"; } $cmd .= " -n $_[2] 2>&1"; local $out = &backquote_logged( $cmd); &error(&text('emdadmgrow', "<tt>'$cmd' -> $out</tt>")) if ($?); } else { $newcount = $_[1] - 1; $cmd="mdadm --grow $_[0]->{'value'} --level $_[3] -n $newcount"; $raid_device_short = $_[0]->{'value'}; $raid_device_short =~ s/\/dev\///; $date = `date \+\%Y\%m\%d-\%H\%M`; chomp($date); $cmd .= " --backup-file /tmp/convert-$raid_device_short-$date"; local $out = &backquote_logged( $cmd); &error(&text('emdadmgrow', "<tt>'$cmd' -> $out</tt>")) if ($?); } } } # remove_partition(&raid, device) # Removes a device from some RAID set, both in the config file and for real sub remove_partition { if ($raid_mode eq "mdadm") { # Call mdadm commands to fail and remove local $out = &backquote_logged( "mdadm --manage $_[0]->{'value'} --fail $_[1] 2>&1"); &error(&text('emdadfail', "<tt>$out</tt>")) if ($?); local $out = &backquote_logged( "mdadm --manage $_[0]->{'value'} --remove $_[1] 2>&1"); &error(&text('emdadremove', "<tt>$out</tt>")) if ($?); # Remove device from mdadm.conf local $lref = &read_file_lines($config{'mdadm'}); local ($i, $done_device); for($i=0; $i<@$lref; $i++) { if ($lref->[$i] =~ /^DEVICE\s+(.*)/) { local @olddevices = split(/\s+/, $1); local @newdevices = grep { $_ ne $_[1] } @olddevices; if (@newdevices) { $lref->[$i] = "DEVICE ".join(" ", @newdevices); } else { splice(@$lref, $i--, 1); } } elsif ($lref->[$i] =~ /^ARRAY\s+(\S+)/ && $1 eq $_[0]->{'value'}) { $lref->[$i] =~ s/((=)|,)\Q$_[1]\E/$2/; } } &flush_file_lines(); &update_initramfs(); } } # remove_detached(&raid) # Removes detached device(s) from some RAID set sub remove_detached { if ($raid_mode eq "mdadm") { # Call mdadm commands to remove local $out = &backquote_logged( "mdadm --manage $_[0]->{'value'} --remove detached 2>&1"); &error(&text('emdadremove', "<tt>$out</tt>")) if ($?); } } # directive_lines(&directive, indent) sub directive_lines { local @rv = ( "$_[1]$_[0]->{'name'}\t$_[0]->{'value'}" ); foreach $m (@{$_[0]->{'members'}}) { push(@rv, &directive_lines($m, $_[1]."\t")); } return @rv; } # find(name, &array) sub find { local($c, @rv); foreach $c (@{$_[1]}) { if ($c->{'name'} eq $_[0]) { push(@rv, $c); } } return @rv ? wantarray ? @rv : $rv[0] : wantarray ? () : undef; } # find_value(name, &array) sub find_value { local(@v); @v = &find($_[0], $_[1]); if (!@v) { return undef; } elsif (wantarray) { return map { $_->{'value'} } @v; } else { return $v[0]->{'value'}; } } # device_status(device) # Returns an array of directory, type, mounted sub device_status { return &fdisk::device_status($_[0]); } # find_free_partitions(&skip, showtype, showsize) # Returns a list of options, suitable for ui_select sub find_free_partitions { &foreign_require("fdisk"); &foreign_require("mount"); &foreign_require("lvm"); local %skip = map { $_, 1 } @{$_[0]}; local %used; local $c; local $conf = &get_raidtab(); foreach $c (@$conf) { foreach $d (&find_value('device', $c->{'members'})) { $used{$d}++; } } local @disks; local $d; foreach $d (&fdisk::list_disks_partitions()) { foreach $p (@{$d->{'parts'}}) { next if ($used{$p->{'device'}} || $p->{'extended'} || $skip{$p->{'device'}}); local @st = &device_status($p->{'device'}); next if (@st); $tag = $p->{'type'} ? &fdisk::tag_name($p->{'type'}) : undef; $p->{'blocks'} =~ s/\+$//; push(@disks, [ $p->{'device'}, $p->{'desc'}. ($tag && $_[1] ? " ($tag)" : ""). (!$_[2] ? "" : $d->{'cylsize'} ? " (".&nice_size($d->{'cylsize'}*($p->{'end'} - $p->{'start'} + 1)).")" : " ($p->{'blocks'} $text{'blocks'})") ]); } if (!@{$d->{'parts'}} && !$used{$d->{'device'}} && !$skip{$d->{'device'}}) { # Raw disk has no partitions - add it as an option push(@disks, [ $d->{'device'}, $d->{'desc'}. ($d->{'cylsize'} ? " (".&nice_size($d->{'cylsize'}*$d->{'cylinders'}).")" : "") ]); } } foreach $c (@$conf) { next if (!$c->{'active'} || $used{$c->{'value'}}); local @st = &device_status($c->{'value'}); next if (@st || $skip{$c->{'value'}}); push(@disks, [ $c->{'value'}, &text('create_rdev', $c->{'value'} =~ /md(\d+)$/ ? "$1" : $c->{'value'}) ]); } local $vg; foreach $vg (&lvm::list_volume_groups()) { local $lv; foreach $lv (&lvm::list_logical_volumes($vg->{'name'})) { next if ($lv->{'perm'} ne 'rw' || $used{$lv->{'device'}} || $skip->{$lv->{'device'}}); local @st = &device_status($lv->{'device'}); next if (@st); push(@disks, [ $lv->{'device'}, &text('create_lvm', $lv->{'vg'}, $lv->{'name'}) ]); } } return sort { $a->[0] cmp $b->[0] } @disks; } # convert_to_hd(device) # Converts a device file like /dev/ide/host0/bus0/target1/lun0/part1 to # /dev/hdb1, if it doesn't actually exist. sub convert_to_hd { local ($dev) = @_; return $dev if (-r $dev); if ($dev =~ /ide\/host(\d+)\/bus(\d+)\/target(\d+)\/lun(\d+)\/part(\d+)/) { local ($host, $bus, $target, $lun, $part) = ($1, $2, $3, $4, $5); return "/dev/".&fdisk::hbt_to_device($host, $bus, $target).$part; } else { return $dev; } } %mdadm_notification_opts = map { $_, 1 } ( 'MAILADDR', 'MAILFROM', 'PROGRAM' ); # get_mdadm_notifications() # Returns a hash from mdadm.conf notification-related settings to values sub get_mdadm_notifications { local $lref = &read_file_lines($config{'mdadm'}); local %rv; foreach my $l (@$lref) { $l =~ s/#.*$//; if ($l =~ /^(\S+)\s+(\S.*)/ && $mdadm_notification_opts{$1}) { $rv{$1} = $2; } } return \%rv; } # save_mdadm_notifications(&notifications) # Updates mdadm.conf with settings from the given hash. Those set to undef # are removed from the file. sub save_mdadm_notifications { local ($notif) = @_; local $lref = &read_file_lines($config{'mdadm'}); local %done; for(my $i=0; $i<@$lref; $i++) { my $l = $lref->[$i]; $l =~ s/#.*$//; local ($k, $v) = split(/\s+/, $l, 2); if (exists($notif->{$k})) { if (defined($notif->{$k})) { $lref->[$i] = "$k $notif->{$k}"; } else { splice(@$lref, $i--, 1); } $done{$k}++; } } foreach my $k (grep { !$done{$_} && defined($notif->{$_}) } keys %$notif) { push(@$lref, "$k $notif->{$k}"); } &flush_file_lines($config{'mdadm'}); } # get_mdadm_action() # Returns the name of an init module action for mdadm monitoring, or undef if # not supported. sub get_mdadm_action { if (&foreign_installed("init")) { &foreign_require("init"); foreach my $a ("mdmonitor", "mdadm", "mdadmd") { local $st = &init::action_status($a); return $a if ($st); } } return undef; } # get_mdadm_monitoring() # Returns 1 if mdadm monitoring is enabled, 0 if not sub get_mdadm_monitoring { local $act = &get_mdadm_action(); if ($act) { &foreign_require("init"); local $st = &init::action_status($act); return $st == 2; } return 0; } # save_mdadm_monitoring(enabled) # Tries to enable or disable mdadm monitoring. Returns an error mesage # if something goes wrong, undef on success sub save_mdadm_monitoring { local ($enabled) = @_; local $act = &get_mdadm_action(); if ($act) { &foreign_require("init"); if ($enabled) { &init::enable_at_boot($act); &init::stop_action($act); sleep(2); local ($ok, $err) = &init::start_action($act); return $err if (!$ok); } else { &init::disable_at_boot($act); &init::stop_action($act); } } return undef; } # update_initramfs() # If the update-initramfs command is installed, run it to update mdadm.conf # in the ramdisk sub update_initramfs { if (&has_command("update-initramfs")) { &system_logged("update-initramfs -u >/dev/null 2>&1 </dev/null"); } } # get_mdadm_version() # Returns the mdadm version number sub get_mdadm_version { local $out = `mdadm --version 2>&1`; local $ver = $out =~ /\s+v([0-9\.]+)/ ? $1 : undef; return wantarray ? ( $ver, $out ) : $ver; } 1;
xtso520ok/webmin
raid/raid-lib.pl
Perl
bsd-3-clause
21,178
=pod =head1 NAME gendsa - generate a DSA private key from a set of parameters =head1 SYNOPSIS B<openssl> B<gendsa> [B<-out filename>] [B<-des>] [B<-des3>] [B<-idea>] [B<-rand file(s)>] [B<-engine id>] [B<paramfile>] =head1 DESCRIPTION The B<gendsa> command generates a DSA private key from a DSA parameter file (which will be typically generated by the B<openssl dsaparam> command). =head1 OPTIONS =over 4 =item B<-des|-des3|-idea> These options encrypt the private key with the DES, triple DES, or the IDEA ciphers respectively before outputting it. A pass phrase is prompted for. If none of these options is specified no encryption is used. =item B<-rand file(s)> a file or files containing random data used to seed the random number generator, or an EGD socket (see L<RAND_egd(3)|RAND_egd(3)>). Multiple files can be specified separated by a OS-dependent character. The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for all others. =item B<-engine id> specifying an engine (by its unique B<id> string) will cause B<gendsa> to attempt to obtain a functional reference to the specified engine, thus initialising it if needed. The engine will then be set as the default for all available algorithms. =item B<paramfile> This option specifies the DSA parameter file to use. The parameters in this file determine the size of the private key. DSA parameters can be generated and examined using the B<openssl dsaparam> command. =back =head1 NOTES DSA key generation is little more than random number generation so it is much quicker that RSA key generation for example. =head1 SEE ALSO L<dsaparam(1)|dsaparam(1)>, L<dsa(1)|dsa(1)>, L<genrsa(1)|genrsa(1)>, L<rsa(1)|rsa(1)> =cut
GaloisInc/hacrypto
src/C/libssl/HEAD/src/doc/apps/gendsa.pod
Perl
bsd-3-clause
1,710
/* Part of SWISH Author: Jan Wielemaker E-mail: J.Wielemaker@cs.vu.nl WWW: http://www.swi-prolog.org Copyright (C): 2017, VU University Amsterdam CWI Amsterdam 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ :- module(swish_data_sparql, []). :- use_module(library(semweb/sparql_client)). :- use_module(library(semweb/rdf11)). :- use_module(library(option)). :- use_module('../data_source'). /** <module> Data source handler for SPARQL endpoints This handler deals with from a SPARQL endpoint. Given a SELECT query with variables Name1, Name2, ... it creates a data source with columns Name1, Name1_t, Name2, Name2_t, ... The `_t` column contains the type, which is either `iri`, a language name or a type name. Values are translated into their Prolog native representation according to library(semweb/rdf11). */ :- multifile swish_data_source:source/2. swish_data_source:source(sparql(Query, Options), swish_data_sparql:import_sparql(Query, Options)). /******************************* * SPARQL IMPORT * *******************************/ :- public import_sparql/3. import_sparql(Query, Options, Hash) :- add_varnames(Options, VarNames, Options1), State = state(-), setup_call_catcher_cleanup( true, once(( forall(sparql_query(Query, Row, Options1), assert_row(Hash, Row, State, VarNames)), arg(1, State, Signature), Signature \== (-) )), Catcher, finalize(Catcher, Hash, State, import_sparql(Query, Options))). finalize(exit, Hash, state(Signature), _Action) :- 'data materialized'(Hash, Signature, version{}). finalize(Reason, Hash, state(Signature), Action) :- ( Signature == (-) -> true ; 'data failed'(Hash, Signature) ), ( Reason = exception(Ex) -> throw(Ex) ; throw(error(failure_error(Action))) ). add_varnames(Options, VarNames, Options) :- option(variable_names(VarNames), Options), !. add_varnames(Options, VarNames, [variable_names(VarNames)|Options]). assert_row(Hash, Row, State, VarNames) :- create_signature(State, Hash, VarNames), Row =.. [_|Values], make_row(Values, Columns), DBRow =.. [Hash|Columns], 'data assert'(DBRow). make_row([], []). make_row([V|VT], [Value,Type|RT]) :- type_value(V, Type, Value), make_row(VT, RT). type_value(literal(Literal), Type, Value) :- !, literal_type_value(Literal, Type, Value). type_value(IRI, iri, IRI). literal_type_value(lang(Lang, Text), Lang, String) :- !, atom_string(Text, String). literal_type_value(type(Type, Text), Type, Val) :- !, ( catch(rdf11:out_type(Type, Val, Text), _, fail) -> true ; atom_string(Text, Val) ). literal_type_value(Plain, Type, Value) :- ( atom_number(Plain, Value) -> ( integer(Value) -> rdf_equal(Type, xsd:integer) ; rdf_equal(Type, xsd:double) ) ; atom_string(Plain, Value), rdf_equal(Type, xsd:string) ). create_signature(State, Hash, VarNames) :- State == state(-), !, add_types(VarNames, ColNames), Signature =.. [Hash|ColNames], nb_setarg(1, State, Signature). create_signature(_, _, _). add_types([], []). add_types([H|T0], [H,Type|T]) :- atom_concat(H, '_t', Type), add_types(T0, T).
TeamSPoon/logicmoo_workspace
packs_web/swish/lib/data/sparql.pl
Perl
mit
4,745
#!/usr/bin/env perl use strict; use warnings; use Factory::LumiaFactory; my $factory = Factory::LumiaFactory->new; my $nokia = $factory->create; $nokia->call(911);
PoisonBOx/design-patterns
src/factory-method/perl/test.pl
Perl
mit
166
package Bogus::TooOld; $VERSION = 0.01; use strict; 1;
gitpan/CPAN-Reporter
t/perl5lib/Bogus/TooOld.pm
Perl
apache-2.0
55
package Paws::SES::GetIdentityPoliciesResponse; use Moose; has Policies => (is => 'ro', isa => 'Paws::SES::PolicyMap', required => 1); has _request_id => (is => 'ro', isa => 'Str'); 1; ### main pod documentation begin ### =head1 NAME Paws::SES::GetIdentityPoliciesResponse =head1 ATTRIBUTES =head2 B<REQUIRED> Policies => L<Paws::SES::PolicyMap> A map of policy names to policies. =head2 _request_id => Str =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/SES/GetIdentityPoliciesResponse.pm
Perl
apache-2.0
432
package Google::Ads::AdWords::v201406::AdGroupCriterionService::queryResponse; use strict; use warnings; { # BLOCK to scope variables sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201406' } __PACKAGE__->__set_name('queryResponse'); __PACKAGE__->__set_nillable(); __PACKAGE__->__set_minOccurs(); __PACKAGE__->__set_maxOccurs(); __PACKAGE__->__set_ref(); use base qw( SOAP::WSDL::XSD::Typelib::Element Google::Ads::SOAP::Typelib::ComplexType ); 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 %rval_of :ATTR(:get<rval>); __PACKAGE__->_factory( [ qw( rval ) ], { 'rval' => \%rval_of, }, { 'rval' => 'Google::Ads::AdWords::v201406::AdGroupCriterionPage', }, { 'rval' => 'rval', } ); } # end BLOCK } # end of BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201406::AdGroupCriterionService::queryResponse =head1 DESCRIPTION Perl data type class for the XML Schema defined element queryResponse from the namespace https://adwords.google.com/api/adwords/cm/v201406. =head1 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * rval $element->set_rval($data); $element->get_rval(); =back =head1 METHODS =head2 new my $element = Google::Ads::AdWords::v201406::AdGroupCriterionService::queryResponse->new($data); Constructor. The following data structure may be passed to new(): { rval => $a_reference_to, # see Google::Ads::AdWords::v201406::AdGroupCriterionPage }, =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201406/AdGroupCriterionService/queryResponse.pm
Perl
apache-2.0
1,808
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the 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 XrefMapper::anopheles_gambiae; use XrefMapper::BasicMapper; use XrefMapper::VBCoordinateMapper; use vars '@ISA'; @ISA = qw{ XrefMapper::BasicMapper }; sub set_methods{ my $default_method = 'ExonerateGappedBest1_55_perc_id'; my %override_method_for_source = ( ExonerateGappedBest5_55_perc_id => ['RefSeq_mRNA','RefSeq_mRNA_predicted', 'RefSeq_ncRNA', 'RefSeq_ncRNA_predicted' ], ); return $default_method, \%override_method_for_source; } # transcript, gene display_xrefs can use defaults # since anopheles_symbol is "before" Uniprot # If there is an Anopheles_symbol xref, use its description # mh4 says Anopheles_symbol doesn't get chosen over UniP # (but they do get chosen in other cases) sub gene_description_sources { return ("VB_Community_Annotation", "Uniprot/SWISSPROT", "VB_RNA_Description", ); } sub transcript_display_xref_sources { my @list = qw( VB_Community_Annotation Uniprot/SWISSPROT VB_RNA_Description ); my %ignore; return [\@list,\%ignore]; } # regexps to match any descriptons we want to filter out sub gene_description_filter_regexps { return (); } 1;
mjg17/ensembl
misc-scripts/xref_mapping/XrefMapper/anopheles_gambiae.pm
Perl
apache-2.0
1,818
% dcg_pfc: translation of dcg-like grammar rules into pfc rules. :- if(( ( \+ ((current_prolog_flag(logicmoo_include,Call),Call))) )). :- module(pfc_dcg,[]). :- endif. :- op(1200,xfx,'-->>'). :- op(1200,xfx,'--*>>'). % :- op(1200,xfx,'<<--'). :- op(400,yfx,'\\\\'). % :- use_module(library(strings)), use_module(library(lists)). mpred_translate_rule((LP-->>[]),H) :- !, mpred_t_lp(LP,_Id,S,S,H). mpred_translate_rule((LP-->>RP),(H <= B)):- mpred_t_lp(LP,Id,S,SR,H), mpred_t_rp(RP,Id,S,SR,B1), mpred_tidy(B1,B). mpred_translate_rule((LP--*>>[]),H) :- !, mpred_t_lp(LP,_Id,S,S,H). mpred_translate_rule((LP--*>>RP),(B ==> H)):- mpred_t_lp(LP,Id,S,SR,H), mpred_t_rp(RP,Id,S,SR,B1), mpred_tidy(B1,B). mpred_t_lp(X,Id,S,SR,ss(X,Id,(S \\ SR))) :- var(X),!. mpred_t_lp((LP,List),Id,S,SR,ss(LP,Id,(S \\ List2))):- !, append(List,SR,List2). mpred_t_lp(LP,Id,S,SR,ss(LP,Id,(S \\ SR))). mpred_t_rp(!,_Id,S,S,!) :- !. mpred_t_rp([],_Id,S,S1,S=S1) :- !. mpred_t_rp([X],Id,S,SR,ss(word(X),Id,(S \\ SR))) :- !. mpred_t_rp([X|R],Id,S,SR,(ss(word(X),Id,(S \\ SR1)),RB)) :- !, mpred_t_rp(R,Id,SR1,SR,RB). mpred_t_rp({T},_Id,S,S,{T}) :- !. mpred_t_rp((T,R),Id,S,SR,(Tt,Rt)) :- !, mpred_t_rp(T,Id,S,SR1,Tt), mpred_t_rp(R,Id,SR1,SR,Rt). mpred_t_rp((T;R),Id,S,SR,(Tt;Rt)) :- !, mpred_t_or(T,Id,S,SR,Tt), mpred_t_or(R,Id,S,SR,Rt). mpred_t_rp(T,Id,S,SR,ss(T,Id,(S \\ SR))). mpred_t_or(X,Id,S0,S,P) :- mpred_t_rp(X,Id,S0a,S,Pa), ( var(S0a), (\==(S0a,S)), !, S0=S0a, P=Pa; P=(S0=S0a,Pa) ). mpred_tidy((P1;P2),(Q1;Q2)) :- !, mpred_tidy(P1,Q1), mpred_tidy(P2,Q2). mpred_tidy(((P1,P2),P3),Q) :- mpred_tidy((P1,(P2,P3)),Q). mpred_tidy((P1,P2),(Q1,Q2)) :- !, mpred_tidy(P1,Q1), mpred_tidy(P2,Q2). mpred_tidy(A,A) :- !. :- was_dynamic(sentence/2). compile_pfcg :- ((retract((L -->> R)), mpred_translate_rule((L -->> R), PfcRule)); (retract((L --*>> R)), mpred_translate_rule((L --*>> R), PfcRule))), ain(PfcRule), fail. compile_pfcg. parse(Words) :- parse(Words,Id), format("~N% sentence id = ~w",Id), show(Id,sentence(_X)). parse(Words,Id) :- gen_s_tag(Id), parse1(Words,Id), ain(sentence(Id,Words)). parse1([],_) :- !. parse1([H|T],Id) :- l_do(ain(ss(word(H),Id,([H|T] \\ T)))), parse1(T,Id). :- was_dynamic(sentences/2). show_sentences(Id) :- show_sentences(Id,_). show_sentences(Id,Words) :- sentence(Id,Words), call_u(ss(s(S),Id,(Words \\ []))), nl,write(S), fail. show_sentences(_,_). :- meta_predicate l_do(0). l_do(X) :- call(X) -> true;true. show(Id,C) :- call_u(ss(C,Id,A \\ B)), append(Words,B,A), format("~N% ~w : ~w",[C,Words]), fail. gen_s_tag(s(N2)) :- % var(_V), (retract(s_tag(N)); N=0), N2 is N+1, assert(s_tag(N2)). make_term(ss(Constituent,Id,String),Term) :- Constituent =.. [Name|Args], name(Name,Name_string), name(Name2,[36|Name_string]), append([Name2|Args],[Id,String],Term_string), Term =.. Term_string. is_mpred_term_expansion((P -->> Q),(:- ain(Rule))) :- mpred_translate_rule((P -->> Q), Rule). is_mpred_term_expansion((P --*>> Q),(:- ain(Rule))) :- mpred_translate_rule((P --*>> Q), Rule).
TeamSPoon/pfc
prolog/pfc_dcg.pl
Perl
bsd-2-clause
3,161
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 6.2.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. return <<'END'; 0300 036F 0483 0489 0591 05BD 05BF 05C1 05C2 05C4 05C5 05C7 0610 061A 064B 065F 0670 06D6 06DC 06DF 06E4 06E7 06E8 06EA 06ED 0711 0730 074A 07A6 07B0 07EB 07F3 0816 0819 081B 0823 0825 0827 0829 082D 0859 085B 08E4 08FE 0900 0903 093A 093C 093E 094F 0951 0957 0962 0963 0981 0983 09BC 09BE 09C4 09C7 09C8 09CB 09CD 09D7 09E2 09E3 0A01 0A03 0A3C 0A3E 0A42 0A47 0A48 0A4B 0A4D 0A51 0A70 0A71 0A75 0A81 0A83 0ABC 0ABE 0AC5 0AC7 0AC9 0ACB 0ACD 0AE2 0AE3 0B01 0B03 0B3C 0B3E 0B44 0B47 0B48 0B4B 0B4D 0B56 0B57 0B62 0B63 0B82 0BBE 0BC2 0BC6 0BC8 0BCA 0BCD 0BD7 0C01 0C03 0C3E 0C44 0C46 0C48 0C4A 0C4D 0C55 0C56 0C62 0C63 0C82 0C83 0CBC 0CBE 0CC4 0CC6 0CC8 0CCA 0CCD 0CD5 0CD6 0CE2 0CE3 0D02 0D03 0D3E 0D44 0D46 0D48 0D4A 0D4D 0D57 0D62 0D63 0D82 0D83 0DCA 0DCF 0DD4 0DD6 0DD8 0DDF 0DF2 0DF3 0E31 0E34 0E3A 0E47 0E4E 0EB1 0EB4 0EB9 0EBB 0EBC 0EC8 0ECD 0F18 0F19 0F35 0F37 0F39 0F3E 0F3F 0F71 0F84 0F86 0F87 0F8D 0F97 0F99 0FBC 0FC6 102B 103E 1056 1059 105E 1060 1062 1064 1067 106D 1071 1074 1082 108D 108F 109A 109D 135D 135F 1712 1714 1732 1734 1752 1753 1772 1773 17B4 17D3 17DD 180B 180D 18A9 1920 192B 1930 193B 19B0 19C0 19C8 19C9 1A17 1A1B 1A55 1A5E 1A60 1A7C 1A7F 1B00 1B04 1B34 1B44 1B6B 1B73 1B80 1B82 1BA1 1BAD 1BE6 1BF3 1C24 1C37 1CD0 1CD2 1CD4 1CE8 1CED 1CF2 1CF4 1DC0 1DE6 1DFC 1DFF 200C 200D 20D0 20F0 2CEF 2CF1 2D7F 2DE0 2DFF 302A 302F 3099 309A A66F A672 A674 A67D A69F A6F0 A6F1 A802 A806 A80B A823 A827 A880 A881 A8B4 A8C4 A8E0 A8F1 A926 A92D A947 A953 A980 A983 A9B3 A9C0 AA29 AA36 AA43 AA4C AA4D AA7B AAB0 AAB2 AAB4 AAB7 AAB8 AABE AABF AAC1 AAEB AAEF AAF5 AAF6 ABE3 ABEA ABEC ABED FB1E FE00 FE0F FE20 FE26 FF9E FF9F 101FD 10A01 10A03 10A05 10A06 10A0C 10A0F 10A38 10A3A 10A3F 11000 11002 11038 11046 11080 11082 110B0 110BA 11100 11102 11127 11134 11180 11182 111B3 111C0 116AB 116B7 16F51 16F7E 16F8F 16F92 1D165 1D169 1D16D 1D172 1D17B 1D182 1D185 1D18B 1D1AA 1D1AD 1D242 1D244 E0100 E01EF END
Bjay1435/capstone
rootfs/usr/share/perl/5.18.2/unicore/lib/SB/EX.pl
Perl
mit
2,409
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the 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. use strict; use warnings; use Data::Dumper; use Bio::AlignIO; use Bio::EnsEMBL::Registry; #Auto-configure the registry Bio::EnsEMBL::Registry->load_registry_from_db( -host=>"ensembldb.ensembl.org", -user=>"anonymous", -port=>'5306'); # Get the Compara Adaptor for MethodLinkSpeciesSets my $method_link_species_set_adaptor = Bio::EnsEMBL::Registry->get_adaptor( "Multi", "compara", "MethodLinkSpeciesSet"); my $methodLinkSpeciesSet = $method_link_species_set_adaptor-> fetch_by_dbID("619"); # Define the start and end positions for the alignment my ($pig_start, $pig_end) = (105734307,105739335); # Get the pig *core* Adaptor for Slices my $pig_slice_adaptor = Bio::EnsEMBL::Registry->get_adaptor( "sus_scrofa", "core", "Slice"); # Get the slice corresponding to the region of interest my $pig_slice = $pig_slice_adaptor->fetch_by_region( "chromosome", 15, $pig_start, $pig_end); # Get the Compara Adaptor for GenomicAlignBlocks my $genomic_align_block_adaptor = Bio::EnsEMBL::Registry->get_adaptor( "Multi", "compara", "GenomicAlignBlock"); # The fetch_all_by_MethodLinkSpeciesSet_Slice() returns a ref. # to an array of GenomicAlingBlock objects (pig is the reference species) my $all_genomic_align_blocks = $genomic_align_block_adaptor-> fetch_all_by_MethodLinkSpeciesSet_Slice( $methodLinkSpeciesSet, $pig_slice); # set up an AlignIO to format SimpleAlign output my $alignIO = Bio::AlignIO->newFh(-interleaved => 0, -fh => \*STDOUT, -format => 'clustalw', -idlength => 20); # print the restricted alignments foreach my $genomic_align_block( @{ $all_genomic_align_blocks }) { my $restricted_gab = $genomic_align_block->restrict_between_reference_positions($pig_start, $pig_end); print $alignIO $restricted_gab->get_SimpleAlign; }
ckongEbi/ensembl-compara
docs/workshop/API_workshop_exercises/GenomicAlignBlock_2.pl
Perl
apache-2.0
2,560
#!/usr/bin/perl # Simple script that takes a ticket as input and gets the associated # irods file (if any). It does an iquest query to get the collection # and name and then uses that to 'iget' the file. ($arg1, $arg2, $arg3)=@ARGV; my $ticket = $arg1; if ($arg1 eq "") { printf("Usage: igetbyticket.pl ticket-string\n"); printf("Type 'igetbyticket.pl help' for more\n"); exit(); } if ($arg1 eq "help") { printf("This script gets an iRODS file using a provided ticket.\n"); printf("It does this by running iquest to map the ticket to the file\n"); printf("and then iget to retrieve it. For more about tickets see\n"); printf("https://www.irods.org/index.php/Ticket-based_Access .\n"); exit(); } my $verbose = '0'; my $iquest = "iquest"; # just assuming it's in the path for now my $iget = "iget"; # just assuming it's in the path for now my $command = "$iquest \"%s/%s\" \"select TICKET_DATA_COLL_NAME, TICKET_DATA_NAME where TICKET_STRING = \'$ticket\'\" "; if ($verbose==1) { print "running: $command \n"; } my $output = `$command`; my $cmdStat=$?; chomp($output); if ($verbose==1) { print "out:" . $output . ":\n"; } my $fullFilePath=$output; if ($cmdStat != 0) { printf("Not found\n"); exit(); } my $command = "$iget -t $ticket $fullFilePath"; print "getting: $fullFilePath\n"; if ($verbose==1) { print "running: $command \n"; } my $output = `$command`; my $cmdStat=$?;
iychoi/iRODS-FUSE-Mod-v3.3.1
clients/icommands/bin/igetbyticket.pl
Perl
bsd-3-clause
1,430
# Test for checking consistency of on-disk pages for a cluster with # the minimum recovery LSN, ensuring that the updates happen across # all processes. In this test, the updates from the startup process # and the checkpointer (which triggers non-startup code paths) are # both checked. use strict; use warnings; use PostgresNode; use TestLib; use Test::More tests => 1; # Find the largest LSN in the set of pages part of the given relation # file. This is used for offline checks of page consistency. The LSN # is historically stored as a set of two numbers of 4 byte-length # located at the beginning of each page. sub find_largest_lsn { my $blocksize = int(shift); my $filename = shift; my ($max_hi, $max_lo) = (0, 0); open(my $fh, "<:raw", $filename) or die "failed to open $filename: $!"; my ($buf, $len); while ($len = read($fh, $buf, $blocksize)) { $len == $blocksize or die "read only $len of $blocksize bytes from $filename"; my ($hi, $lo) = unpack("LL", $buf); if ($hi > $max_hi or ($hi == $max_hi and $lo > $max_lo)) { ($max_hi, $max_lo) = ($hi, $lo); } } defined($len) or die "read error on $filename: $!"; close($fh); return sprintf("%X/%X", $max_hi, $max_lo); } # Initialize primary node my $primary = get_new_node('primary'); $primary->init(allows_streaming => 1); # Set shared_buffers to a very low value to enforce discard and flush # of PostgreSQL buffers on standby, enforcing other processes than the # startup process to update the minimum recovery LSN in the control # file. Autovacuum is disabled so as there is no risk of having other # processes than the checkpointer doing page flushes. $primary->append_conf("postgresql.conf", <<EOF); # The minimum on GPDB is higher #shared_buffers = 128kB shared_buffers = 512kB autovacuum = off EOF # Start the primary $primary->start; # setup/start a standby $primary->backup('bkp'); my $standby = get_new_node('standby'); $standby->init_from_backup($primary, 'bkp', has_streaming => 1); $standby->start; # Create base table whose data consistency is checked. # Use more data in GPDB, because the block size is larger, and because # in GPDB the data will be distributed across segments. $primary->safe_psql( 'postgres', " CREATE TABLE test1 (a int) WITH (fillfactor = 10); INSERT INTO test1 SELECT generate_series(1, 10000 * 100);"); # Take a checkpoint and enforce post-checkpoint full page writes # which makes the startup process replay those pages, updating # minRecoveryPoint. $primary->safe_psql('postgres', 'CHECKPOINT;'); $primary->safe_psql('postgres', 'UPDATE test1 SET a = a + 1;'); # Wait for last record to have been replayed on the standby. $primary->wait_for_catchup($standby, 'replay', $primary->lsn('insert')); # Fill in the standby's shared buffers with the data filled in # previously. $standby->safe_psql('postgres', 'SELECT count(*) FROM test1;'); # Update the table again, this does not generate full page writes so # the standby will replay records associated with it, but the startup # process will not flush those pages. $primary->safe_psql('postgres', 'UPDATE test1 SET a = a + 1;'); # Extract from the relation the last block created and its relation # file, this will be used at the end of the test for sanity checks. my $blocksize = $primary->safe_psql('postgres', "SELECT setting::int FROM pg_settings WHERE name = 'block_size';"); my $last_block = $primary->safe_psql('postgres', "SELECT pg_relation_size('test1')::int / $blocksize - 1;"); my $relfilenode = $primary->safe_psql('postgres', "SELECT pg_relation_filepath('test1'::regclass);"); # Wait for last record to have been replayed on the standby. $primary->wait_for_catchup($standby, 'replay', $primary->lsn('insert')); # Issue a restart point on the standby now, which makes the checkpointer # update minRecoveryPoint. $standby->safe_psql('postgres', 'CHECKPOINT;'); # Now shut down the primary violently so as the standby does not # receive the shutdown checkpoint, making sure that the startup # process does not flush any pages on its side. The standby is # cleanly stopped, which makes the checkpointer update minRecoveryPoint # with the restart point created at shutdown. $primary->stop('immediate'); $standby->stop('fast'); # Check the data consistency of the instance while offline. This is # done by directly scanning the on-disk relation blocks and what # pg_controldata lets know. my $standby_data = $standby->data_dir; my $offline_max_lsn = find_largest_lsn($blocksize, "$standby_data/$relfilenode"); # Fetch minRecoveryPoint from the control file itself my ($stdout, $stderr) = run_command([ 'pg_controldata', $standby_data ]); my @control_data = split("\n", $stdout); my $offline_recovery_lsn = undef; foreach (@control_data) { if ($_ =~ /^Minimum recovery ending location:\s*(.*)$/mg) { $offline_recovery_lsn = $1; last; } } die "No minRecoveryPoint in control file found\n" unless defined($offline_recovery_lsn); # minRecoveryPoint should never be older than the maximum LSN for all # the pages on disk. ok($offline_recovery_lsn ge $offline_max_lsn, "Check offline that table data is consistent with minRecoveryPoint");
50wu/gpdb
src/test/recovery/t/016_min_consistency.pl
Perl
apache-2.0
5,161
package API::DeliveryServiceRegexes; # # Copyright 2015 Comcast Cable Communications Management, 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. # # # # JvD Note: you always want to put Utils as the first use. Sh*t don't work if it's after the Mojo lines. use UI::Utils; use UI::DeliveryService; use Mojo::Base 'Mojolicious::Controller'; use Data::Dumper; use Common::ReturnCodes qw(SUCCESS ERROR); sub index { my $self = shift; my $rs; if ( &is_privileged($self) ) { $rs = $self->db->resultset('Deliveryservice')->search( undef, { prefetch => [ 'cdn', 'deliveryservice_regexes' ], order_by => 'xml_id' } ); my @regexes; while ( my $row = $rs->next ) { my $cdn_name = defined( $row->cdn_id ) ? $row->cdn->name : ""; my $xml_id = defined( $row->xml_id ) ? $row->xml_id : ""; my $re_rs = $row->deliveryservice_regexes; my @matchlist; while ( my $re_row = $re_rs->next ) { push( @matchlist, { type => $re_row->regex->type->name, pattern => $re_row->regex->pattern, setNumber => $re_row->set_number, } ); } my $delivery_service->{dsName} = $xml_id; $delivery_service->{regexes} = \@matchlist; push( @regexes, $delivery_service ); } return $self->success( \@regexes ); } else { return $self->forbidden("Forbidden. Insufficent privileges."); } } 1;
dneuman64/traffic_control
traffic_ops/app/lib/API/DeliveryServiceRegexes.pm
Perl
apache-2.0
1,847
#!/usr/local/bin/perl #Vincent Nkawu #Information Retrieval #Assignment 2. Part 2 print "Please enter a file path to read from: "; my $file = <>; chomp $file; open(FH, "<$file")|| die "Could not open file $file\n"; my %count; while(my $line = <FH>){ chomp $line; $line =~ tr/[A-Z]/[a-z]/; foreach my $word (split /[^A-Z|^a-z&&^']/, $line){ $wordSS++; $count{$word}++; } } $totalWords = $wordSS - $count{''}; foreach my $word (sort keys %count){ printf "%-25s %s\n", $word, $count{$word}; #write to an output file since terminal cannot display all lines at once unless(open WINPUT, '>>', output123.txt){ die "Unable to create output.txt"; } printf WINPUT "%-25s %s\n", $word, $count{$word}; close(WINPUT); } print"Total number of words is $totalWords \n";
ronaldivinci/Information-Retrieval
Assignment2Part2.pl
Perl
mit
825
#!/usr/local/bin/perl use strict; use warnings; use POSIX; use File::Basename; use File::Path qw(make_path); use FindBin; use YAML::XS 'LoadFile'; use feature 'say'; my $relpath = $FindBin::Bin; my $configpath = dirname(dirname($relpath)); my $config = LoadFile("$configpath/_config.yaml"); my $parentdir = $config->{parentdir}; use lib "$FindBin::Bin/../lib"; use SmaugFunctions qw(forkExecWait getRef); my $chr=$ARGV[0]; my @categs = qw( AT_CG AT_GC AT_TA GC_AT GC_CG GC_TA ); foreach my $categ (@categs) { my $outfile = "$parentdir/output/predicted/tracks/chr${chr}_$categ.wig"; my $headercmd = "echo -e \"variableStep\\tchrom=chr${chr}\" > $outfile"; forkExecWait($headercmd); my $datacmd = "cut -f2,4 $parentdir/output/predicted/chr${chr}.$categ.txt >> $outfile"; forkExecWait($datacmd); }
carjed/smaug-genetics
data_mgmt/process_predicted/toWig.pl
Perl
mit
813
dup(L1, L2) :- L1 = [], L2 = []. dup(L1, L2) :- L1 = [H|T], dup(T,L3), L2 = [H|[H|L3]].
greenstatic/fri-undergraduate-coursework
4 semester/principles of programming languages/3 - Lists/4 - dup.pl
Perl
mit
109
animal([c,o,c,o,d,r,i,l]). animal([t,o,r,t,u,g,a]). animal([l,l,o,p]). animal([g,o,r,r,i,o]). animal([o,n,s,o]). animal([g,a,l,l,i,n,a]). animal([s,o,m,e,r,a]). afegir([],L,L). afegir([X|L1],L2,[X|L3]):-afegir(L1,L2,L3). mutant(X):- animal(A), animal(B), afegir(CapA,CoaA,A), CapA\=[], CoaA\=[], afegir(CapB,CoaB,B), CoaA = CapB, afegir(CapA,B,X).
pabloriutort/Aula
Lenguajes-de-programacion/ProLog/mutants/mutants.pl
Perl
mit
366
:- expects_dialect(lps). % Note the execution of this program is very sensitive to the order % in which the clauses for make_on and make_clear are written. maxTime(5). fluents location(_,_). actions move(_,_). initially location(f,floor), location(b,f),location(e,b), location(a,floor), location(d,a),location(c,d). if true then make_tower([a,b,c,floor]) from T1 to T2. if true then make_tower([f,e,d,floor]) from T1 to T2. clear(Block) at T if Block \= floor, not location(_,Block) at T. clear(floor) at _. make_tower([Block,floor]) from T1 to T2 if make_on(Block,floor) from T1 to T2. make_tower([Block,Place|Places]) from T1 to T3 if Place \= floor, make_tower([Place|Places]) from T1 to T2, make_on(Block,Place) from T2 to T3. make_on(Block,Place) from T1 to T4 if not location(Block,Place) at T1, make_clear(Place) from T1 to T2, make_clear(Block) from T2 to T3, move(Block,Place) from T3 to T4. make_on(Block,Place) from T to T if location(Block,Place) at T. make_clear(Place) from T to T if clear(Place) at T. make_clear(Block) from T1 to T2 if location(Block1,Block) at T1, make_on(Block1,floor) from T1 to T2. move(Block,Place) initiates location(Block,Place). move(Block,_) terminates location(Block,Place). /** <examples> ?- go(Timeline). */
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_lps/examples/CLOUT_workshop/concurrent_towers.pl
Perl
mit
1,323
% test 1 examples example(active(d112), 1, 1). example(active(d20), 1, 1). example(active(d109), 1, 1). example(active(d25), 1, 1). example(active(d26), 1, 1). example(active(d1), 1, 1). example(active(d177), 1, 1). example(active(d91), 1, 1). example(active(d162), 1, 1). example(active(d18), 1, 1). example(active(d52), 1, 1). example(active(d57), 1, 1). example(active(d48), 1, 1). example(active(d183), 1, 1). example(active(d37), 1, 1). example(active(d24), 1, 1). example(active(d60), 1, 1). example(active(d33), 1, 1). example(active(d104), 1, 1). example(active(d64), 1, 1). example(active(d88), -1, 1). example(active(d111), -1, 1). example(active(d160), -1, 1). example(active(d34), -1, 1). example(active(d76), -1, 1). example(active(d156), -1, 1). % test 2 examples example(active(d173), 1, 2). example(active(d56), 1, 2). example(active(d10), 1, 2). example(active(d29), 1, 2). example(active(d159), 1, 2). example(active(d153), 1, 2). example(active(d167), 1, 2). example(active(d172), 1, 2). example(active(d35), 1, 2). example(active(d105), 1, 2). example(active(d107), 1, 2). example(active(d180), 1, 2). example(active(d132), -1, 2). example(active(d14), -1, 2). example(active(d138), -1, 2). example(active(d131), -1, 2). example(active(d42), -1, 2). example(active(d78), -1, 2). % test 3 examples example(active(d44), 1, 3). example(active(d86), 1, 3). example(active(d71), 1, 3). example(active(d31), 1, 3). example(active(d176), 1, 3). example(active(d79), 1, 3). example(active(d145), 1, 3). example(active(d68), 1, 3). example(active(d41), 1, 3). example(active(d129), -1, 3). example(active(d3), -1, 3). example(active(d143), -1, 3). example(active(d7), -1, 3). example(active(d98), -1, 3). example(active(d100), -1, 3). example(active(d114), -1, 3). example(active(d124), -1, 3). example(active(d113), -1, 3). % test 4 example(active(d174), 1, 4). example(active(d128), 1, 4). example(active(d90), 1, 4). example(active(d47), 1, 4). example(active(d54), 1, 4). example(active(d49), 1, 4). example(active(d161), 1, 4). example(active(d148), 1, 4). example(active(d21), 1, 4). example(active(d82), 1, 4). example(active(d137), 1, 4). example(active(d69), 1, 4). example(active(d53), 1, 4). example(active(d67), 1, 4). example(active(d121), 1, 4). example(active(d22), 1, 4). example(active(d123), -1, 4). example(active(d39), -1, 4). % test 5 example(active(d16), 1, 5). example(active(d63), 1, 5). example(active(d12), 1, 5). example(active(d30), 1, 5). example(active(d127), 1, 5). example(active(d170), 1, 5). example(active(d83), 1, 5). example(active(d59), 1, 5). example(active(d61), 1, 5). example(active(d178), 1, 5). example(active(d144), -1, 5). example(active(d182), -1, 5). example(active(d66), -1, 5). example(active(d147), -1, 5). example(active(d65), -1, 5). example(active(d84), -1, 5). example(active(d188), -1, 5). example(active(d55), -1, 5). % test 6 example(active(d106), 1, 6). example(active(d87), 1, 6). example(active(d96), 1, 6). example(active(d149), 1, 6). example(active(d166), 1, 6). example(active(d27), 1, 6). example(active(d108), 1, 6). example(active(d46), 1, 6). example(active(d187), 1, 6). example(active(d117), 1, 6). example(active(d163), 1, 6). example(active(d122), 1, 6). example(active(d146), 1, 6). example(active(d75), 1, 6). example(active(d168), -1, 6). example(active(d185), -1, 6). example(active(d19), -1, 6). example(active(d154), -1, 6). % test 7 example(active(d95), 1, 7). example(active(d51), 1, 7). example(active(d97), 1, 7). example(active(d72), 1, 7). example(active(d85), 1, 7). example(active(d164), 1, 7). example(active(d158), 1, 7). example(active(d81), 1, 7). example(active(d11), 1, 7). example(active(d115), 1, 7). example(active(d152), 1, 7). example(active(d92), 1, 7). example(active(d155), -1, 7). example(active(d40), -1, 7). example(active(d110), -1, 7). example(active(d186), -1, 7). example(active(d62), -1, 7). example(active(d150), -1, 7). % test 8 example(active(d136), 1, 8). example(active(d102), 1, 8). example(active(d6), 1, 8). example(active(d93), 1, 8). example(active(d126), 1, 8). example(active(d43), 1, 8). example(active(d28), 1, 8). example(active(d140), 1, 8). example(active(d101), 1, 8). example(active(d103), 1, 8). example(active(d45), 1, 8). example(active(d120), -1, 8). example(active(d89), -1, 8). example(active(d181), -1, 8). example(active(d179), -1, 8). example(active(d73), -1, 8). example(active(d77), -1, 8). example(active(d141), -1, 8). % test 9 example(active(d58), 1, 9). example(active(d32), 1, 9). example(active(d8), 1, 9). example(active(d74), 1, 9). example(active(d184), 1, 9). example(active(d134), 1, 9). example(active(d80), 1, 9). example(active(d23), 1, 9). example(active(d118), 1, 9). example(active(d94), 1, 9). example(active(d157), 1, 9). example(active(d133), -1, 9). example(active(d142), -1, 9). example(active(d5), -1, 9). example(active(d36), -1, 9). example(active(d17), -1, 9). example(active(d70), -1, 9). example(active(d119), -1, 9). % test 10 example(active(d4), 1, 10). example(active(d125), 1, 10). example(active(d15), 1, 10). example(active(d99), 1, 10). example(active(d165), 1, 10). example(active(d169), 1, 10). example(active(d50), 1, 10). example(active(d151), 1, 10). example(active(d13), 1, 10). example(active(d171), 1, 10). example(active(d116), -1, 10). example(active(d175), -1, 10). example(active(d2), -1, 10). example(active(d38), -1, 10). example(active(d130), -1, 10). example(active(d135), -1, 10). example(active(d9), -1, 10). example(active(d139), -1, 10).
JoseCSantos/GILPS
datasets/mutagenesis/examples.pl
Perl
mit
5,797
# # Copyright 2019 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package storage::dell::fluidfs::snmp::mode::components::substorage; use strict; use warnings; my $mapping = { fluidFSStorageSubsystemType => { oid => '.1.3.6.1.4.1.674.11000.2000.200.1.32.1.2' }, fluidFSStorageSubsystemLunsAccessibility => { oid => '.1.3.6.1.4.1.674.11000.2000.200.1.32.1.3' }, }; my $oid_fluidFSStorageSubsystemEntry = '.1.3.6.1.4.1.674.11000.2000.200.1.32.1'; sub load { my ($self) = @_; push @{$self->{request}}, { oid => $oid_fluidFSStorageSubsystemEntry }; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking storage subsystem"); $self->{components}->{substorage} = {name => 'substorage', total => 0, skip => 0}; return if ($self->check_filter(section => 'substorage')); foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$oid_fluidFSStorageSubsystemEntry}})) { next if ($oid !~ /^$mapping->{fluidFSStorageSubsystemLunsAccessibility}->{oid}\.(.*)$/); my $instance = $1; my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_fluidFSStorageSubsystemEntry}, instance => $instance); next if ($self->check_filter(section => 'substorage', instance => $instance)); $self->{components}->{substorage}->{total}++; $self->{output}->output_add(long_msg => sprintf("storage subsystem '%s' status is '%s' [instance = %s]", $result->{fluidFSStorageSubsystemType}, $result->{fluidFSStorageSubsystemLunsAccessibility}, $instance )); my $exit = $self->get_severity(label => 'default', section => 'substorage', value => $result->{fluidFSStorageSubsystemLunsAccessibility}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Storage subsystem '%s' status is '%s'", $result->{fluidFSStorageSubsystemType}, $result->{fluidFSStorageSubsystemLunsAccessibility} )); } } } 1;
Sims24/centreon-plugins
storage/dell/fluidfs/snmp/mode/components/substorage.pm
Perl
apache-2.0
3,082
:- module(between, [between/3], [assertions, isomodes]). :- comment(title, "Enumeration of integers inside a range"). :- comment(author, "The CLIP Group."). :- comment(module, "This modules enumerates integers between two numbers, or checks that an integer lies within a range"). :- comment(summary, "This modules enumerates integers between two numbers, or checks that an integer lies within a range. If the second purpose is the needed one, it is probably wiser (faster and clearer) to check in the program itself using directly arithmetic predicates."). :- pred between(+Min, +Max, ?N) : number * number * int # "@var{N} is an integer which is greater than or equal to @var{Min} and smaller than or equal to @var{Max}. Both @var{Min} and @var{Max} can be either integer or real numbers.". between(Min, Max, N) :- integer(N), !, N >= Min, N =< Max. between(Min, Max, V) :- var(V), Min =< Max, between_nd(V, Min, Max). between_nd(Min, Min, _). between_nd(N, Min, Max) :- Min < Max, NMin is Min+1, between_nd(N, NMin, Max).
leuschel/ecce
www/CiaoDE/ciao/lib/between.pl
Perl
apache-2.0
1,051
package VMOMI::HostAccessControlEntry; use parent 'VMOMI::DynamicData'; use strict; use warnings; our @class_ancestors = ( 'DynamicData', ); our @class_members = ( ['principal', undef, 0, ], ['group', 'boolean', 0, ], ['accessMode', 'HostAccessMode', 0, ], ); 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/HostAccessControlEntry.pm
Perl
apache-2.0
498
# © Copyright 2011-2012 Tiago Quintino # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. package openmpi; use strict; use warnings; use Recipe; my %fields = (); our @ISA = ("Recipe"); sub new { my $class = shift; my $self = $class->SUPER::new(); my($element); foreach $element (keys %fields) { $self->{_permitted}->{$element} = $fields{$element}; } @{$self}{keys %fields} = values %fields; return $self; } sub name { return "openmpi"; } sub version { return "1.6.4"; } sub url { return "http://www.open-mpi.org/software/ompi/v1.6/downloads/openmpi-1.6.4.tar.gz"; } sub md5 { return "70aa9b6271d904c6b337ca326e6613d1"; } sub sha1 { return "3acfe95f80b19a11b300cae40ce6649dff6df5cf"; } sub configure_command { my $self = shift; return "./configure --disable-visibility --without-cs-fs --with-threads=posix --prefix=" . $self->prefix; } 1;
tlmquintino/cookup
cookbook/openmpi.pm
Perl
apache-2.0
1,093
package Google::Ads::AdWords::v201402::AdGroupBidModifierService::ApiExceptionFault; use strict; use warnings; { # BLOCK to scope variables sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201402' } __PACKAGE__->__set_name('ApiExceptionFault'); __PACKAGE__->__set_nillable(); __PACKAGE__->__set_minOccurs(); __PACKAGE__->__set_maxOccurs(); __PACKAGE__->__set_ref(); use base qw( SOAP::WSDL::XSD::Typelib::Element Google::Ads::AdWords::v201402::ApiException ); } 1; =pod =head1 NAME Google::Ads::AdWords::v201402::AdGroupBidModifierService::ApiExceptionFault =head1 DESCRIPTION Perl data type class for the XML Schema defined element ApiExceptionFault from the namespace https://adwords.google.com/api/adwords/cm/v201402. A fault element of type ApiException. =head1 METHODS =head2 new my $element = Google::Ads::AdWords::v201402::AdGroupBidModifierService::ApiExceptionFault->new($data); Constructor. The following data structure may be passed to new(): $a_reference_to, # see Google::Ads::AdWords::v201402::ApiException =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201402/AdGroupBidModifierService/ApiExceptionFault.pm
Perl
apache-2.0
1,112
# # Copyright 2019 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package centreon::common::broadcom::megaraid::snmp::mode::components::fan; use strict; use warnings; my %map_fan_status = ( 1 => 'status-invalid', 2 => 'status-ok', 3 => 'status-critical', 4 => 'status-nonCritical', 5 => 'status-unrecoverable', 6 => 'status-not-installed', 7 => 'status-unknown', 8 => 'status-not-available' ); my $mapping = { enclosureId => { oid => '.1.3.6.1.4.1.3582.4.1.5.3.1.2' }, fanStatus => { oid => '.1.3.6.1.4.1.3582.4.1.5.3.1.3', map => \%map_fan_status }, }; my $oid_enclosureFanEntry = '.1.3.6.1.4.1.3582.4.1.5.3.1'; sub load { my ($self) = @_; push @{$self->{request}}, { oid => $oid_enclosureFanEntry, start => $mapping->{enclosureId}->{oid}, end => $mapping->{fanStatus}->{oid} }; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking fans"); $self->{components}->{fan} = {name => 'fan', 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_enclosureFanEntry}})) { next if ($oid !~ /^$mapping->{fanStatus}->{oid}\.(.*)$/); my $instance = $1; my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_enclosureFanEntry}, instance => $instance); next if ($self->check_filter(section => 'fan', instance => $instance)); if ($result->{fanStatus} =~ /status-not-installed/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, enclosure = %s]", $instance, $result->{fanStatus}, $instance, $result->{enclosureId})); $exit = $self->get_severity(label => 'default', section => 'fan', value => $result->{fanStatus}); 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->{fanStatus})); } } } 1;
Sims24/centreon-plugins
centreon/common/broadcom/megaraid/snmp/mode/components/fan.pm
Perl
apache-2.0
3,081
=head1 LICENSE Copyright [1999-2013] Wellcome Trust Sanger Institute and the 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 Sanger::Graphics::Glyph::Space; use strict; use base qw(Sanger::Graphics::Glyph); 1;
Ensembl/ensembl-draw
modules/Sanger/Graphics/Glyph/Space.pm
Perl
apache-2.0
744
# # 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 cloud::aws::ec2::mode::instancesstatus; use base qw(centreon::plugins::templates::counter); use strict; use warnings; my $instance_mode; sub custom_status_threshold { my ($self, %options) = @_; my $status = 'ok'; my $message; eval { local $SIG{__WARN__} = sub { $message = $_[0]; }; local $SIG{__DIE__} = sub { $message = $_[0]; }; my $label = $self->{label}; $label =~ s/-/_/g; if (defined($instance_mode->{option_results}->{'critical_' . $label}) && $instance_mode->{option_results}->{'critical_' . $label} ne '' && eval "$instance_mode->{option_results}->{'critical_' . $label}") { $status = 'critical'; } elsif (defined($instance_mode->{option_results}->{'warning_' . $label}) && $instance_mode->{option_results}->{'warning_' . $label} ne '' && eval "$instance_mode->{option_results}->{'warning_' . $label}") { $status = 'warning'; } }; if (defined($message)) { $self->{output}->output_add(long_msg => 'filter status issue: ' . $message); } return $status; } sub custom_status_output { my ($self, %options) = @_; my $msg = sprintf('state: %s, status: %s', $self->{result_values}->{state}, $self->{result_values}->{status}); return $msg; } sub custom_status_calc { my ($self, %options) = @_; $self->{result_values}->{state} = $options{new_datas}->{$self->{instance} . '_state'}; $self->{result_values}->{status} = $options{new_datas}->{$self->{instance} . '_status'}; $self->{result_values}->{display} = $options{new_datas}->{$self->{instance} . '_display'}; return 0; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'global', type => 0, cb_prefix_output => 'prefix_global_output' }, { name => 'aws_instances', type => 1, cb_prefix_output => 'prefix_awsinstance_output', message_multiple => 'All instances are ok' }, ]; $self->{maps_counters}->{global} = [ { label => 'total-pending', set => { key_values => [ { name => 'pending' } ], output_template => "pending : %s", perfdatas => [ { label => 'total_pending', value => 'pending_absolute', template => '%d', min => 0 }, ], } }, { label => 'total-running', set => { key_values => [ { name => 'running' } ], output_template => "running : %s", perfdatas => [ { label => 'total_running', value => 'running_absolute', template => '%d', min => 0 }, ], } }, { label => 'total-shutting-down', set => { key_values => [ { name => 'shutting-down' } ], output_template => "shutting-down : %s", perfdatas => [ { label => 'total_shutting_down', value => 'shutting-down_absolute', template => '%d', min => 0 }, ], } }, { label => 'total-terminated', set => { key_values => [ { name => 'terminated' } ], output_template => "terminated : %s", perfdatas => [ { label => 'total_terminated', value => 'terminated_absolute', template => '%d', min => 0 }, ], } }, { label => 'total-stopping', set => { key_values => [ { name => 'stopping' } ], output_template => "stopping : %s", perfdatas => [ { label => 'total_stopping', value => 'stopping_absolute', template => '%d', min => 0 }, ], } }, { label => 'total-stopped', set => { key_values => [ { name => 'stopped' } ], output_template => "stopped : %s", perfdatas => [ { label => 'total_stopped', value => 'stopped_absolute', template => '%d', min => 0 }, ], } }, ]; $self->{maps_counters}->{aws_instances} = [ { label => 'status', threshold => 0, set => { key_values => [ { name => 'state' }, { name => 'status' }, { name => 'display' } ], closure_custom_calc => $self->can('custom_status_calc'), closure_custom_output => $self->can('custom_status_output'), closure_custom_perfdata => sub { return 0; }, closure_custom_threshold_check => $self->can('custom_status_threshold'), } }, ]; } 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 => { "region:s" => { name => 'region' }, "filter-instanceid:s" => { name => 'filter_instanceid' }, "warning-status:s" => { name => 'warning_status', default => '' }, "critical-status:s" => { name => 'critical_status', default => '' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); if (!defined($self->{option_results}->{region}) || $self->{option_results}->{region} eq '') { $self->{output}->add_option_msg(short_msg => "Need to specify --region option."); $self->{output}->option_exit(); } $instance_mode = $self; $self->change_macros(); } sub prefix_global_output { my ($self, %options) = @_; return "Total instances "; } sub prefix_awsinstance_output { my ($self, %options) = @_; return "Instance '" . $options{instance_value}->{display} . "' "; } sub change_macros { my ($self, %options) = @_; foreach (('warning_status', 'critical_status')) { if (defined($self->{option_results}->{$_})) { $self->{option_results}->{$_} =~ s/%\{(.*?)\}/\$self->{result_values}->{$1}/g; } } } sub manage_selection { my ($self, %options) = @_; $self->{global} = { pending => 0, running => 0, 'shutting-down' => 0, terminated => 0, stopping => 0, stopped => 0, }; $self->{aws_instances} = {}; my $result = $options{custom}->ec2_get_instances_status(region => $self->{option_results}->{region}); foreach my $instance_id (keys %{$result}) { if (defined($self->{option_results}->{filter_instanceid}) && $self->{option_results}->{filter_instanceid} ne '' && $instance_id !~ /$self->{option_results}->{filter_instanceid}/) { $self->{output}->output_add(long_msg => "skipping '" . $instance_id . "': no matching filter.", debug => 1); next; } $self->{aws_instances}->{$instance_id} = { display => $instance_id, state => $result->{$instance_id}->{state}, status => $result->{$instance_id}->{status}, }; $self->{global}->{$result->{$instance_id}->{state}}++; } if (scalar(keys %{$self->{aws_instances}}) <= 0) { $self->{output}->add_option_msg(short_msg => "No aws instance found."); $self->{output}->option_exit(); } } 1; __END__ =head1 MODE Check EC2 instances status. Example: perl centreon_plugins.pl --plugin=cloud::aws::ec2::plugin --custommode=paws --mode=instances-status --region='eu-west-1' --filter-instanceid='.*' --filter-counters='^total-running$' --critical-total-running='10' --verbose See 'https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstanceStatus.html' for more informations. =over 8 =item B<--filter-counters> Only display some counters (regexp can be used). Example: --filter-counters='^total-running$' =item B<--filter-instanceid> Filter by instance id (can be a regexp). =item B<--warning-status> Set warning threshold for status (Default: ''). Can used special variables like: %{state}, %{display} =item B<--critical-status> Set critical threshold for status (Default: ''). Can used special variables like: %{state}, %{display} =item B<--warning-*> Threshold warning. Can be: 'total-pending', 'total-running', 'total-shutting-down', 'total-terminated', 'total-stopping', 'total-stopped'. =item B<--critical-*> Threshold critical. Can be: 'total-pending', 'total-running', 'total-shutting-down', 'total-terminated', 'total-stopping', 'total-stopped'. =back =cut
wilfriedcomte/centreon-plugins
cloud/aws/ec2/mode/instancesstatus.pm
Perl
apache-2.0
9,446
package Google::Ads::AdWords::v201809::OfflineConversionAdjustmentFeedService::mutate; use strict; use warnings; { # BLOCK to scope variables sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201809' } __PACKAGE__->__set_name('mutate'); __PACKAGE__->__set_nillable(); __PACKAGE__->__set_minOccurs(); __PACKAGE__->__set_maxOccurs(); __PACKAGE__->__set_ref(); use base qw( SOAP::WSDL::XSD::Typelib::Element Google::Ads::SOAP::Typelib::ComplexType ); 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 %operations_of :ATTR(:get<operations>); __PACKAGE__->_factory( [ qw( operations ) ], { 'operations' => \%operations_of, }, { 'operations' => 'Google::Ads::AdWords::v201809::OfflineConversionAdjustmentFeedOperation', }, { 'operations' => 'operations', } ); } # end BLOCK } # end of BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201809::OfflineConversionAdjustmentFeedService::mutate =head1 DESCRIPTION Perl data type class for the XML Schema defined element mutate from the namespace https://adwords.google.com/api/adwords/cm/v201809. Reports a conversion adjustment for each entry in {@code operations}. <p><b>Note:</b> {@link OfflineConversionAdjustmentFeedOperation} supports only the {@code ADD} operator. ({@code SET} and {@code REMOVE} are not supported.) @param operations A list of offline conversion adjustment feed operations. @return The list of offline conversion adjustment feed results in the same order as the operations. @throws {@link ApiException} If problems occurred while applying offline adjustment conversions. =head1 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * operations $element->set_operations($data); $element->get_operations(); =back =head1 METHODS =head2 new my $element = Google::Ads::AdWords::v201809::OfflineConversionAdjustmentFeedService::mutate->new($data); Constructor. The following data structure may be passed to new(): { operations => $a_reference_to, # see Google::Ads::AdWords::v201809::OfflineConversionAdjustmentFeedOperation }, =head1 AUTHOR Generated by SOAP::WSDL =cut
googleads/googleads-perl-lib
lib/Google/Ads/AdWords/v201809/OfflineConversionAdjustmentFeedService/mutate.pm
Perl
apache-2.0
2,429
#!/usr/bin/env perl # 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. use warnings ; use strict; use Getopt::Long qw(:config no_ignore_case); use Bio::EnsEMBL::DBSQL::DBAdaptor; use Bio::EnsEMBL::Mapper; $| = 1; my ($dbname, $dbuser, $dbhost, $dbport, $verbose, $agp_outfile, $agp_outfh, $gene_outfile, $gene_outfh, $log_outfile, $log_outfh, @agp_files, @gene_files); $dbport = 3306; GetOptions('agp=s@' => \@agp_files, 'genes=s@' => \@gene_files, 'outagp=s' => \$agp_outfile, 'outgenes=s' => \$gene_outfile, 'outlog=s' => \$log_outfile, 'verbose' => \$verbose, 'dbname|db|D=s' => \$dbname, 'dbhost|host|h=s' => \$dbhost, 'dbuser|user|u=s' => \$dbuser, 'dbport|port|P=s' => \$dbport); $| = 1; my $DB = Bio::EnsEMBL::DBSQL::DBAdaptor->new(-dbname => $dbname, -host => $dbhost, -user => $dbuser, -port => $dbport); my $FAKE_SCAFFOLD_PREFIX = 'DUMMYSCAFFOLD_'; my $GENE_SCAFFOLD_PREFIX = 'GeneScaffold_'; my $fake_scaffold_count = 1; my $GENE_SCAFFOLD_PADDING = 100; if (defined $agp_outfile) { open $agp_outfh, ">$agp_outfile" or die "Could not open $agp_outfile for writing\n"; } else { $agp_outfh = \*STDOUT; } if (defined $gene_outfile) { open $gene_outfh, ">$gene_outfile" or die "Could not open $gene_outfile for writing\n"; } else { $gene_outfh = \*STDOUT; } if (defined $log_outfile) { open $log_outfh, ">$log_outfile" or die "Could not open $log_outfile for writing\n"; } else { $log_outfh = \*STDERR; } $verbose and print STDERR "Indexing AGP files...\n"; my ($gs_index, $s_index) = &index_gene_scaffold_files(@agp_files); $verbose and print STDERR "Indexing Annotation files...\n"; &index_gene_annotation_files(@gene_files); my @clusters; if (@ARGV) { @clusters = ([@ARGV]); } else { $verbose and print STDERR "Clustering gene scaffolds...\n"; @clusters = &single_linkage_cluster($gs_index, $s_index); } my $out_gene_scaffold_count = 1; for(my $cl_cnt=0; $cl_cnt < @clusters; $cl_cnt++) { my $cluster = $clusters[$cl_cnt]; $verbose and print STDERR "Doing $cl_cnt Cluster @$cluster\n"; print $log_outfh "CLUSTER: ", join("|", @$cluster), "\n"; my $gene_scaffolds = {}; &fetch_gene_scaffold_entries($gene_scaffolds, @$cluster); &fetch_gene_annotation_entries($gene_scaffolds, @$cluster); # transcript filtering could have left gene scaffold fragments # that have no exons; remove these #&remove_unused_components_from_gene_scaffolds($gene_scaffolds); # add in the gaps we have "plugged" as fake components &identify_plugged_gaps($gene_scaffolds); # we need the slices and their seq-level component structure for # assessing scaffold splits my ($target_slices, $target_slice_maps) = &fetch_slices_and_component_maps($DB, $gene_scaffolds); # make list of "non trivial" gene scaffolds, which are those # that involve more than one component my (%simple_gene_scaffolds, %complex_gene_scaffolds); foreach my $gs_id (keys %$gene_scaffolds) { if (&is_simple_gene_scaffold($gs_id, $gene_scaffolds)) { $simple_gene_scaffolds{$gs_id} = $gene_scaffolds->{$gs_id}; } else { $complex_gene_scaffolds{$gs_id} = $gene_scaffolds->{$gs_id}; } } my $chains = &make_gene_scaffold_chains(\%complex_gene_scaffolds); my $extended_chains = &extend_gene_scaffold_components($chains, \%complex_gene_scaffolds, \%simple_gene_scaffolds, $target_slices, $target_slice_maps); # make a map to/from Gene scaffold coords and component coords my $orig_map = Bio::EnsEMBL::Mapper->new('scaffold', 'genescaffold'); my $new_map = Bio::EnsEMBL::Mapper->new('scaffold', 'genescaffold'); foreach my $gs_id (keys %$gene_scaffolds) { my $gs = $gene_scaffolds->{$gs_id}; foreach my $seg (@{$gs->{components}}) { $orig_map->add_map_coordinates($seg->to->id, $seg->to->start, $seg->to->end, $seg->to->strand, $gs_id, $seg->from->start, $seg->from->end, ); } } foreach my $ch (@$extended_chains) { my @gs_ids = @{$ch->{members}}; my $new_gs_name = $GENE_SCAFFOLD_PREFIX . $out_gene_scaffold_count++; print $agp_outfh "##-AGP for $new_gs_name [@gs_ids]\n"; my @coords = @{$ch->{merged_coords}}; my $last_end = 0; my $line_count = 1; for(my $i=0; $i < @coords; $i++) { my $c = $coords[$i]; my $gs_start = $last_end + 1; $last_end = $gs_start + $c->length - 1; $new_map->add_map_coordinates($c->id, $c->start, $c->end, $c->strand, $new_gs_name, $gs_start, $last_end, ); if ($c->id =~ /^$FAKE_SCAFFOLD_PREFIX/) { printf($agp_outfh "%s\t%d\t%d\t%d\tN\t%d\n", $new_gs_name, $gs_start, $last_end, $line_count++, $last_end - $gs_start + 1); } else { printf($agp_outfh "%s\t%d\t%d\t%d\tW\t%s\t%d\t%d\t%s\n", $new_gs_name, $gs_start, $last_end, $line_count++, $c->id, $c->start, $c->end, $c->strand > 0 ? "+" : "-"); } unless ($i == @coords - 1) { $gs_start = $last_end + 1; $last_end = $gs_start + $GENE_SCAFFOLD_PADDING - 1; printf($agp_outfh "%s\t%d\t%d\t%d\tN\t%d\n", $new_gs_name, $gs_start, $last_end, $line_count++, $last_end - $gs_start + 1); } } printf $gene_outfh "# GENE for $new_gs_name [@gs_ids]\n"; foreach my $gs_id (@gs_ids) { foreach my $line (@{$gene_scaffolds->{$gs_id}->{annotation}}) { if (ref($line) ne "ARRAY") { print $gene_outfh $line; next; } my ($loc_in_orig) = $orig_map->map_coordinates($line->[0], $line->[3], $line->[4], $line->[5], 'genescaffold'); my ($loc_in_new) = $new_map->map_coordinates($loc_in_orig->id, $loc_in_orig->start, $loc_in_orig->end, $loc_in_orig->strand, 'scaffold'); $line->[0] = $new_gs_name; $line->[3] = $loc_in_new->start; $line->[4] = $loc_in_new->end; $line->[5] = $loc_in_new->strand; print $gene_outfh join("\t", @$line); } } } # we need to deal with the simple gene scaffolds which refer # to a component that has ended up in this gene scaffold foreach my $gs_id (keys %simple_gene_scaffolds) { my @cmps = @{$simple_gene_scaffolds{$gs_id}->{components}}; my %result_gs; foreach my $cmp (@cmps) { my ($loc_in_orig) = $orig_map->map_coordinates($gs_id, $cmp->from->start, $cmp->from->end, 1, 'genescaffold'); my ($loc_in_new) = $new_map->map_coordinates($loc_in_orig->id, $loc_in_orig->start, $loc_in_orig->end, 1, 'scaffold'); if ($loc_in_new->isa("Bio::EnsEMBL::Mapper::Coordinate")) { $result_gs{$loc_in_new->id}++; } } if (scalar(keys %result_gs) == 1) { my ($other_gs) = keys %result_gs; foreach my $line (@{$simple_gene_scaffolds{$gs_id}->{annotation}}) { if (ref($line) ne "ARRAY") { print $gene_outfh $line; next; } my ($loc_in_orig) = $orig_map->map_coordinates($line->[0], $line->[3], $line->[4], $line->[5], 'genescaffold'); my ($loc_in_new) = $new_map->map_coordinates($loc_in_orig->id, $loc_in_orig->start, $loc_in_orig->end, $loc_in_orig->strand, 'scaffold'); $line->[0] = $loc_in_new->id; $line->[3] = $loc_in_new->start; $line->[4] = $loc_in_new->end; $line->[5] = $loc_in_new->strand; print $gene_outfh join("\t", @$line); } delete $simple_gene_scaffolds{$gs_id}; print $log_outfh "WRITE: Accommodated annotation for $gs_id into $other_gs\n"; } elsif (scalar(keys %result_gs)) { delete $simple_gene_scaffolds{$gs_id}; print($log_outfh "WRITE: Simple gs $gs_id is split between >1 complex ones so rejecting : " . join(",", keys %result_gs) ."\n"); } } # for all of the remaining simple gene scaffolds, the annotation # can be written directly without need for agp foreach my $gs_id (keys %simple_gene_scaffolds) { printf $gene_outfh "# GENE output for %s\n", $gs_id; foreach my $line (@{$simple_gene_scaffolds{$gs_id}->{annotation}}) { if (ref($line) ne "ARRAY") { print $gene_outfh $line; next; } my ($mapped_reg) = $orig_map->map_coordinates($line->[0], $line->[3], $line->[4], 1, 'genescaffold'); $line->[0] = $mapped_reg->id; $line->[3] = $mapped_reg->start; $line->[4] = $mapped_reg->end; if ($simple_gene_scaffolds{$gs_id}->{components}->[0]->to->strand < 0) { $line->[5] *= -1; } print $gene_outfh join("\t", @$line); } print $log_outfh "WRITE: Accommodated annotation for $gs_id without gene scaffold\n"; } } ################################################################# # single_linkage_cluster # # Single-linkage cluster the gene_scaffolds based on common # scaffold ################################################################# sub single_linkage_cluster { my ($gs_index, $s_index) = @_; my %clusters; foreach my $gs_id (keys %{$gs_index}) { # find out which scaffold are implicated in this gene scaf # find other gene scafs that share these scaffolds # form a cluster, and make all gene scaf ids, and their cluster # members, # point to the same cluster my @other_gs_ids; foreach my $s_id (keys %{$gs_index->{$gs_id}}) { # look for other gene scaffold that are involved in this scaffold foreach my $other_gs_id (keys %{$s_index->{$s_id}}) { push @other_gs_ids, $other_gs_id if $other_gs_id ne $gs_id; } } my (%new_cluster); $new_cluster{$gs_id} = 1; # merge with existing clusters foreach my $other_gs_id (@other_gs_ids) { if (exists $clusters{$other_gs_id}) { foreach my $k (keys %{$clusters{$other_gs_id}}) { $new_cluster{$k} = 1; } } $new_cluster{$other_gs_id} = 1; } # make all members of the revised cluster point to it foreach my $gs_mem (keys %new_cluster) { $clusters{$gs_mem} = \%new_cluster; } } # finally, return a list of distinct clusters my %unique_clusters; foreach my $clust (values %clusters) { if (not exists $unique_clusters{$clust}) { my @members = keys %$clust; $unique_clusters{$clust} = \@members; } } my @clusts = values %unique_clusters; @clusts = sort { $a->[0] cmp $b->[0] } @clusts; return @clusts; } ################################################################# # identify_plugged_gaps # # looks for exons that lie on gene_scaffold gaps ################################################################# sub identify_plugged_gaps { my ($gene_scaffolds) = @_; my %plugged_gaps; foreach my $gs_id (keys %{$gene_scaffolds}) { my @lines; foreach my $line (@{$gene_scaffolds->{$gs_id}->{annotation}}) { if (ref($line) eq "ARRAY") { push @lines, $line; } } my @comps = sort { $a->from->start <=> $b->from->start; } @{$gene_scaffolds->{$gs_id}->{components}}; $plugged_gaps{$gs_id} = []; my @gaps; foreach my $l (@lines) { my ($type, $start, $end) = ($l->[2], $l->[3], $l->[4]); next if $type ne 'Exon'; # does this exon lie in a gap? my $in_gap = 1; foreach my $seg (@comps) { if ($start >= $seg->from->start and $end <= $seg->from->end) { $in_gap = 0; last; } } if ($in_gap) { push @gaps, { start => $start, end => $end, }; } } foreach my $gap (sort { $a->{start} <=> $b->{start} } @gaps) { if (@{$plugged_gaps{$gs_id}} and $plugged_gaps{$gs_id}->[-1]->{end} >= $gap->{start}) { if ($gap->{end} > $plugged_gaps{$gs_id}->[-1]->{end}) { $plugged_gaps{$gs_id}->[-1]->{end} = $gap->{end}; } } else { push @{$plugged_gaps{$gs_id}}, $gap; } } } foreach my $gs_id (keys %plugged_gaps) { foreach my $reg (@{$plugged_gaps{$gs_id}}) { my $fake_name = &get_unique_fake_scaffold_id; my $fake_start = 1; my $fake_end = $reg->{end} - $reg->{start} + 1; my $fake_q = Bio::EnsEMBL::Mapper::Coordinate->new($gs_id, $reg->{start}, $reg->{end}, 1); my $fake_t = Bio::EnsEMBL::Mapper::Coordinate->new($fake_name, $fake_start, $fake_end, 1); my $pair = Bio::EnsEMBL::Mapper::Pair->new($fake_q, $fake_t); push @{$gene_scaffolds->{$gs_id}->{components}}, $pair; } $gene_scaffolds->{$gs_id}->{components} = [ sort { $a->from->start <=> $b->from->start; } @{$gene_scaffolds->{$gs_id}->{components}} ]; } } ################################################################# # make_gene_scaffold_chains # # returns a list of chains, each element of which is a # list of AGP references that can be glued together, in # order, to make a larger AGP. Each of the given AGPs # occurs in exactly one of the returned chains ################################################################# sub make_gene_scaffold_chains { my ($gene_scaffolds) = @_; my $go_further = 1; $go_further = 0 if scalar(keys %{$gene_scaffolds}) <= 1; my (@all_chains, %sub_clusters, @shared_sids); if ($go_further) { # form chains based on component composition foreach my $gs_id (keys %{$gene_scaffolds}) { foreach my $comp (@{$gene_scaffolds->{$gs_id}->{components}}) { push @{$sub_clusters{$comp->to->id}->{$gs_id}}, $comp; } } foreach my $s_id (keys %sub_clusters) { if (scalar(keys %{$sub_clusters{$s_id}}) > 1) { push @shared_sids, $s_id; } } if (scalar(@shared_sids) > 1) { print $log_outfh "CHAINING: cluster has more than one shared scaffold: @shared_sids\n"; } elsif (not @shared_sids) { print $log_outfh "CHAINING: odd; cluster had no shared scaffolds\n"; $go_further = 0; } } if ($go_further) { # check that the shared component is self-consistent in each # implicated gene scaffold foreach my $shared_sid (@shared_sids) { my (@extents, @consistent_extents, @chains); GS: foreach my $gs_id (keys %{$sub_clusters{$shared_sid}}) { my @comps = @{$sub_clusters{$shared_sid}->{$gs_id}}; my ($tstart, $tend, $strand); foreach my $comp (@comps) { if (not defined $strand) { $tstart = $comp->to->start; $tend = $comp->to->end; $strand = $comp->to->strand; } else { # need to check for consistency if ($comp->to->strand == $strand) { if ($strand > 0 and $comp->to->start > $tend) { $tend = $comp->to->end; } elsif ($strand < 0 and $comp->to->end < $tstart) { $tstart = $comp->to->start; } else { next GS; } } } } push @extents, { gs_id => $gs_id, qid => $gene_scaffolds->{$gs_id}->{ref_name}, qstart => $gene_scaffolds->{$gs_id}->{ref_start}, qend => $gene_scaffolds->{$gs_id}->{ref_end}, tstart => $tstart, tend => $tend, tstrand => $strand, }; } # generate all possible selections of consistent chains from the list if (scalar(@extents) > 1) { my @sub_lists = _generate_sub_lists(@extents); foreach my $sl (@sub_lists) { my @these_extents = @$sl; # check if this is a consistent sub-list; my $consistent = 1; for(my $i=1; $i < @these_extents; $i++) { my $this = $these_extents[$i]; my $last = $these_extents[$i-1]; if ($this->{qid} eq $last->{qid} and $this->{qstart} > $last->{qend} and $this->{tstrand} == $last->{tstrand} and (($this->{tstrand} > 0 and $this->{tstart} > $last->{tend}) or ($this->{tstrand} < 0 and $this->{tend} < $last->{tstart}))) { # consistent } else { $consistent = 0; last; } } if ($consistent) { push @consistent_extents, $sl; } } } @consistent_extents = sort { scalar(@$b) <=> scalar(@$b) } @consistent_extents; my %gs_in_chains; while (@consistent_extents) { my $first = shift @consistent_extents; my @gs_ids = map { $_->{gs_id} } @$first; if (not grep { exists($gs_in_chains{$_}) } @gs_ids) { push @chains, \@gs_ids; map { $gs_in_chains{$_} = 1 } @gs_ids; } } foreach my $ch (@chains) { print $log_outfh "CHAINING: formed chain " . join(" ", @$ch) . "\n"; push @all_chains, $ch; } } } # attempt to merge consistent chains together @all_chains = sort { scalar(@$b) <=> scalar(@$a) } @all_chains; if (scalar(@all_chains) > 1) { print $log_outfh "CHAINING: Attempting to consolidate ", scalar(@all_chains), " chains\n"; } my @merged_chains; foreach my $c (@all_chains) { my $merged = 0; OC: foreach my $o_c (@merged_chains) { my ($i, $j); for($i=0; $i < @$o_c; $i++) { if ($o_c->[$i] eq $c->[0]) { my $mismatch = 0; for($j=0; $j < @$c and $i < @$o_c ; $j++, $i++) { if ($c->[$j] ne $o_c->[$i]) { $mismatch = 1; } } if (not $mismatch) { for(my $k=$j; $k < @$c; $k++) { push @$o_c, $c->[$k]; } $merged = 1; print $log_outfh "CHAINING: merging ", join(":", @$c), " to ", join(":", @$o_c), "\n"; last OC; } else { last; } } } for($i=scalar(@$o_c)-1; $i>=0; $i--) { if ($o_c->[$i] eq $c->[-1]) { my $mismatch = 0; for($j=scalar(@$c)-1; $j>=0 and $i>=0; $j--, $i--) { if ($c->[$j] ne $o_c->[$i]) { $mismatch = 1; } } if (not $mismatch) { for(my $k=$j; $k >= 0; $k--) { unshift @$o_c, $c->[$k]; } $merged = 1; print $log_outfh "CHAINING: merging ", join(":", @$c), " to ", join(":", @$o_c), "\n"; last OC; } else { last; } } } } if (not $merged) { push @merged_chains, $c; } } # any remaining chains that share elements are removed my %chains_by_el; foreach my $c (@merged_chains) { map { push @{$chains_by_el{$_}}, $c } @$c; } my %delete; foreach my $el (keys %chains_by_el) { if (@{$chains_by_el{$el}} > 1) { foreach my $cref (@{$chains_by_el{$el}}) { map { $delete{$_} = 1 } @$cref; @merged_chains = grep { $_ ne $cref } @merged_chains; } print $log_outfh "CHAINING: $el occurs inconsistently in more than one chain; removing\n"; } } map { delete $chains_by_el{$_} } keys %delete; # finally, we have to make singleton chains for all # gene-scaffolds not in chains foreach my $gs_id (keys %$gene_scaffolds) { if (not exists $chains_by_el{$gs_id}) { push @merged_chains, [$gs_id]; } } foreach my $c (@merged_chains) { print $log_outfh "CHAINING: final chain " . join(":", @$c), "\n"; } return \@merged_chains; } sub _generate_sub_lists { my @list = @_; if (scalar(@list) == 2) { return ([$list[0], $list[1]],[$list[1],$list[0]]); } else { my ($first, @rest) = @list; my @s_lists = &_generate_sub_lists(@rest); if (scalar(@s_lists) > 50_000) { print "!!!! Bailing out of combinatorial explosion !!!!!\n"; return @s_lists; } my @new_s_lists; foreach my $sl (@s_lists) { my @this_list = @$sl; my $size = scalar(@this_list); push @new_s_lists, [$first, @this_list]; for(my $i = 0; $i < $size - 1; $i++) { my @new_list = (@this_list[0..$i], $first, @this_list[$i+1..$size-1]); push @new_s_lists, \@new_list; } push @new_s_lists, [@this_list, $first]; } push @s_lists, @new_s_lists; return @s_lists; } } ################################################################# # sort_gene_scaffolds_by_common_component # ################################################################# sub sort_gene_scaffolds_by_common_component { my ($gene_scaffolds, $s_id, $gs_ids) = @_; # these gene scaffolds can be oriented if the extents # of the components that they have in common are in # orientation agreement and are non-overlapping my @gs_ids = @$gs_ids; my @summaries; foreach my $gs_id (@$gs_ids) { my $extents = &get_gene_scaffold_component_extents($gene_scaffolds->{$gs_id}); if (exists($extents->{$s_id}->{ori}->{1}) and exists($extents->{$s_id}->{ori}->{-1})) { # this AGP has fragments from a single scaffold in # both orientation. We may be use a consensus # orientation, but for now, give up. printf($log_outfh "SORT: Cannot order [@gs_ids] on $s_id due to internal ori disagreement in %s\n", $gs_id); return 0; } my ($ori) = keys %{$extents->{$s_id}->{ori}}; push @summaries, { gs_id => $gs_id, start => $extents->{$s_id}->{start}, end => $extents->{$s_id}->{end}, ori => $ori, }; } for(my $i=0; $i < @summaries; $i++) { for(my $j=0; $j < $i; $j++) { if ($summaries[$i]->{start} <= $summaries[$j]->{end} and $summaries[$i]->{end} >= $summaries[$j]->{start}) { # overlap printf($log_outfh "SORT: Cannot order [@gs_ids] on $s_id due to overlap in %s and %s\n", $summaries[$i]->{gs_id}, $summaries[$j]->{gs_id}); return 0; } if ($summaries[$i]->{ori} != $summaries[$j]->{ori}) { printf($log_outfh "SORT: Cannot order [@gs_ids] on $s_id due to ori disagreement between %s and %s\n", $summaries[$i]->{gs_id}, $summaries[$j]->{gs_id}); return 0; } } } if ($summaries[0]->{ori} < 0) { @summaries = sort { $b->{start} <=> $a->{start} } @summaries; } else { @summaries = sort { $a->{start} <=> $b->{start} } @summaries; } @$gs_ids = map { $_->{gs_id} } @summaries; return 1; } ################################################################# # extend_gene_scaffold_components # ################################################################# sub extend_gene_scaffold_components { my ($chains, $gene_scaffolds, $simple_gene_scaffolds, $target_slices, $target_slice_maps) = @_; # the annotation for the simple gene scaffolds can be # placed on the appropriate part of a a complex gene-scaffold # (or directly on the scaffold), but we must ensure that # do no split a scaffold in the middle of one of these # regions my %non_break_regions; foreach my $gs_id (keys %$simple_gene_scaffolds) { my ($min_start, $max_end, $id); foreach my $cmp (@{$simple_gene_scaffolds->{$gs_id}->{components}}) { $id = $cmp->to->id if not defined $id; $min_start = $cmp->to->start if not defined $min_start or $cmp->to->start < $min_start; $max_end = $cmp->to->end if not defined $max_end or $cmp->to->end > $max_end; } push @{$non_break_regions{$id}}, { start => $min_start, end => $max_end, }; } foreach my $sid (keys %non_break_regions) { my @segs = @{$non_break_regions{$sid}}; @segs = sort { $a->{start} <=> $b->{start} } @segs; my @nov_segs; foreach my $seg (@segs) { if (not @nov_segs or $nov_segs[-1]->{end} < $seg->{start} - 1) { push @nov_segs, $seg; } elsif ($nov_segs[-1]->{end} < $seg->{end}) { $nov_segs[-1]->{end} = $seg->{end}; } } $non_break_regions{$sid} = \@nov_segs; } my (%coords_by_scaffold); # # index-by-scaffold of all the agp fragments in this group # foreach my $chain (@$chains) { foreach my $gs_id (@$chain) { my $gs = $gene_scaffolds->{$gs_id}; foreach my $pair (@{$gs->{components}}) { push @{$coords_by_scaffold{$pair->to->id}}, $pair->to; } } } # # join components together where possible # my @merged_chains; foreach my $chain (@$chains) { my @merged_coords; foreach my $gs_id (@$chain) { foreach my $pair (@{$gene_scaffolds->{$gs_id}->{components}}) { my $this_c = $pair->to; my $merged = 0; if (@merged_coords and $merged_coords[-1]->strand == $this_c->strand and $merged_coords[-1]->id eq $this_c->id) { if ($this_c->strand == 1) { if ($this_c->start > $merged_coords[-1]->end) { my $can_merge = 1; foreach my $o_c (@{$coords_by_scaffold{$this_c->id}}) { if ($o_c->start > $merged_coords[-1]->end and $o_c->end < $this_c->start) { $can_merge = 0; last; } } if ($can_merge) { $merged_coords[-1]->end($this_c->end); $merged = 1; } } } else { if ($this_c->end < $merged_coords[-1]->start) { my $can_merge = 1; foreach my $o_c (@{$coords_by_scaffold{$this_c->id}}) { if ($o_c->start > $this_c->end and $o_c->end < $merged_coords[-1]->start) { $can_merge = 0; last; } } if ($can_merge) { $merged_coords[-1]->start($this_c->start); $merged = 1; } } } } if (not $merged) { push @merged_coords, Bio::EnsEMBL::Mapper::Coordinate ->new($this_c->id, $this_c->start, $this_c->end, $this_c->strand); } } } push @merged_chains, { members => $chain, merged_coords => \@merged_coords, }; } # now extend scaffold components so that for any scaffold involved # in a gene scaffold, every bp of it is accounted for somewhere %coords_by_scaffold = (); foreach my $ch (@merged_chains) { foreach my $c (@{$ch->{merged_coords}}) { if ($c->id !~ /^$FAKE_SCAFFOLD_PREFIX/) { push @{$coords_by_scaffold{$c->id}}, $c; } } } foreach my $sid (keys %coords_by_scaffold) { my @sorted_els = sort { $a->start <=> $b->start; } @{$coords_by_scaffold{$sid}}; my $tsl = $target_slices->{$sid}; my $map = $target_slice_maps->{$sid}; my (@contig_breaks, @scaffold_gaps, @non_break_regions); if (exists $non_break_regions{$sid}) { @non_break_regions = @{$non_break_regions{$sid}}; @non_break_regions = sort { $a->{start} <=> $b->{start} } @non_break_regions; } my @bits = $map->map_coordinates($sid, 1, $tsl->length, 1, 'scaffold'); my $last_end = 0; for (my $i=0; $i < @bits; $i++) { my $bit = $bits[$i]; my $this_start = $last_end + 1; my $this_end = $this_start + $bit->length - 1; if ($bit->isa("Bio::EnsEMBL::Mapper::Gap")) { push @scaffold_gaps, $bit; } elsif ($i > 0 and $bits[$i-1]->isa("Bio::EnsEMBL::Mapper::Coordinate")) { push @contig_breaks, Bio::EnsEMBL::Mapper::Gap->new($last_end, $this_start); } $last_end = $bit->end; } $sorted_els[0]->start(1); for(my $i=1; $i<@sorted_els; $i++) { my $prev_el = $sorted_els[$i-1]; my $this_el = $sorted_els[$i]; my (@relevant_gaps, @relevant_breaks); foreach my $break (@scaffold_gaps) { if ($break->start <= $this_el->start and $break->end >= $prev_el->end) { # check that it does not overlap non-interruptable regions my $bad_break = 0; foreach my $reg (@non_break_regions) { if ($break->start >= $reg->{start} and $break->end <= $reg->{end}) { $bad_break = 1; last; } } push @relevant_gaps, $break if not $bad_break; } } foreach my $break (@contig_breaks) { if ($break->start < $this_el->start and $break->end > $prev_el->end) { my $bad_break = 0; foreach my $reg (@non_break_regions) { if ($break->start >= $reg->{start} and $break->end <= $reg->{end}) { $bad_break = 1; last; } } push @relevant_breaks, $break if not $bad_break; } } my $split_reg_start = $prev_el->end + 1; my $split_reg_end = $this_el->start - 1; if (@relevant_gaps) { my $mid = int(scalar(@relevant_gaps) / 2); $split_reg_start = $relevant_gaps[$mid]->start; $split_reg_start = $prev_el->end + 1 if $split_reg_start < $prev_el->end + 1; $split_reg_end = $relevant_gaps[$mid]->end; $split_reg_end = $this_el->start - 1 if $split_reg_end > $this_el->start - 1; printf($log_outfh "EXTEND: Split in scaffold gap (%s/%d-%d -> %d-%d)\n", $sid, $prev_el->end, $this_el->start, $split_reg_start, $split_reg_end); } elsif (@relevant_breaks) { # relevant breaks are always a precise positiom my $mid = int(scalar(@relevant_breaks) / 2); $split_reg_start = $relevant_breaks[$mid]->end; $split_reg_end = $relevant_breaks[$mid]->start; printf($log_outfh "EXTEND: Split between adjacent contigs (%s/%d-%d -> %d-%d)\n", $sid, $prev_el->end, $this_el->start, $split_reg_start, $split_reg_end); } else { printf($log_outfh "EXTEND: Split within contig region (%s/%d-%d)\n", $sid, $prev_el->end, $this_el->start, ); # make sure that we do not break in a non-break region if (@non_break_regions) { for(my $i=1; $i < @non_break_regions; $i++) { my $okay_reg_start = $non_break_regions[$i-1]->{end} + 1; my $okay_reg_end = $non_break_regions[$i]->{start} - 1; if ($okay_reg_start >= $split_reg_start and $okay_reg_end <= $split_reg_end) { $split_reg_start = $okay_reg_start; $split_reg_end = $okay_reg_end; last; } } } } my $new_prev_end = int((($split_reg_start + $split_reg_end)/2)); my $new_this_start = $new_prev_end + 1; $prev_el->end($new_prev_end); $this_el->start($new_this_start); } $sorted_els[-1]->end($tsl->length); } return \@merged_chains; } ################################################################# # fetch_slices_and_component_maps # ################################################################# sub fetch_slices_and_component_maps { my ($db, $gene_scaffolds) = @_; my (%slices, %slice_maps); foreach my $gs_id (keys %$gene_scaffolds) { foreach my $comp (@{$gene_scaffolds->{$gs_id}->{components}}) { my $sid = $comp->to->id; next if $sid =~ /^$FAKE_SCAFFOLD_PREFIX/; if (not exists($slices{$sid})) { $slices{$sid} = $db->get_SliceAdaptor->fetch_by_region('toplevel', $sid); # get components here my @seq_lev = @{$slices{$sid}->project('seqlevel')}; my $map = Bio::EnsEMBL::Mapper->new('seqlevel', 'scaffold'); foreach my $comp (@seq_lev) { $map->add_map_coordinates($comp->to_Slice->seq_region_name, $comp->to_Slice->start, $comp->to_Slice->end, $comp->to_Slice->strand, $sid, $comp->from_start, $comp->from_end); } $slice_maps{$sid} = $map; } } } return (\%slices, \%slice_maps); } ################################################################# # is_simple_gene_scaffold # ################################################################# sub is_simple_gene_scaffold { my ($gene_scaf_id, $all_gene_scaffs) = @_; # a simple gene scaffold is one in which # (a) all components come from the same scaffold # (b) all are in the same orientation # (c) the order is consistent my $gene_scaf = $all_gene_scaffs->{$gene_scaf_id}; for(my $i=1; $i < @{$gene_scaf->{components}}; $i++) { my $this = $gene_scaf->{components}->[$i]; my $prev = $gene_scaf->{components}->[$i-1]; if ($this->to->id ne $prev->to->id or $this->to->strand != $prev->to->strand or ($this->to->strand > 0 and $this->to->start <= $prev->to->end) or ($this->to->strand < 0 and $this->to->end >= $prev->to->start)) { return 0; } } return 1; } ################################################################# # get_unique_fake_scaffold_id ################################################################# sub get_unique_fake_scaffold_id { my $fake_name = $FAKE_SCAFFOLD_PREFIX . $fake_scaffold_count; $fake_scaffold_count++; return $fake_name; } ##################################### # # file index and read functions # ##################################### my (@gs_fhs, @gene_fhs, %gs_file_index, %gene_file_index); sub index_gene_scaffold_files { my @files = @_; my (%gs_index, %s_index, $last_gs_id); for(my $i=0; $i < @files; $i++) { my $file = $files[$i]; open my $fh, $file or die "Could not open '$file' for reading\n"; $gs_fhs[$i] = $fh; for(my $curpos = tell $fh; $_ = <$fh>; $curpos = tell $fh) { my ($gs_id, $s_id); if (/^\#.+AGP.+scaffold\s+(\S+)\s+/) { $gs_id = $1; } elsif ($_ !~ /^\#/) { my @l = split(/\t/, $_); if ($l[4] ne 'N') { $gs_id = $l[0]; $s_id = $l[5]; } } if (defined $gs_id) { if (not exists $gs_file_index{$gs_id}) { $gs_file_index{$gs_id} = { fh_index => $i, from => $curpos, to => $curpos, }; } else { if (defined $last_gs_id and $gs_id ne $last_gs_id) { die "Error in gene scaffold files(s) $gs_id appears in more than one block\n"; } $gs_file_index{$gs_id}->{to} = $curpos; } if (defined $s_id) { # maintain 2 other indices for the single-linkage clustering $s_index{$s_id}->{$gs_id} = 1; $gs_index{$gs_id}->{$s_id} = 1; } $last_gs_id = $gs_id; } } } return (\%gs_index, \%s_index); } sub index_gene_annotation_files { my @files = @_; my ($last_gs_id); for(my $i=0; $i < @files; $i++) { my $file = $files[$i]; open my $fh, $file or die "Could not open '$file' for reading\n"; $gene_fhs[$i] = $fh; for(my $curpos = tell $fh; $_ = <$fh>; $curpos = tell $fh) { my $gs_id; if (/^\#\s+Gene\s+report\s+for\s+(\S+)/) { $gs_id = $1; } elsif ($_ !~ /^\#/) { my @l = split(/\t/, $_); $gs_id = $l[0]; } if (defined $gs_id) { if (not exists $gene_file_index{$gs_id}) { $gene_file_index{$gs_id} = { fh_index => $i, from => $curpos, to => $curpos, }; } else { if (defined $last_gs_id and $gs_id ne $last_gs_id) { die "Error in gene annotation(s) files: $gs_id appears in more than one block\n"; } $gene_file_index{$gs_id}->{to} = $curpos; } $last_gs_id = $gs_id; } } } } sub fetch_gene_scaffold_entries { my ($gene_scaffolds, @gs_ids) = @_; foreach my $gs_id (@gs_ids) { my $index = $gs_file_index{$gs_id}; my $fh = $gs_fhs[$index->{fh_index}]; seek $fh, $index->{from}, 0; my %scaffolds_seen; for(my $curpos = tell $fh; $_ = <$fh>; $curpos = tell $fh) { last if $curpos > $index->{to}; /^\#.+AGP.+scaffold\s+(\S+)\s+.+region\=(\S+)\/(\d+)\-(\d+)/ and do { if ($1 ne $gs_id) { die "Index lookup error: Looking for $gs_id, found $1\n"; } $gene_scaffolds->{$gs_id}->{id} = $gs_id; $gene_scaffolds->{$gs_id}->{ref_name} = $2; $gene_scaffolds->{$gs_id}->{ref_start} = $3; $gene_scaffolds->{$gs_id}->{ref_end} = $4; next; }; /^(\S+)\s+(\d+)\s+(\d+)\s+\S+\s+\S+\s+(\S+)\s+(\d+)\s+(\d+)\s+(\S+)/ and do { my ($this_gs_id, $gs_start, $gs_end, $scaf_id, $scaf_start, $scaf_end, $scaf_ori) = ($1, $2, $3, $4, $5, $6, $7); $scaffolds_seen{$scaf_id} = 1; if ($this_gs_id ne $gs_id) { die "Index lookup error: Looking for $gs_id, found $this_gs_id\n"; } $scaf_ori = ($scaf_ori eq '+') ? 1 : -1; my ($level) = ($gs_id =~ /\-(\d+)$/); $gene_scaffolds->{$gs_id}->{level} = $level; ### # finally, record the AGP line itself ### my $asm_unit = Bio::EnsEMBL::Mapper::Coordinate->new($gs_id, $gs_start, $gs_end, 1); my $cmp_unit = Bio::EnsEMBL::Mapper::Coordinate->new($scaf_id, $scaf_start, $scaf_end, $scaf_ori); my $pair = Bio::EnsEMBL::Mapper::Pair->new($asm_unit, $cmp_unit); push @{$gene_scaffolds->{$gs_id}->{components}}, $pair; } } } } sub fetch_gene_annotation_entries { my ($gene_scaffolds, @gs_ids) = @_; foreach my $gs_id (@gs_ids) { my $index = $gene_file_index{$gs_id}; my $fh = $gene_fhs[$index->{fh_index}]; seek $fh, $index->{from}, 0; for(my $curpos = tell $fh; $_ = <$fh>; $curpos = tell $fh) { last if $curpos > $index->{to}; if (/^\#\#\-ATTRIBUTE/) { push @{$gene_scaffolds->{$gs_id}->{annotation}}, $_; } elsif ($_ !~ /^\#/) { my @l = split(/\t/, $_); push @{$gene_scaffolds->{$gs_id}->{annotation}}, \@l; } } } }
kiwiroy/ensembl-analysis
scripts/wga2genes/merge_and_extend_gene_scaffolds.pl
Perl
apache-2.0
43,626
# # Copyright 2015 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::hp::p2000::xmlapi::custom; use strict; use warnings; use centreon::plugins::http; use XML::XPath; use Digest::MD5 qw(md5_hex); sub new { my ($class, %options) = @_; my $self = {}; bless $self, $class; # $options{options} = options object # $options{output} = output object # $options{exit_value} = integer # $options{noptions} = integer if (!defined($options{output})) { print "Class Custom: Need to specify 'output' argument.\n"; exit 3; } if (!defined($options{options})) { $options{output}->add_option_msg(short_msg => "Class Custom: Need to specify 'options' argument."); $options{output}->option_exit(); } if (!defined($options{noptions})) { $options{options}->add_options(arguments => { "hostname:s@" => { name => 'hostname', }, "port:s@" => { name => 'port', }, "proto:s@" => { name => 'proto', }, "urlpath:s@" => { name => 'url_path', }, "proxyurl:s@" => { name => 'proxyurl', }, "username:s@" => { name => 'username', }, "password:s@" => { name => 'password', }, "timeout:s@" => { name => 'timeout', }, }); } $options{options}->add_help(package => __PACKAGE__, sections => 'P2000 OPTIONS', once => 1); $self->{output} = $options{output}; $self->{mode} = $options{mode}; $self->{session_id} = ''; $self->{logon} = 0; return $self; } # Method to manage multiples sub set_options { my ($self, %options) = @_; # options{options_result} $self->{option_results} = $options{option_results}; } # Method to manage multiples sub set_defaults { my ($self, %options) = @_; # options{default} # Manage default value foreach (keys %{$options{default}}) { if ($_ eq $self->{mode}) { for (my $i = 0; $i < scalar(@{$options{default}->{$_}}); $i++) { foreach my $opt (keys %{$options{default}->{$_}[$i]}) { if (!defined($self->{option_results}->{$opt}[$i])) { $self->{option_results}->{$opt}[$i] = $options{default}->{$_}[$i]->{$opt}; } } } } } } sub check_options { my ($self, %options) = @_; # return 1 = ok still hostname # return 0 = no hostname left $self->{hostname} = (defined($self->{option_results}->{hostname})) ? shift(@{$self->{option_results}->{hostname}}) : undef; $self->{username} = (defined($self->{option_results}->{username})) ? shift(@{$self->{option_results}->{username}}) : undef; $self->{password} = (defined($self->{option_results}->{password})) ? shift(@{$self->{option_results}->{password}}) : undef; $self->{timeout} = (defined($self->{option_results}->{timeout})) ? shift(@{$self->{option_results}->{timeout}}) : 45; $self->{port} = (defined($self->{option_results}->{port})) ? shift(@{$self->{option_results}->{port}}) : undef; $self->{proto} = (defined($self->{option_results}->{proto})) ? shift(@{$self->{option_results}->{proto}}) : 'http'; $self->{url_path} = (defined($self->{option_results}->{url_path})) ? shift(@{$self->{option_results}->{url_path}}) : '/api/'; $self->{proxyurl} = (defined($self->{option_results}->{proxyurl})) ? shift(@{$self->{option_results}->{proxyurl}}) : undef; if (!defined($self->{hostname})) { $self->{output}->add_option_msg(short_msg => "Need to specify hostname option."); $self->{output}->option_exit(); } if (!defined($self->{username}) || !defined($self->{password})) { $self->{output}->add_option_msg(short_msg => 'Need to specify username or/and password option.'); $self->{output}->option_exit(); } if (!defined($self->{hostname}) || scalar(@{$self->{option_results}->{hostname}}) == 0) { return 0; } return 1; } sub build_options_for_httplib { my ($self, %options) = @_; $self->{option_results}->{hostname} = $self->{hostname}; $self->{option_results}->{timeout} = $self->{timeout}; $self->{option_results}->{port} = $self->{port}; $self->{option_results}->{proto} = $self->{proto}; $self->{option_results}->{url_path} = $self->{url_path}; $self->{option_results}->{proxyurl} = $self->{proxyurl}; } sub check_login { my ($self, %options) = @_; my ($xpath, $nodeset); eval { $xpath = XML::XPath->new(xml => $options{content}); $nodeset = $xpath->find("//OBJECT[\@basetype='status']//PROPERTY[\@name='return-code']"); }; if ($@) { $self->{output}->add_option_msg(short_msg => "Cannot parse login response: $@"); $self->{output}->option_exit(); } if (scalar($nodeset->get_nodelist) == 0) { $self->{output}->output_add(severity => 'UNKNOWN', short_msg => 'Cannot find login response.'); $self->{output}->display(); $self->{output}->exit(); } foreach my $node ($nodeset->get_nodelist()) { if ($node->string_value != 1) { $self->{output}->output_add(severity => 'UNKNOWN', short_msg => 'Login authentification failed (return-code: ' . $node->string_value . ').'); $self->{output}->display(); $self->{output}->exit(); } } $nodeset = $xpath->find("//OBJECT[\@basetype='status']//PROPERTY[\@name='response']"); my @nodes = $nodeset->get_nodelist(); my $node = shift(@nodes); $self->{session_id} = $node->string_value; $self->{logon} = 1; } sub DESTROY { my $self = shift; if ($self->{logon} == 1) { $self->{http}->request(url_path => $self->{url_path} . 'exit', header => ['dataType: api', 'sessionKey: ' . $self->{session_id}]); } } sub get_infos { my ($self, %options) = @_; my ($xpath, $nodeset); my $cmd = $options{cmd}; $cmd =~ s/ /\//g; my $response =$self->{http}->request(url_path => $self->{url_path} . $cmd, header => ['dataType: api', 'sessionKey: '. $self->{session_id}]); eval { $xpath = XML::XPath->new(xml => $response); $nodeset = $xpath->find("//OBJECT[\@basetype='" . $options{base_type} . "']"); }; if ($@) { $self->{output}->add_option_msg(short_msg => "Cannot parse 'cmd' response: $@"); $self->{output}->option_exit(); } my $results = {}; foreach my $node ($nodeset->get_nodelist()) { my $properties = {}; foreach my $prop_node ($node->getChildNodes()) { my $prop_name = $prop_node->getAttribute('name'); if (defined($prop_name) && ($prop_name eq $options{key} || $prop_name =~ /$options{properties_name}/)) { $properties->{$prop_name} = $prop_node->string_value; } } if (defined($properties->{$options{key}})) { $results->{$properties->{$options{key}}} = $properties; } } return $results; } ############## # Specific methods ############## sub login { my ($self, %options) = @_; $self->build_options_for_httplib(); $self->{http} = centreon::plugins::http->new(output => $self->{output}); $self->{http}->set_options(%{$self->{option_results}}); # Login First my $md5_hash = md5_hex($self->{username} . '_' . $self->{password}); my $response = $self->{http}->request(url_path => $self->{url_path} . 'login/' . $md5_hash); $self->check_login(content => $response); } 1; __END__ =head1 NAME MSA p2000 =head1 SYNOPSIS my p2000 xml api manage =head1 P2000 OPTIONS =over 8 =item B<--hostname> HP p2000 Hostname. =item B<--port> Port used =item B<--proxyurl> Proxy URL if any =item B<--proto> Specify https if needed =item B<--urlpath> Set path to xml api (Default: '/api/') =item B<--username> Username to connect. =item B<--password> Password to connect. =item B<--timeout> Set HTTP timeout =back =head1 DESCRIPTION B<custom>. =cut
s-duret/centreon-plugins
storage/hp/p2000/xmlapi/custom.pm
Perl
apache-2.0
9,116
=head1 LICENSE Copyright [1999-2014] Wellcome Trust Sanger Institute and the 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::Production::Projection::ProjectionEngine =head1 DESCRIPTION This is a re-implementation of the code currently held in Ensembl's core API checkout which can project DBEntries from one species to another by using the Homologies projected from the Compara Genomics GeneTree pipeline. Normally this is used to project GO terms from a well annotated species to one which is not. Ensembl's original implementation involved a monolithic script with no scope for customisation. This implementation attempts to be as pluggable as possible by leveraging L<Data::Predicate>s (a way of encapsulating logic to allow a user to specify their own filters). This means the algorithm for projection becomes =over 8 =item Get all homologies projected between two species (one given at construction) the other when we run C<project> =item Filter them for allowed linkage using C<homology_predicate()> e.g. filter on allowed mappings or percentage identitiy limits =item Loop through these homologies =item For each member of the homology get the DBEntry objects from the core database (delegates to Bio::EnsEMBL::Compara::Production::Projection::FakeXrefHolder) =item For each source DBEntry filter out using C<db_entry_predicate()> ensuring we want to work with this DBEntry type =item If we still have a DBEntry then make sure the target does not already have the DBEntry linked to it =item If still okay then build a C<Bio::EnsEMBL::Compara::Production::Projection::Projection> object based on this =item Return an ArrayRef of these projection objects =back The main way to cut into this procedure is to give your own predicates during construction or to extend this module & reimplement the builder methods. =head1 CAVEATS =over 8 =item This version is designed for a basic plant transfer algorithm =item We must consult both GO and PO External DBs because plant databases have mixed usage of these types =item We only project GOs =back =head1 AUTHOR Andy Yates (ayatesatebiacuk) =head1 CONTACT This modules is part of the EnsEMBL project (http://www.ensembl.org) Questions can be posted to the dev mailing list: http://lists.ensembl.org/mailman/listinfo/dev =cut package Bio::EnsEMBL::Compara::Production::Projection::ProjectionEngine; use strict; use warnings; use Bio::EnsEMBL::Utils::Argument qw(rearrange); use Bio::EnsEMBL::Utils::Scalar qw(assert_ref); use Data::Predicate::Predicates qw(:all); use Bio::EnsEMBL::Compara::Production::Projection::Projection; =head2 new() Arg[-dbentry_predicate] : Predicate used to filter out DBEntry instances Arg[-homology_predicate] : Predicate used to filter out Homology instances Arg[-log] : Logger instance. Can be a Log::Log4perl::Logger instance or a class which implements the methods Arg[-dba] : required; Compara adaptor to get homologies from Arg[-method_link_type] : Method link to get homologies from Arg[-genome_db] : required; GenomeDB to use as the source of the homologies Description : New method used for a new instance of the given object. Required fields are indicated accordingly. Fields are specified using the Arguments syntax (case insensitive). =cut sub new { my ( $class, @args ) = @_; my $self = bless( {}, ref($class) || $class ); my ( $dbentry_predicate, $homology_predicate, $log, $dba, $method_link_type, $genome_db ) = rearrange([ qw( dbentry_predicate homology_predicate log dba method_link_type genome_db ) ], @args); assert_ref( $dbentry_predicate, 'Data::Predicate' ) if defined $dbentry_predicate; $self->{dbentry_predicate} = $dbentry_predicate if defined $dbentry_predicate; assert_ref( $homology_predicate, 'Data::Predicate' ) if defined $homology_predicate; $self->{homology_predicate} = $homology_predicate if defined $homology_predicate; $log = $self->_log_builder() if !defined $log; confess('The attribute log must be specified during construction or provide a builder subroutine') if !defined $log; $self->{log} = $log if defined $log; assert_ref( $dba, 'Bio::EnsEMBL::Compara::DBSQL::DBAdaptor' ); confess('The attribute dba must be specified during construction or provide a builder subroutine') if !defined $dba; $self->{dba} = $dba if defined $dba; $method_link_type = $self->_method_link_type_builder() if !defined $method_link_type; $self->{method_link_type} = $method_link_type if defined $method_link_type; assert_ref( $genome_db, 'Bio::EnsEMBL::Compara::GenomeDB' ); confess('The attribute genome_db must be specified during construction or provide a builder subroutine' ) if !defined $genome_db; $self->{genome_db} = $genome_db if defined $genome_db; return $self; } =head2 dbentry_predicate() Description : Getter. Predicate used to filter out DBEntry instances Can be customised by overriding C<_dbentry_predicate_builder>(). =cut sub dbentry_predicate { my ($self) = @_; if ( !exists $self->{dbentry_predicate} ) { $self->{dbentry_predicate} = $self->_dbentry_predicate_builder(); } return $self->{dbentry_predicate}; } =head2 homology_predicate() Description : Getter. Predicate used to filter out Homology instances Can be customised by overriding C<_homology_predicate_builder>(). =cut sub homology_predicate { my ($self) = @_; if ( !exists $self->{homology_predicate} ) { $self->{homology_predicate} = $self->_homology_predicate_builder(); } return $self->{homology_predicate}; } =head2 log() Description : Getter. Logger instance =cut sub log { my ($self) = @_; return $self->{log}; } =head2 dba() Description : Getter. Compara adaptor to get homologies from =cut sub dba { my ($self) = @_; return $self->{dba}; } =head2 method_link_type() Description : Getter. Method link to get homologies from Can be customised by overriding C<_method_link_type_builder>(). Defaults to ENSEMBL_ORTHOLOGUES. =cut sub method_link_type { my ($self) = @_; return $self->{method_link_type}; } =head2 genome_db() Description : Getter. GenomeDB to use as the source of the homologies =cut sub genome_db { my ($self) = @_; return $self->{genome_db}; } ######BUILDERS sub _method_link_type_builder { my ($self) = @_; return 'ENSEMBL_ORTHOLOGUES'; } my $imported_log4p = 0; sub _log_builder { my ($self) = @_; if(! $imported_log4p) { eval "require Log::Log4perl"; if($@) { throw('Cannot build a logger because Log::Log4perl is not available. Detected error: '.$@); } $imported_log4p = 1; } return Log::Log4perl->get_logger(__PACKAGE__); } sub _homology_predicate_builder { my ($self) = @_; throw('Override to provide a default Homology predicate'); } sub _dbentry_predicate_builder { my ($self) = @_; throw('Override to provide a default DBEntry predicate'); } ######LOGIC =head2 project() Arg[0] : GenomeDB object which is used as the projection target Description : Workhorse subroutine which loops through homologies and filters through those and DBEntry objects using L<Data::Predicate> objects. See class description for more information on the filtering process. Returntype : Bio::EnsEMBL::Compara::Production::Projection::Projection Exceptions : If we cannot contact the target databases =cut sub project { my ($self, $target_genome_db) = @_; my $log = $self->log(); $log->info('Processing '.$self->genome_db()->name().' Vs. '.$target_genome_db->name()); my $mlss = $self->_get_mlss($target_genome_db); my $homologies = $self->_homologies($mlss); my @projections; $log->info('Looping over '.scalar(@{$homologies}).' homologies'); foreach my $homology (@{$homologies}) { my ($query_member, $target_member) = $self->_decode_homology($homology); if($self->log()->is_trace()) { my $q_id = $query_member->stable_id(); my $t_id = $target_member->stable_id(); $log->trace(sprintf('Projecting from %s to %s', $q_id, $t_id)); } my $query_dbentry_holder = $self->dbentry_source_object($query_member); my $target_dbentry_holder = $self->dbentry_source_object($target_member); my $db_entries = $query_dbentry_holder->get_all_DBEntries(); foreach my $dbentry (@{$db_entries}) { if($log->is_trace()) { $log->trace(sprintf('Working with %s from external db %s', $dbentry->primary_id(), $dbentry->dbname())); } my $filter_dbentry = $self->_filter_dbentry($dbentry, $target_dbentry_holder); if($filter_dbentry) { if($log->is_trace()) { $log->trace('Passes DBEntry filter'); } if($self->_transfer_dbentry_by_targets($dbentry, $target_dbentry_holder->get_all_DBEntries(), $target_member->stable_id())) { $log->trace('DBEntry will be transferred'); my $projection = $self->build_projection($query_member, $target_member, $dbentry, $homology); push(@projections, $projection) if defined $projection; } else { if($log->is_trace()) { $log->trace('Failed target entry transfer; check target for existing annotation or better quality annotation'); } } } else { if($log->is_trace()) { $log->trace('Fails DBEntry filter'); } } } } $log->info('Finished homology and have found '.scalar(@projections).' projection(s)'); return \@projections; } =head2 build_projection() Arg[1] : Member; source member of projection Arg[2] : Member; target member of projection Arg[3] : DBEntry projected Arg[4] : The homology used for projection Description : Provides an abstraction to building a projection from a set of elements. Returntype : Projection object. Can be null & the current projection code will ignore it =cut sub build_projection { my ($self, $query_member, $target_member, $dbentry, $homology) = @_; return Bio::EnsEMBL::Compara::Production::Projection::Projection->new( -ENTRY => $dbentry, -FROM => $query_member->get_canonical_SeqMember(), -TO => $target_member->get_canonical_SeqMember(), -FROM_IDENTITY => $query_member->perc_id(), -TO_IDENTITY => $target_member->perc_id(), -TYPE => $homology->description() ); } sub _get_mlss { my ($self, $target_genome_db) = @_; my $mlssa = $self->dba()->get_MethodLinkSpeciesSetAdaptor(); my $mlss = $mlssa->fetch_by_method_link_type_GenomeDBs( $self->method->type(), [$self->genome_db(), $target_genome_db]); return $mlss; } sub _homologies { my ($self, $mlss) = @_; $self->log()->debug('Retriving homologies'); my $homologies = $self->_get_homologies($mlss); $self->log()->debug('Filtering homologies'); my $predicate = $self->homology_predicate(); my $log = $self->log(); my $trace = $log->is_trace(); my @filtered; foreach my $h (@{$homologies}) { $log->trace(sprintf('Filtering homology %d', $h->dbID())) if $trace; if($predicate->apply($h)) { $log->trace('Accepted homology') if $trace; push(@filtered, $h); } else { $log->trace('Rejected homology') if $trace; } } $self->log()->debug('Finished filtering'); return \@filtered; } sub _filter_dbentry { my ($self, $dbentry, $target_dbentry_holder) = @_; return $self->dbentry_predicate()->apply($dbentry); } sub _transfer_dbentry_by_targets { my ($self, $source, $targets) = @_; my $source_ref = ref($source); foreach my $target_xref (@{$targets}) { next unless check_ref($target_xref, $source_ref); #Reject if it was the same if ( $source->dbname() eq $target_xref->dbname() && $source->primary_id() eq $target_xref->primary_id()) { return 0; } } return 1; } sub _decode_homology { my ($self, $homology) = @_; my $query; my $target; foreach my $member (@{$homology->get_all_Members}) { if($member->genome_db()->dbID() == $self->genome_db()->dbID()) { $query = $member; } else { $target = $member; } } return ($query, $target); } sub _get_homologies { my ($self, $mlss) = @_; my $ha = $self->dba()->get_HomologyAdaptor(); $self->log()->debug('Fetching homologues'); my $homologies = $ha->fetch_all_by_MethodLinkSpeciesSet($mlss); return $homologies; } =head2 dbentry_source_object() Arg[1] : Member to get the DBEntry objects for =cut sub dbentry_source_object { my ($self, $member) = @_; throw('Unsupported operation called; override in the implementing class'); } 1;
dbolser-ebi/ensembl-compara
modules/Bio/EnsEMBL/Compara/Production/Projection/ProjectionEngine.pm
Perl
apache-2.0
13,307
package Google::Ads::AdWords::v201402::ConstantDataService::getCarrierCriterion; use strict; use warnings; { # BLOCK to scope variables sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201402' } __PACKAGE__->__set_name('getCarrierCriterion'); __PACKAGE__->__set_nillable(); __PACKAGE__->__set_minOccurs(); __PACKAGE__->__set_maxOccurs(); __PACKAGE__->__set_ref(); use base qw( SOAP::WSDL::XSD::Typelib::Element Google::Ads::SOAP::Typelib::ComplexType ); 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 __PACKAGE__->_factory( [ qw( ) ], { }, { }, { } ); } # end BLOCK } # end of BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201402::ConstantDataService::getCarrierCriterion =head1 DESCRIPTION Perl data type class for the XML Schema defined element getCarrierCriterion from the namespace https://adwords.google.com/api/adwords/cm/v201402. Returns a list of all carrier criteria. @return A list of carriers. @throws ApiException when there is at least one error with the request. =head1 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =back =head1 METHODS =head2 new my $element = Google::Ads::AdWords::v201402::ConstantDataService::getCarrierCriterion->new($data); 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/ConstantDataService/getCarrierCriterion.pm
Perl
apache-2.0
1,638
package Moose::Exception::ConflictDetectedInCheckRoleExclusions; our $VERSION = '2.1404'; use Moose; extends 'Moose::Exception'; with 'Moose::Exception::Role::Role'; has 'excluded_role_name' => ( is => 'ro', isa => 'Str', required => 1 ); sub _build_message { my $self = shift; my $role_name = $self->role_name; my $excluded_role_name = $self->excluded_role_name; return "Conflict detected: $role_name excludes role '$excluded_role_name'"; } 1;
ray66rus/vndrv
local/lib/perl5/x86_64-linux-thread-multi/Moose/Exception/ConflictDetectedInCheckRoleExclusions.pm
Perl
apache-2.0
511
package Paws::EC2::HistoryRecord; use Moose; has EventInformation => (is => 'ro', isa => 'Paws::EC2::EventInformation', request_name => 'eventInformation', traits => ['NameInRequest'], required => 1); has EventType => (is => 'ro', isa => 'Str', request_name => 'eventType', traits => ['NameInRequest'], required => 1); has Timestamp => (is => 'ro', isa => 'Str', request_name => 'timestamp', traits => ['NameInRequest'], required => 1); 1; ### main pod documentation begin ### =head1 NAME Paws::EC2::HistoryRecord =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::EC2::HistoryRecord object: $service_obj->Method(Att1 => { EventInformation => $value, ..., Timestamp => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::EC2::HistoryRecord object: $result = $service_obj->Method(...); $result->Att1->EventInformation =head1 DESCRIPTION This class has no description =head1 ATTRIBUTES =head2 B<REQUIRED> EventInformation => L<Paws::EC2::EventInformation> Information about the event. =head2 B<REQUIRED> EventType => Str The event type. =over =item * C<error> - Indicates an error with the Spot fleet request. =item * C<fleetRequestChange> - Indicates a change in the status or configuration of the Spot fleet request. =item * C<instanceChange> - Indicates that an instance was launched or terminated. =back =head2 B<REQUIRED> Timestamp => Str The date and time of the event, in UTC format (for example, I<YYYY>-I<MM>-I<DD>TI<HH>:I<MM>:I<SS>Z). =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::EC2> =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/EC2/HistoryRecord.pm
Perl
apache-2.0
2,129
# 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::V10::Enums::FeedAttributeTypeEnum; use strict; use warnings; use Const::Exporter enums => [ UNSPECIFIED => "UNSPECIFIED", UNKNOWN => "UNKNOWN", INT64 => "INT64", DOUBLE => "DOUBLE", STRING => "STRING", BOOLEAN => "BOOLEAN", URL => "URL", DATE_TIME => "DATE_TIME", INT64_LIST => "INT64_LIST", DOUBLE_LIST => "DOUBLE_LIST", STRING_LIST => "STRING_LIST", BOOLEAN_LIST => "BOOLEAN_LIST", URL_LIST => "URL_LIST", DATE_TIME_LIST => "DATE_TIME_LIST", PRICE => "PRICE" ]; 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V10/Enums/FeedAttributeTypeEnum.pm
Perl
apache-2.0
1,193
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2020] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =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>. =head1 NAME XrefParser::VGNCParser =head1 DESCRIPTION A parser class to parse the VGNC source. VGNC is the official naming source for some vertebrates species -data_uri = ftp://ftp.ebi.ac.uk/pub/databases/genenames/vgnc/tsv/vgnc_gene_set_All.txt.gz -file_format = TSV -columns = [ taxon_id vgnc_id symbol name locus_group locus_type status location location_sortable: alias_symbol alias_name prev_symbol prev_name gene_family gene_family_id date_approved_reserved date_symbol_changed date_name_changed date_modified entrez_id ensembl_gene_id uniprot_ids ] Only columns listed in @required_columns are mandatory. =head1 SYNOPSIS my $parser = XrefParser::VGNCParser->new($db->dbh); my $parser->run( { source_id => 144, species_id => 9598, files => ['VGNC/vgnc_gene_set_All.txt.gz'], } ); =cut package XrefParser::VGNCParser; use strict; use warnings; use Carp; use Text::CSV; use parent qw( XrefParser::HGNCParser ); =head2 run Description: Runs the VGNCParser Return type: none Exceptions : throws on all processing errors Caller : ParseSource in the xref pipeline =cut sub run { my ($self, $ref_arg) = @_; my $source_id = $ref_arg->{source_id}; my $species_id = $ref_arg->{species_id}; my $files = $ref_arg->{files}; my $verbose = $ref_arg->{verbose} // 0; my $dbi = $ref_arg->{dbi} // $self->dbi; if ( (!defined $source_id) || (!defined $species_id) || (!defined $files) ) { confess "Need to pass source_id, species_id and files as pairs"; } my $file = @{$files}[0]; my $count = 0; my $file_io = $self->get_filehandle($file); if ( !defined $file_io ) { confess "Can't open VGNC file '$file'\n"; } my $source_name = $self->get_source_name_for_source_id($source_id, $dbi); # Create a hash of all valid taxon_ids for this species my %species2tax = $self->species_id2taxonomy($dbi); my @tax_ids = @{$species2tax{$species_id}}; my %taxonomy2species_id = map{ $_=>$species_id } @tax_ids; my $input_file = Text::CSV->new({ sep_char => "\t", empty_is_undef => 1 }) or confess "Cannot use file '$file': ".Text::CSV->error_diag(); # header must contain these columns my @required_columns = qw( taxon_id ensembl_gene_id vgnc_id symbol name alias_symbol prev_symbol ); # get header columns my @columns = @{ $input_file->getline( $file_io ) }; # die if some required_column is not in columns foreach my $colname (@required_columns) { if ( !grep { /$colname/xms } @columns ) { confess "Can't find required column '$colname' in VGNC file '$file'\n"; } } $input_file->column_names( @columns ); while ( my $data = $input_file->getline_hr( $file_io ) ) { # skip data for other species next if ( !exists $taxonomy2species_id{$data->{'taxon_id'}} ); if ( $data->{'ensembl_gene_id'} ) { # Ensembl direct xref $self->add_to_direct_xrefs({ stable_id => $data->{'ensembl_gene_id'}, type => 'gene', acc => $data->{'vgnc_id'}, label => $data->{'symbol'}, desc => $data->{'name'}, dbi => $dbi, source_id => $source_id, species_id => $species_id }); $self->add_synonyms_for_hgnc({ source_id => $source_id, name => $data->{'vgnc_id'}, species_id => $species_id, dbi => $dbi, dead => $data->{'alias_symbol'}, alias => $data->{'prev_symbol'} }); $count++; } } $input_file->eof or confess "Error parsing file '$file': " . $input_file->error_diag(); $file_io->close(); if($verbose){ print "Loaded a total of $count VGNC xrefs\n"; } return 0; # successful } 1;
james-monkeyshines/ensembl
misc-scripts/xref_mapping/XrefParser/VGNCParser.pm
Perl
apache-2.0
4,838
package CSS::Prepare; use Modern::Perl; use CSS::Prepare::CSSGrammar; use CSS::Prepare::Property::Background; use CSS::Prepare::Property::Border; use CSS::Prepare::Property::BorderRadius; use CSS::Prepare::Property::Color; use CSS::Prepare::Property::Effects; use CSS::Prepare::Property::Font; use CSS::Prepare::Property::Formatting; use CSS::Prepare::Property::Generated; use CSS::Prepare::Property::Hacks; use CSS::Prepare::Property::Margin; use CSS::Prepare::Property::Padding; use CSS::Prepare::Property::Tables; use CSS::Prepare::Property::Text; use CSS::Prepare::Property::UI; use CSS::Prepare::Property::Values; use CSS::Prepare::Property::Vendor; use Digest::SHA1 qw( sha1_hex ); use FileHandle; use File::Basename; use File::Path; use List::Util qw( first ); use Storable qw( dclone ); use version; our $VERSION = qv( 0.9.2.2 ); use constant MAX_REDIRECT => 3; use constant RE_IS_URL => qr{^ http s? : // }x; use constant RE_MATCH_HOSTNAME => qr{^ ( http s? : // [^/]+ ) /? .* $}x; use constant RE_MATCH_DIRECTORY => qr{^ (.*?) (?: / [^/]* )? $}x; use constant NOT_VENDOR_PREFIX => qw( background border empty font letter list margin padding page table text unicode white z ); my @MODULES = qw( Background Border BorderRadius Color Effects Font Formatting Hacks Generated Margin Padding Tables Text UI Vendor ); sub new { my $class = shift; my %args = @_; my $self = { hacks => 1, extended => 0, suboptimal_threshold => 10, http_timeout => 30, pretty => 0, assets_output => undef, assets_base => undef, location => undef, status => \&status_to_stderr, %args }; bless $self, $class; my %http_providers = ( lite => 'HTTP::Lite', lwp => 'LWP::UserAgent', ); # sort to prefer HTTP::Lite over LWP::UserAgent HTTP: foreach my $provider ( sort keys %http_providers ) { my $module = $http_providers{ $provider }; eval "require $module"; unless ($@) { $self->{'http_provider'} = $provider; last HTTP; } } # check for ability to use plugins if ( $self->support_extended_syntax() ) { eval "use Module::Pluggable require => 1;"; unless ($@) { foreach my $plugin ( $self->plugins() ) { $self->{'has_plugins'} = 1; } } } return $self; } sub get_hacks { my $self = shift; return $self->{'hacks'}; } sub set_hacks { my $self = shift; my $hacks = shift // 0; $self->{'hacks'} = $hacks; } sub support_hacks { my $self = shift; return $self->{'hacks'}; } sub get_extended { my $self = shift; return $self->{'extended'}; } sub set_extended { my $self = shift; my $extended = shift // 0; $self->{'extended'} = $extended; } sub support_extended_syntax { my $self = shift; return $self->{'extended'}; } sub get_suboptimal_threshold { my $self = shift; return $self->{'suboptimal_threshold'}; } sub set_suboptimal_threshold { my $self = shift; my $suboptimal_threshold = shift // 0; $self->{'suboptimal_threshold'} = $suboptimal_threshold; } sub suboptimal_threshold { my $self = shift; return $self->{'suboptimal_threshold'}; } sub get_pretty { my $self = shift; return $self->{'pretty'}; } sub set_pretty { my $self = shift; my $value = shift; $self->{'pretty'} = $value; } sub pretty_output { my $self = shift; return $self->{'pretty'}; } sub assets_output { my $self = shift; return defined $self->{'assets_output'}; } sub location { my $self = shift; return $self->{'location'}; } sub set_base_directory { my $self = shift; my $base = shift; # ensure trailing slash $base =~ s{/?$}{/}; $self->{'base_directory'} = $base; } sub get_base_directory { my $self = shift; return $self->{'base_directory'}; } sub set_base_url { my $self = shift; $self->{'base_url'} = shift; } sub get_base_url { my $self = shift; return $self->{'base_url'}; } sub get_http_timeout { my $self = shift; return $self->{'http_timeout'}; } sub set_http_timeout { my $self = shift; $self->{'http_timeout'} = shift; } sub has_http { my $self = shift; return defined $self->{'http_provider'}; } sub get_http_provider { my $self = shift; return $self->{'http_provider'}; } sub has_plugins { my $self = shift; return $self->{'has_plugins'}; } my $elements_first = sub { my $a_element = ( $a =~ m{^[a-z]}i ); my $b_element = ( $b =~ m{^[a-z]}i ); my $element_count = $a_element + $b_element; return ( $a_element ? -1 : 1 ) if 1 == $element_count; return $a cmp $b; }; sub parse_file { my $self = shift; my $file = shift; my $location = shift; my $string = $self->read_file( $file ); return $self->parse( $string, $file, $location ) if defined $string; return; } sub parse_file_structure { my $self = shift; my $file = shift; my $base = $self->get_base_directory(); return undef unless defined $base && -d $base; my $stylesheet = basename( $file ); my $directory = dirname( $file ); my @blocks; my $path; foreach my $section ( split m{/}, $directory ) { $path .= "${section}/"; my $target = "${base}${path}${stylesheet}"; my @file_blocks = $self->parse_file( $target ); push @blocks, @file_blocks if @file_blocks; # non-existent file is not an error } return @blocks; } sub parse_url { my $self = shift; my $url = shift; my $location = shift; my $string = $self->read_url( $url ); return $self->parse( $string, $url, $location ) if defined $string; return; } sub parse_url_structure { my $self = shift; my $file = shift; my $base = $self->get_base_url(); return undef unless defined $base && $base =~ m{https?://}; my $stylesheet = basename( $file ); my $directory = dirname( $file ); my @blocks; my $path; foreach my $section ( split m{/}, $directory ) { $path .= "${section}/"; my $target = "${base}${path}${stylesheet}"; my @file_blocks = $self->parse_url( $target ); push @blocks, @file_blocks if @file_blocks; # non-existent url is not an error } return @blocks; } sub parse_string { my $self = shift; my $string = shift; my $location = shift; return $self->parse( $string ) } sub parse_stylesheet { my $self = shift; my $stylesheet = shift; my $location = shift; my $target = $self->canonicalise_location( $stylesheet, $location ); return $self->parse_url( $target, $location ) if $target =~ RE_IS_URL; return $self->parse_file( $target, $location ); } sub canonicalise_location { my $self = shift; my $file = shift; my $location = shift; my $target; # don't interfere with an absolute URL if ( $file =~ RE_IS_URL ) { $target = $file; } else { if ( $file =~ m{^/} ) { my $base = $self->get_base_directory(); if ( defined $base ) { $target = "$base/$file"; } else { $target = $file; } if ( defined $location ) { if ( $location =~ RE_MATCH_HOSTNAME ) { $target = "${1}${file}"; } } } else { if ( defined $location ) { $location =~ RE_MATCH_DIRECTORY; $target = "${1}/${file}"; } else { my $base = $self->get_base_directory() || ''; $target = "${base}${file}"; } } } return $target; } sub output_as_string { my $self = shift; my @data = @_; my $output = ''; foreach my $block ( @data ) { my $type = $block->{'type'} // ''; if ( 'at-media' eq $type || 'import' eq $type ) { my $query = $block->{'query'}; my $string = $self->output_as_string( @{$block->{'blocks'}} ); if ( defined $query && $query ) { $string =~ s{^}{ }gm; $output .= "\@media ${query}{\n${string}}\n"; } else { $output .= $string; } } elsif ( 'verbatim' eq $type ) { $output .= $block->{'string'}; } elsif ( 'boundary' eq $type ) { # just skip the block } else { $output .= $self->output_block_as_string( $block ); } } return $output; } sub output_block_as_string { my $self = shift; my $block = shift; my $shorthands_first_hacks_last = sub { # sort hacks after normal properties my $a_hack = ( $a =~ m{^ \s* [_\*] }x ); my $b_hack = ( $b =~ m{^ \s* [_\*] }x ); my $hack_count = $a_hack + $b_hack; return $a_hack ? 1 : -1 if 1 == $hack_count; # sort properties with vendor prefixes before # their matching properties $a =~ m{^ \s* ( [-] \w+ - )? ( .* ) $}sx; my $a_vendor = defined $1 && ! defined first { $_ eq $1 } NOT_VENDOR_PREFIX; $b =~ m{^ \s* ( [-] \w+ - )? ( .* ) $}sx; my $b_vendor = defined $1 && ! defined first { $_ eq $1 } NOT_VENDOR_PREFIX; my $vendors = ( $a_vendor ) + ( $b_vendor ); return $a_vendor ? -1 : 1 if 1 == $vendors; # sort more-specific properties after less-specific properties $a =~ m{^ \s* ( [^:]+ ) : }x; my $a_declaration = $1; $b =~ m{^ \s* ( [^:]+ ) : }x; my $b_declaration = $1; my $a_specifics = ( $a_declaration =~ tr{-}{-} ); my $b_specifics = ( $b_declaration =~ tr{-}{-} ); return $a_specifics <=> $b_specifics if $a_specifics != $b_specifics; # just sort alphabetically return $a cmp $b; }; my %properties = $self->output_properties( $block->{'block'} ); return '' unless %properties; # unique selectors only my %seen; my @selectors = grep { !$seen{$_}++ } @{$block->{'selectors'}}; my $output; my $separator = $self->pretty_output ? ",\n" : ','; my $selector = join $separator, sort $elements_first @selectors; my $properties = join '', sort $shorthands_first_hacks_last keys %properties; return $self->pretty_output ? "${selector} \{\n${properties}\}\n" : "${selector}\{${properties}\}\n"; } sub output_properties { my $self = shift; my $block = shift; # separate out the important rules from the normal, so that they are # not accidentally shorthanded, despite being different values my %normal; my %important; foreach my $key ( keys %{$block} ) { if ( $key =~ m{^important-(.*)$} ) { $important{ $1 } = $block->{ $key }; } else { $normal{ $key } = $block->{ $key }; } } my %properties; my @outputters; if ( $self->has_plugins() ) { map { push @outputters, "${_}::output" } $self->plugins(); } map { push @outputters, "CSS::Prepare::Property::${_}::output" } @MODULES; foreach my $outputter ( @outputters ) { my( @normal, @important ); eval { no strict 'refs'; @normal = &$outputter( $self, \%normal ); @important = &$outputter( $self, \%important ); }; say STDERR $@ if $@; foreach my $property ( @normal ) { $properties{ $property } = 1 if defined $property; } foreach my $property ( @important ) { if ( defined $property ) { my $prefix = $self->output_separator; $property =~ s{;$}{${prefix}!important;}; $properties{ $property } = 1; } } } return %properties; } sub output_format { my $self = shift; return $self->pretty_output ? $pretty_format : $concise_format; } sub output_separator { my $self = shift; return $self->pretty_output ? $pretty_separator : $concise_separator; } sub fetch_file { my $self = shift; my $file = shift; my $location = shift; my $target = $self->canonicalise_location( $file, $location ); return $self->read_url( $target ) if $target =~ RE_IS_URL; return $self->read_file( $target ); } sub read_file { my $self = shift; my $file = shift; my $handle = FileHandle->new( $file ); if ( defined $handle ) { local $/; return <$handle>; } return; } sub read_url { my $self = shift; my $url = shift; my $provider = $self->get_http_provider(); given ( $provider ) { when ( 'lite' ) { return $self->get_url_lite( $url ); } when ( 'lwp' ) { return $self->get_url_lwp( $url ); } } return; } sub get_url_lite { my $self = shift; my $url = shift; my $depth = shift // 1; # don't follow infinite redirections return unless $depth <= MAX_REDIRECT; my $http = HTTP::Lite->new(); $http->{'timeout'} = $self->get_http_timeout; my $code = $http->request( $url ); given ( $code ) { when ( 200 ) { return $http->body(); } when ( 301 || 302 || 303 || 307 ) { my $location = $http->get_header( 'Location' ); return $self->get_url_lite( $location, $depth+1 ); } default { return; } } } sub get_url_lwp { my $self = shift; my $url = shift; my $http = LWP::UserAgent->new( max_redirect => MAX_REDIRECT ); $http->timeout( $self->get_http_timeout ); my $resp = $http->get( $url ); my $code = $resp->code(); given ( $code ) { when ( 200 ) { return $resp->decoded_content(); } default { return; } } } sub copy_file_to_staging { my $self = shift; my $file = shift; my $location = $self->location() // shift; return unless $self->assets_output; my $content = $self->fetch_file( $file, $location ); return unless $content; my $hex = sha1_hex $content; my $filename = basename $file; my $assets_file = sprintf "%s/%s/%s-%s", $self->{'assets_base'}, substr( $hex, 0, 3 ), substr( $hex, 4 ), $filename; my $output_file = sprintf "%s/%s/%s-%s", $self->{'assets_output'}, substr( $hex, 0, 3 ), substr( $hex, 4 ), $filename; my $output_dir = dirname $output_file; mkpath $output_dir; my $handle = FileHandle->new( $output_file, 'w' ); print {$handle} $content; return $assets_file; } sub parse { my $self = shift; my $string = shift; my $location = shift; return unless defined $string; my( $charset, $stripped ) = strip_charset( $string ); return { errors => [{ fatal => "Unsupported charset '${charset}'" }] } unless 'UTF-8' eq $charset; $stripped = $self->strip_comments( $stripped ); $string = escape_braces_in_strings( $stripped ); my @split = $self->split_into_statements( $string, $location ); my @statements; my @appended; foreach my $statement ( @split ) { my $type = $statement->{'type'}; if ( 'appended' eq $type ) { push @statements, @{$statement->{'content'}}; } elsif ( 'import' eq $type ) { push @statements, $statement; } elsif ( 'rulesets' eq $type ) { my ( $rule_sets, $appended ) = $self->parse_rule_sets( $statement->{'content'}, $location ); push @statements, @$rule_sets; push @split, { type => 'appended', content => $appended, } if defined $appended; } elsif ( 'at-media' eq $type ) { my ( $rule_sets, $appended ) = $self->parse_rule_sets( $statement->{'content'}, $location ); push @{$statement->{'blocks'}}, @$rule_sets; delete $statement->{'content'}; push @statements, $statement; push @split, { type => 'appended', content => $appended, } if defined $appended; } else { die "unknown type '${type}'"; } } return @statements; } sub parse_rule_sets { my $self = shift; my $styles = shift; my $location = shift; return [] unless defined $styles; my @declaration_blocks = split_into_declaration_blocks( $styles ); my @rule_sets; my @appended; foreach my $block ( @declaration_blocks ) { my $type = $block->{'type'} // ''; my $preserve_as_is = defined $block->{'errors'} || 'verbatim' eq $type || 'boundary' eq $type; if ( $preserve_as_is ) { push @rule_sets, $block; } else { # extract from the string a data structure of selectors my( $selectors, $selectors_errors ) = parse_selectors( $block->{'selector'} ); my $declarations = {}; my $declaration_errors = []; my $append_blocks; # CSS2.1 4.1.6: "the whole statement should be ignored if # there is an error anywhere in the selector" if ( ! @$selectors_errors ) { # extract from the string a data structure of # declarations and their properties ( $declarations, $declaration_errors, $append_blocks ) = $self->parse_declaration_block( $block->{'block'}, $location, $selectors ); } push @appended, @$append_blocks if defined @$append_blocks; my $is_empty = !@$selectors_errors && !@$declaration_errors && !%{$declarations}; push @rule_sets, { original => unescape_braces( $block->{'block'} ), selectors => $selectors, errors => [ @$selectors_errors, @$declaration_errors ], block => $declarations, } unless $is_empty; } } return \@rule_sets, \@appended; } sub strip_charset { my $string = shift; # "User agents must support at least the UTF-8 encoding." my $charset = "UTF-8"; # "Authors using an @charset rule must place the rule at the very beginning # of the style sheet, preceded by no characters" if ( $string =~ s{^ \@charset \s " ([^"]+) "; }{}sx ) { $charset = $1; } return ( $charset, $string ); } sub strip_comments { my $self = shift; my $string = shift; # remove CDO/CDC markers $string =~ s{ <!-- }{}gsx; $string =~ s{ --> }{}gsx; if ( $self->support_extended_syntax ) { # remove line-level comments $string =~ s{ (?: ^ | \s ) // [^\n]* $ }{}gmx; } # disguise verbatim comments $string =~ s{ \/ \* \! ( .*? ) \* \/ }{%-COMMENT-%$1%-ENDCOMMENT-%}gsx; # disguise boundary markers $string =~ s{ \/ \* ( \s+ \-\-+ \s+ ) \* \/ }{%-COMMENT-%$1%-ENDCOMMENT-%}gsx; # remove CSS comments $string =~ s{ \/ \* .*? \* \/ }{}gsx; # reveal verbatim comments and boundary markers $string =~ s{%-COMMENT-%}{/*}gsx; $string =~ s{%-ENDCOMMENT-%}{*/}gsx; return $string; } sub escape_braces_in_strings { my $string = shift; my $strip_next_string = qr{ ^ ( .*? ) # $1: everything before the string ( ['"] ) # $2: the string delimiter ( .*? ) # $3: the content of the string (?<! \\ ) \2 # the string delimiter (but not escaped ones) }sx; # find all strings, and tokenise the braces within my $return; while ( $string =~ s{$strip_next_string}{}sx ) { my $before = $1; my $delim = $2; my $content = $3; $content =~ s{ \{ }{\%-LEFTBRACE-\%}gsx; $content =~ s{ \} }{\%-RIGHTBRACE-\%}gsx; $return .= "${before}${delim}${content}${delim}"; } $return .= $string; return $return; } sub unescape_braces { my $string = shift; $string =~ s{\%-LEFTBRACE-\%}{\{}gs; $string =~ s{\%-RIGHTBRACE-\%}{\}}gs; return $string; } sub split_into_statements { my $self = shift; my $string = shift; my $location = shift; # "In CSS 2.1, any @import rules must precede all other rules (except the # @charset rule, if present)." (CSS 2.1 #6.3) my ( $remainder, @statements ) = $self->do_import_rules( $string, $location ); my $splitter = qr{ ^ ( .*? ) # $1: everything before the media block \@media \s+ ( # $2: the media query $grammar_media_query_list ) \s* ( # $3: (used in the nested expression) \{ (?: # the content of the media block, (?> [^\{\}]+ ) # which is a nested recursive match... | # (?3) # ...triggered here ("(?3)" means use $3 )* \} # matching again) ) }sx; while ( $remainder =~ s{$splitter}{}sx ) { my $before = $1; my $query = $2; my $block = $3; # strip the outer braces from the media block $block =~ s{^ \{ (.*) \} $}{$1}sx; push @statements, { type => 'rulesets', content => $before, }; push @statements, { type => 'at-media', query => $query, content => $block, }; } push @statements, { type => 'rulesets', content => $remainder, }; return @statements; } sub do_import_rules { my $self = shift; my $string = shift; my $directory = shift; # "In CSS 2.1, any @import rules must precede all other rules (except the # @charset rule, if present)." (CSS 2.1 #6.3) my $splitter = qr{ ^ \s* \@import \s* ( $string_value | $url_value ) (?: \s+ ( $media_types_value ) )? \s* \; }x; my @blocks; while ( $string =~ s{$splitter}{}sx ) { my $import = $1; my $media = $2; $import =~ s{^ url\( \s* (.*?) \) $}{$1}x; # strip url() $import =~ s{^ ( ['"] ) (.*?) \1 $}{$2}x; # strip quotes my @styles = $self->parse_stylesheet( $import, $directory ); if ( @styles ) { push @blocks, { type => 'import', query => $media, blocks => [ @styles ], }; } } return $string, @blocks; } sub split_into_declaration_blocks { my $string = shift; my @blocks; my $get_import_rule = qr{ ^ \@import \s+ (?: $string_value | $url_value ) (?: \s+ ( $media_types_value ) )? \s* \; \s* }x; my $get_charset_rule = qr{ ^ \@charset \s \" [^"]+ \"; \s* }x; my $get_block = qr{ ^ (?<selector> .*? ) \s* \{ (?<block> [^\}]* ) \} \s* }sx; my $get_comment = qr{ ^ ( \/ \* (.*?) \* \/ ) \s* }sx; my $get_verbatim = qr{ ^ \/ \* \s+ verbatim \s+ \*\/ \s* ( .*? ) \s* \/ \* \s+ \-\-+ \s+ \*\/ }sx; my $get_chunk_boundary = qr{ ^ \/ \* \s+ \-\-+ \s+ \* \/ \s* }sx; while ( $string ) { $string =~ s{^\s*}{}sx; # check for a rogue @import rule if ( $string =~ s{$get_import_rule}{}sx ) { push @blocks, { errors => [ { error => '@import rule after statement(s) -- ' . 'ignored (CSS 2.1 #4.1.5)', }, ], }; } # check for a rogue @charset rule elsif ( $string =~ s{$get_charset_rule}{}sx ) { push @blocks, { errors => [ { error => '@charset rule inside stylsheet -- ' . 'ignored (CSS 2.1 #4.4)', }, ], }; } # check for chunk boundaries elsif ( $string =~ s{$get_chunk_boundary}{}sx ) { push @blocks, { type => 'boundary', }; } # check for verbatim blocks elsif ( $string =~ s{$get_verbatim}{}sx ) { push @blocks, { type => 'verbatim', string => "$1\n", }; } # check for verbatim comments elsif ( $string =~ s{$get_comment}{}sx ) { push @blocks, { type => 'verbatim', string => "$1\n", }; } # try and find the next declaration elsif ( $string =~ s{$get_block}{}sx ) { my %match = %+; push @blocks, \%match; } # give up elsif ( $string ) { push @blocks, { errors => [{ error => "Unknown content:\n${string}\n", }], }; $string = undef; } } return @blocks; } sub parse_selectors { my $string = shift; my @selectors; my $splitter = qr{ ^ \s* ( [^,]+ ) \s* \,? }sx; while ( $string =~ s{$splitter}{}sx ) { my $selector = $1; $selector =~ s{\s+}{ }sg; # CSS2.1 4.1.6: "the whole statement should be ignored if # there is an error anywhere in the selector" if ( ! is_valid_selector( $selector ) ) { return [], [ { error => 'ignored block - unknown selector' . " '${selector}' (CSS 2.1 #4.1.7)", } ]; } else { push @selectors, $selector; } } return \@selectors, []; } sub parse_declaration_block { my $self = shift; my $block = shift; my $location = shift; my $selectors = shift; # make '{' and '}' back into actual brackets again $block = unescape_braces( $block ); my( $remainder, @declarations ) = get_declarations_from_block( $block ); my( $declarations, $append_blocks ) = $self->expand_declarations( \@declarations, $selectors ); my %canonical; my @errors; DECLARATION: foreach my $declaration ( @$declarations ) { my %match = %{$declaration}; my $star_hack = 0; my $underscore_hack = 0; my $important = 0; my $has_hack = 0; if ( $self->support_hacks ) { $star_hack = 1 if $match{'property'} =~ s{^\*}{}; $underscore_hack = 1 if $match{'property'} =~ s{^_}{}; $has_hack = $star_hack || $underscore_hack; } $important = 1 if $match{'value'} =~ s{ \! \s* important $}{}x; # strip possible extraneous whitespace $match{'value'} =~ s{ \s+ $}{}x; my( $parsed_as, $errors ) = $self->parse_declaration( $has_hack, $location, %match ); if ( defined $parsed_as or $errors ) { push @errors, @$errors if @$errors; my %parsed; foreach my $property ( keys %$parsed_as ) { my $value = $parsed_as->{ $property }; $property = "_$property" if $underscore_hack; $property = "*$property" if $star_hack; $property = "important-$property" if $important; $parsed{ $property } = $value; } if ( %parsed ) { %canonical = ( %canonical, %parsed, ); } } else { push @errors, { error => "invalid property: '$match{'property'}'" }; } } if ( $remainder !~ m{^ \s* $}sx ) { $remainder =~ s{^ \s* (.*?) \s* $}{$1}sx; push @errors, { error => "invalid property: '$remainder'", }; } return \%canonical, \@errors, \@$append_blocks; } sub get_declarations_from_block { my $block = shift; my $splitter = qr{ ^ \s* (?<property> [^:]+? ) \s* \: \s* (?<value> [^;]+ ) \;? }sx; my @declarations; while ( $block =~ s{$splitter}{}sx ) { my %match = %+; push @declarations, \%match; } return $block, @declarations; } sub parse_declaration { my $self = shift; my $has_hack = shift; my $location = shift; my %declaration = @_; my @parsers; map { push @parsers, "CSS::Prepare::Property::${_}::parse" } @MODULES; if ( $self->has_plugins() ) { map { push @parsers, "${_}::parse" } $self->plugins(); } PARSER: foreach my $module ( @parsers ) { my $parsed_as; my $errors; eval { no strict 'refs'; ( $parsed_as, $errors ) = &$module( $self, $has_hack, $location, %declaration ); }; say STDERR $@ if $@; next PARSER unless ( defined $parsed_as || defined $errors ); return( $parsed_as, $errors ) if %$parsed_as or @$errors; } return; } sub expand_declarations { my $self = shift; my $declarations = shift; my $selectors = shift; my @filtered; my @append; if ( $self->has_plugins ) { DECLARATION: foreach my $declaration ( @$declarations ) { my $property = $declaration->{'property'}; my $value = $declaration->{'value'}; PLUGIN: foreach my $plugin ( $self->plugins() ) { no strict 'refs'; my $try_with = "${plugin}::expand"; my( $filtered, $new_rulesets, $new_chunks ) = &$try_with( $self, $property, $value, $selectors ); push @filtered, @{$filtered} if defined $filtered; push @$declarations, @$new_rulesets if defined $new_rulesets; push @append, @$new_chunks if defined $new_chunks; next DECLARATION if defined $filtered; } # if we get here, no plugin has dealt with the property push @filtered, $declaration; } } else { @filtered = @$declarations; } return \@filtered, \@append; } sub optimise { my $self = shift; my @data = @_; my @blocks; my @complete; while ( my $block = shift @data ) { my $type = $block->{'type'}; my $query = $block->{'query'}; if ( defined $type ) { # process any previously collected blocks my( $savings, @optimised ) = $self->optimise_blocks( @blocks ); undef @blocks; push @complete, @optimised if @optimised; # process this block ( $savings, @optimised ) = $self->optimise_blocks( @{$block->{'blocks'}} ); my $output_as_block = 'at-media' eq $type || ( 'import' eq $type && defined $query ); if ( $output_as_block ) { push @complete, { type => $type, query => $block->{'query'}, blocks => [ @optimised ], }; } elsif ( 'verbatim' eq $type ) { push @complete, $block; } elsif ( 'boundary' eq $type ) { # nothing extra to do } else { push @complete, @optimised if @optimised; } } else { # collect block for later processing push @blocks, $block; } } # process any remaining collected blocks my( $savings, @optimised ) = $self->optimise_blocks( @blocks ); push @complete, @optimised if @optimised; return @complete; } sub optimise_blocks { my $self = shift; my @blocks = @_; return 0 unless @blocks; my %styles = $self->sort_blocks_into_hash( @blocks ); my @properties = $self->array_of_properties( %styles ); # my $before = output_as_string( @properties ); my $declaration_count = scalar @properties; $self->status( " Found ${declaration_count} declarations." ); my ( $savings, %state ) = $self->get_optimal_state( @properties ); my @optimised = $self->get_blocks_from_state( %state ); # my $after = output_as_string( @optimised ); # my $savings = length( $before ) - length( $after ); # # say STDERR "Saved $savings bytes."; # # TODO - calculate savings, even when suboptimal has been used # my $savings = 0; return( $savings, @optimised ); } sub sort_blocks_into_hash { my $self = shift; my @data = @_; my %styles; foreach my $block ( @data ) { foreach my $property ( keys %{ $block->{'block'} } ) { my $value = $block->{'block'}{ $property }; foreach my $selector ( @{ $block->{'selectors'} } ) { $styles{ $selector }{ $property } = $value; } } } return %styles; } sub array_of_properties { my $self = shift; my %styles = @_; my @properties; foreach my $selector ( keys %styles ) { my %properties = $self->output_properties( $styles{ $selector } ); foreach my $property ( keys %properties ) { push @properties, $selector, $property; } } return @properties; } sub get_suboptimal_state { my %by_property = @_; # combine all properties by their selector -- makes a "margin:0;" property # with an "li" selector and a "padding:0;" property with an "li" selector # into an "li" selector with both "margin:0;" and "padding:0;" properties my %by_selector; foreach my $property ( keys %by_property ) { foreach my $selector ( keys %{$by_property{ $property }} ) { $by_selector{ $selector }{ $property } = 1; } } # combine selectors by shared properties -- makes a "div" and an "li" # which both have "margin:0;" and "padding:0;" properties into a # "margin:0;padding:0;" property with a "div" and "li" selector undef %by_property; foreach my $selector ( sort keys %by_selector ) { my $properties = join '', sort keys %{$by_selector{ $selector }}; $by_property{ $properties }{ $selector } = 1; } return %by_property; } sub get_optimal_state { my $self = shift; my @properties = @_; my %by_property = get_selectors_by_property( @properties ); my $found_savings = 1; my $total_savings = 0; # if only one thing has that property, the only thing it can be # successfully combined with is something with the same selector, # so don't even bother calculating possible savings on them, just # combine them at the end my( %multiples, %singles ); foreach my $property ( keys %by_property ) { my $selectors = scalar keys %{$by_property{ $property }}; if ( $selectors > 1 ) { $multiples{ $property } = $by_property{ $property }; } else { $singles{ $property } = $by_property{ $property }; } } my $do_suboptimal_pass = 0; if ( scalar keys %multiples ) { my $start_time = time(); my $time_out_after = $start_time + $self->suboptimal_threshold; my $check_for_timeout = $self->suboptimal_threshold > 0; my $count = 0; my %cache; MIX: while ( $found_savings ) { # adopt a faster strategy if there are too many properties # to deal with, or the code tends towards infinite # time taken to calculate the results my $timed_out = $check_for_timeout && ( time() >= $time_out_after ); if ( $timed_out ) { $do_suboptimal_pass = 1; $self->status( "\r Time threshold reached -- switching " . 'to suboptimal optimisation.' ); last MIX; } ( $found_savings, %multiples ) = mix_biggest_properties( \%cache, %multiples ); $total_savings += $found_savings; $count++; $self->status( " [$count] savings $total_savings", 'line' ); } } %by_property = ( %singles, %multiples ); %by_property = get_suboptimal_state( %by_property ) if $do_suboptimal_pass; return( $total_savings, %by_property); } sub get_selectors_by_property { my @properties = @_; my %by_property; while ( @properties ) { my $selector = shift @properties; my $property = shift @properties; $by_property{ $property }{ $selector } = 1; } return %by_property; } sub mix_biggest_properties { my $cache = shift; my %by_property = @_; my $num_children = sub { my $a_children = scalar keys %{$by_property{ $a }}; my $b_children = scalar keys %{$by_property{ $b }}; return $b_children <=> $a_children; }; my @sorted_properties = sort $num_children keys %by_property; foreach my $property ( @sorted_properties ) { my( $mix_with, $saving ) = get_biggest_saving_if_mixed( $property, $cache, %by_property ); if ( defined $mix_with ) { my %properties = mix_properties( $property, $mix_with, $cache, %by_property ); return( $saving, %properties ); } } return( 0, %by_property ); } sub get_biggest_saving_if_mixed { my $property = shift; my $cache = shift; my %properties = @_; return if defined $cache->{'no_savings'}{ $property }; my $unmixed_property_length = output_string_length( $property, keys %{$properties{ $property }} ); my $largest_value = 0; my $largest; EXAMINE: foreach my $examine ( keys %properties ) { next if $property eq $examine; next if 1 == scalar( keys %{$properties{ $examine }} ); my( $a, $b ) = sort( $property, $examine ); my $saving = $cache->{ $a }{ $b }; if ( !defined $saving ) { my @common_selectors = get_common_selectors( $property, $examine, %properties ); if ( 0 == scalar @common_selectors ) { $cache->{ $a }{ $b } = 0; next EXAMINE; } my @property_remaining = get_remaining_selectors( $examine, $property, %properties ); my @examine_remaining = get_remaining_selectors( $property, $examine, %properties ); my $unmixed_examine_length = output_string_length( $examine, keys %{$properties{ $examine }} ); my $mixed_common_length = output_string_length( "${property},${examine}", @common_selectors ); my $mixed_selector_length = output_string_length( $property, @property_remaining ); my $mixed_examine_length = output_string_length( $examine, @examine_remaining ); my $unmixed = $unmixed_property_length + $unmixed_examine_length; my $mixed = $mixed_common_length + $mixed_selector_length + $mixed_examine_length; $saving = $unmixed - $mixed; $cache->{ $a }{ $b } = $saving; } if ( $saving > $largest_value ) { $largest_value = $saving; $largest = $examine; } } $cache->{'no_savings'}{ $property } = 1 unless $largest_value; return( $largest, $largest_value ); } sub output_string_length { my $property = shift; my @selectors = @_; return 0 unless scalar @selectors; my $string = sprintf '%s{%s}', join( ',', @selectors ), $property; return length $string; } sub get_common_selectors { my $property = shift; my $examine = shift; my %properties = @_; my @common = grep { $_ if defined $properties{ $property }{ $_}; } keys %{$properties{ $examine }}; return @common; } sub get_remaining_selectors { my $property = shift; my $examine = shift; my %properties = @_; my @remaining = grep { $_ if !defined $properties{ $property }{ $_}; } keys %{$properties{ $examine }}; return @remaining; } sub mix_properties { my $property = shift; my $mix_with = shift; my $cache = shift; my %properties = @_; my $mixed_property = join '', sort( $property, $mix_with ); my @common_selectors = get_common_selectors( $property, $mix_with, %properties ); delete $cache->{ $property }; delete $cache->{'no_savings'}{ $property }; delete $cache->{ $mix_with }; delete $cache->{'no_savings'}{ $mix_with }; foreach my $selector ( @common_selectors ) { $properties{ $mixed_property }{ $selector } = 1; delete $properties{ $property }{ $selector }; delete $properties{ $mix_with }{ $selector }; } delete $properties{ $property } unless scalar keys %{$properties{ $property }}; delete $properties{ $mix_with } unless scalar keys %{$properties{ $mix_with }}; return %properties; } sub get_blocks_from_state { my $self = shift; my %by_property = @_; my $elements_first = sub { my $a_element = ( $a =~ m{^[a-z]}i ); my $b_element = ( $b =~ m{^[a-z]}i ); my $element_count = $a_element + $b_element; return ( $a_element ? -1 : 1 ) if 1 == $element_count; return $a cmp $b; }; my %by_selector; foreach my $property ( keys %by_property ) { my @selectors = sort $elements_first keys %{$by_property{ $property }}; my $selector = join ',', @selectors; $by_selector{ $selector }{ $property } = 1; } my @blocks; foreach my $selector ( sort $elements_first keys %by_selector ) { my @properties = sort keys %{$by_selector{ $selector }}; my $properties = join '', @properties; my $css = "${selector}{${properties}}"; push @blocks, $self->parse_string( $css ) } return @blocks; } sub is_valid_selector { my $test = shift; $test = lc $test; my $nmchar = qr{ (?: [_a-z0-9-] ) }x; my $ident = qr{ -? [_a-z] $nmchar * }x; my $element = qr{ (?: $ident | \* ) }x; my $hash = qr{ \# $nmchar + }x; my $class = qr{ \. $ident }x; my $string = qr{ (?: \' $ident \' | \" $ident \" ) }x; my $pseudo = qr{ \: (?: # TODO - I am deliberately ignoring FUNCTION here for now # FUNCTION \s* (?: $ident \s* )? \) $ident \( .* \) | $ident ) }x; my $attrib = qr{ \[ \s* $ident \s* (?: (?: \= | \~\= | \|\= ) \s* (?: $ident | $string ) \s* )? \s* \] }x; my $parts = qr{ (?: $pseudo | $hash | $class | $attrib ) }x; my $simple_selector = qr{ (?: $element $parts * | $parts + ) }x; my $combinator = qr{ (?: [\+\~] \s* | \> \s* ) }x; my $next_selector = qr{ \s* (?: $combinator )? $simple_selector \s* }x; while ( $test =~ s{^ $next_selector }{}x ) { # do nothing, already validated by the regexp } return 0 if length $test; return 1; } sub status { my $self = shift; my $text = shift; my $temp = shift; no strict 'refs'; my $status = $self->{'status'}; &$status( $text, $temp ); } sub status_to_stderr { my $text = shift; my $temp = shift; print STDERR ( $temp ? "\r" : '' ) . $text; } 1; __END__ =head1 NAME B<CSS::Prepare> - pre-process cascading style sheets to make them ready for deployment =head1 SYNOPSIS In your code: my $preparer = CSS::Prepare->new( %opts ); foreach my $stylesheet ( @ARGV ) { print process_stylesheet( $stylesheet ); } In your build process: % cssprepare -e -o styles/*.css > styles/combined.css =head1 OPTIONS The B<new()> method accepts a hash as arguments to control aspects of the eventual output. =over =item hacks I<(boolean)> Switch support for various CSS "hacks" on or off. See L<Supported CSS hacks> in L<CSS::Prepare::Manual>. Defaults to I<true>. =item extended I<(boolean)> Switch support for extensions to the CSS syntax, which are incompatible with the CSS specification (but can make life easier). See L<Extending the CSS syntax> in L<CSS::Prepare::Manual>. Defaults to I<false>. =item suboptimal_threshold I<(int)> Number of seconds that CSS::Prepare will spend optimising each CSS fragment in the more accurate way before switching to a less accurate but much faster algorithm. See <Optimising CSS> in L<CSS::Prepare::Manual>. Defaults to I<10>. If set to zero, it will never switch to the suboptimal method. Do note that large style sheets with thousands of rule sets can take several minutes to process fully, and the extra savings are quite minimal after the first few seconds have elapsed. =item http_timeout I<(int)> Number of seconds that CSS::Prepare will wait whilst trying to fetch a remote style sheet before giving up. Defaults to I<30>. =item pretty I<(boolean)> Switch to support pretty-printed output rather than highly compressed. Defaults to I<false>. Note that this only affects the amount of white space used in the output. All comments and invalid rule sets and declarations from the source style sheets are still dropped before output. =item status I<(callback)> Override how status reports are handled. The callback subroutine is given two parameters: the text to be printed and a flag to say if it is expected to be a temporary line (ie. can be overwritten). The default callback is: sub status_to_stderr { my $text = shift; my $temp = shift; print STDERR ( $temp ? "\r" : '' ) . $text; } Status reports can be silenced by providing a null callback, like so: my $preparer = CSS::Prepare->new( status => sub {} ); =back =head1 REQUIREMENTS The only fixed requirement CSS::Prepare has is that the version of the perl interpreter must be at least 5.10. If you wish to use C<@import url(...);> in your style sheets you will need one of L<HTTP::Lite> or L<LWP::UserAgent> installed. Some parts of the extended CSS syntax are implemented as optional plugins. For these to work you will need L<Module::Pluggable> installed. To use the C<--server> option in the C<cssprepare> script, you will need L<Plack::Runner> installed. =head1 SEE ALSO =over =item * L<cssprepare> (command-line script) =item * L<CSS::Prepare::Manual> =item * CSS::Prepare online: L<http://cssprepare.com/> =back =head1 AUTHOR Mark Norman Francis, L<norm@cackhanded.net>. =head1 COPYRIGHT AND LICENSE Copyright 2010 Mark Norman Francis. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
norm/CSS-Prepare
p5-CSS-Prepare/lib/CSS/Prepare.pm
Perl
bsd-3-clause
51,686
#!%PERL% # Copyright (c) vhffs project and its contributors # 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. Neither the name of vhffs nor the names of its contributors # may be used to endorse or promote products derived from this # software without specific prior written permission. # #THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS #"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS #FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE #COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, #INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, #BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; #LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER #CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. use strict; use utf8; use lib '%VHFFS_LIB_DIR%'; use Vhffs::Robots; use Vhffs::User; my $vhffs = new Vhffs; exit 1 unless defined $vhffs; Vhffs::Robots::lock( $vhffs, 'user' ); my $users = Vhffs::User::get_unused_accounts( $vhffs , 2592000 ); # 30 days foreach ( @{$users} ) { Vhffs::Robots::vhffs_log( $vhffs, 'Deleted user '.$_->get_username.' because it was unused' ); $_->pendingdeletion_withmail; } Vhffs::Robots::unlock( $vhffs, 'user' ); exit 0;
najamelan/vhffs-4.5
vhffs-robots/src/user_cleanup.pl
Perl
bsd-3-clause
2,010
#################################################################################################################################### # COMMON STRING MODULE #################################################################################################################################### package pgBackRestDoc::Common::String; use strict; use warnings FATAL => qw(all); use Carp qw(confess longmess); use Exporter qw(import); our @EXPORT = qw(); use File::Basename qw(dirname); #################################################################################################################################### # trim # # Trim whitespace. #################################################################################################################################### sub trim { my $strBuffer = shift; if (!defined($strBuffer)) { return; } $strBuffer =~ s/^\s+|\s+$//g; return $strBuffer; } push @EXPORT, qw(trim); #################################################################################################################################### # coalesce - return first defined parameter #################################################################################################################################### sub coalesce { foreach my $strParam (@_) { if (defined($strParam)) { return $strParam; } } return; } push @EXPORT, qw(coalesce); #################################################################################################################################### # timestampFormat # # Get standard timestamp format (or formatted as specified). #################################################################################################################################### sub timestampFormat { my $strFormat = shift; my $lTime = shift; if (!defined($strFormat)) { $strFormat = '%4d-%02d-%02d %02d:%02d:%02d'; } if (!defined($lTime)) { $lTime = time(); } my ($iSecond, $iMinute, $iHour, $iMonthDay, $iMonth, $iYear, $iWeekDay, $iYearDay, $bIsDst) = localtime($lTime); if ($strFormat eq "%4d") { return sprintf($strFormat, $iYear + 1900) } else { return sprintf($strFormat, $iYear + 1900, $iMonth + 1, $iMonthDay, $iHour, $iMinute, $iSecond); } } push @EXPORT, qw(timestampFormat); #################################################################################################################################### # stringSplit #################################################################################################################################### sub stringSplit { my $strString = shift; my $strChar = shift; my $iLength = shift; if (length($strString) <= $iLength) { return $strString, undef; } my $iPos = index($strString, $strChar); if ($iPos == -1) { return $strString, undef; } my $iNewPos = $iPos; while ($iNewPos != -1 && $iNewPos + 1 < $iLength) { $iPos = $iNewPos; $iNewPos = index($strString, $strChar, $iPos + 1); } return substr($strString, 0, $iPos + 1), substr($strString, $iPos + 1); } push @EXPORT, qw(stringSplit); 1;
pgbackrest/pgbackrest
doc/lib/pgBackRestDoc/Common/String.pm
Perl
mit
3,279
#!perl use Test::More; use strict; use warnings; our $es; my $r; ### INDEX STATUS ### my $indices; ok $indices = $es->index_status()->{indices}, 'Index status - all'; ok $indices->{'es_test_1'}, ' - Index 1 exists'; ok $indices->{'es_test_2'}, ' - Index 2 exists'; is $es->cluster_state->{metadata}{indices}{'es_test_2'}{settings} {"index.number_of_shards"}, 3, ' - Index 2 settings'; throws_ok { $es->index_status( index => 'foo' ) } qr/Missing/, ' - index missing'; ok $r= $es->index_status( index => 'es_test_1', recovery => 1, snapshot => 1 ) ->{indices}{es_test_1}{shards}{0}, ' - recovery and snapshot'; ok $r->[0]{peer_recovery} || $r->[0]{gateway_recovery}, ' - recovery'; 1;
elastic/elasticsearch-perl-compat
t/request_tests/index_status.pl
Perl
apache-2.0
703
package Google::Ads::AdWords::v201406::SharedSetService::ApiExceptionFault; use strict; use warnings; { # BLOCK to scope variables sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201406' } __PACKAGE__->__set_name('ApiExceptionFault'); __PACKAGE__->__set_nillable(); __PACKAGE__->__set_minOccurs(); __PACKAGE__->__set_maxOccurs(); __PACKAGE__->__set_ref(); use base qw( SOAP::WSDL::XSD::Typelib::Element Google::Ads::AdWords::v201406::ApiException ); } 1; =pod =head1 NAME Google::Ads::AdWords::v201406::SharedSetService::ApiExceptionFault =head1 DESCRIPTION Perl data type class for the XML Schema defined element ApiExceptionFault from the namespace https://adwords.google.com/api/adwords/cm/v201406. A fault element of type ApiException. =head1 METHODS =head2 new my $element = Google::Ads::AdWords::v201406::SharedSetService::ApiExceptionFault->new($data); Constructor. The following data structure may be passed to new(): $a_reference_to, # see Google::Ads::AdWords::v201406::ApiException =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201406/SharedSetService/ApiExceptionFault.pm
Perl
apache-2.0
1,085
package Google::Ads::AdWords::v201406::NotEmptyError; use strict; use warnings; __PACKAGE__->_set_element_form_qualified(1); sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201406' }; our $XML_ATTRIBUTE_CLASS; undef $XML_ATTRIBUTE_CLASS; sub __get_attr_class { return $XML_ATTRIBUTE_CLASS; } use base qw(Google::Ads::AdWords::v201406::ApiError); # Variety: sequence use Class::Std::Fast::Storable constructor => 'none'; use base qw(Google::Ads::SOAP::Typelib::ComplexType); { # BLOCK to scope variables my %fieldPath_of :ATTR(:get<fieldPath>); my %trigger_of :ATTR(:get<trigger>); my %errorString_of :ATTR(:get<errorString>); my %ApiError__Type_of :ATTR(:get<ApiError__Type>); my %reason_of :ATTR(:get<reason>); __PACKAGE__->_factory( [ qw( fieldPath trigger errorString ApiError__Type reason ) ], { 'fieldPath' => \%fieldPath_of, 'trigger' => \%trigger_of, 'errorString' => \%errorString_of, 'ApiError__Type' => \%ApiError__Type_of, 'reason' => \%reason_of, }, { 'fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'ApiError__Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'reason' => 'Google::Ads::AdWords::v201406::NotEmptyError::Reason', }, { 'fieldPath' => 'fieldPath', 'trigger' => 'trigger', 'errorString' => 'errorString', 'ApiError__Type' => 'ApiError.Type', 'reason' => 'reason', } ); } # end BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201406::NotEmptyError =head1 DESCRIPTION Perl data type class for the XML Schema defined complexType NotEmptyError from the namespace https://adwords.google.com/api/adwords/cm/v201406. Errors corresponding with violation of a NOT EMPTY check. =head2 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * reason =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/v201406/NotEmptyError.pm
Perl
apache-2.0
2,253
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the 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>. =head1 AUTHOR Juguang Xiao <juguang@tll.org.sg> =cut =head1 NAME Bio::EnsEMBL::Utils::Converter::bio_ens_exon =head1 SYNOPISIS =head1 DESCRIPTION =head1 METHODS =cut package Bio::EnsEMBL::Utils::Converter::bio_ens_exon; use strict; use vars qw(@ISA %GTF_ENS_PHASE); use Bio::EnsEMBL::Utils::Converter; use Bio::EnsEMBL::Exon; use Bio::EnsEMBL::DnaPepAlignFeature; use Bio::EnsEMBL::Utils::Converter::bio_ens; @ISA = qw(Bio::EnsEMBL::Utils::Converter::bio_ens); BEGIN { %GTF_ENS_PHASE = ( 0 => 0, 1 => 2, 2 => 1, '.' => -1 ); } sub _initialize { my ($self, @args) = @_; $self->SUPER::_initialize(@args); $self->{_bio_ens_seqFeature} = new Bio::EnsEMBL::Utils::Converter ( -in => 'Bio::SeqFeature::Generic', -out => 'Bio::EnsEMBL::SeqFeature', ); $self->{_bio_ens_featurePair} = new Bio::EnsEMBL::Utils::Converter ( -in => 'Bio::SeqFeature::FeaturePair', -out => 'Bio::EnsEMBL::FeaturePair' ); } sub _attach_supporting_feature { my ($self, $exon, $ens_exon) = @_; unless($exon->has_tag('supporting_feature')){ return; } my ($sf) = $exon->each_tag_value('supporting_feature'); unless(defined $sf){ $self->warn("no supporting feature is attached in exon"); return; } # $self->{_bio_ens_seqFeature}->contig($self->contig); $self->{_bio_ens_seqFeature}->analysis($self->analysis); my $ens_f1 = $self->{_bio_ens_seqFeature}->_convert_single($sf->feature1); my $ens_f2 = $self->{_bio_ens_seqFeature}->_convert_single($sf->feature2); $self->{_bio_ens_featurePair}->contig($self->contig); $self->{_bio_ens_featurePair}->analysis($self->analysis); my $ens_sf = $self->{_bio_ens_featurePair}->_convert_single($sf); my @align_feautre_args = ( -feature1 => $ens_f1, -feature2 => $ens_f2, -features => [$ens_sf] ); my $ens_supporting_feature = Bio::EnsEMBL::DnaPepAlignFeature->new(@align_feautre_args); $ens_exon->add_supporting_features($ens_supporting_feature); } sub _convert_single { my ($self, $arg) = @_; unless($arg && $arg->isa('Bio::SeqFeature::Gene::Exon')){ $self->throw("a Bio::SeqFeature::Gene::Exon object needed"); } my $exon = $arg; my $ens_exon = Bio::EnsEMBL::Exon->new_fast( $self->contig, $exon->start, $exon->end, $exon->strand); my ($phase) = $exon->each_tag_value('phase'); $ens_exon->phase($GTF_ENS_PHASE{$phase}); my $ens_end_phase = 3 - ($exon->length - $phase) % 3; $ens_end_phase = 0 if $ens_end_phase == 3; $ens_exon->end_phase($ens_end_phase); if($self->contig->isa('Bio::EnsEMBL::RawContig')){ $ens_exon->sticky_rank(1); } $self->_attach_supporting_feature($exon, $ens_exon); return $ens_exon; } 1;
mjg17/ensembl
modules/Bio/EnsEMBL/Utils/Converter/bio_ens_exon.pm
Perl
apache-2.0
3,746
package CPANPLUS::Dist::MM; use deprecate; use strict; use warnings; use vars qw[@ISA $STATUS $VERSION]; use base 'CPANPLUS::Dist::Base'; $VERSION = "0.9135"; use CPANPLUS::Internals::Constants; use CPANPLUS::Internals::Constants::Report; use CPANPLUS::Error; use FileHandle; use Cwd; use IPC::Cmd qw[run]; use Params::Check qw[check]; use File::Basename qw[dirname]; use Module::Load::Conditional qw[can_load check_install]; use Locale::Maketext::Simple Class => 'CPANPLUS', Style => 'gettext'; local $Params::Check::VERBOSE = 1; =pod =head1 NAME CPANPLUS::Dist::MM - distribution class for MakeMaker related modules =head1 SYNOPSIS $mm = CPANPLUS::Dist::MM->new( module => $modobj ); $mm->create; # runs make && make test $mm->install; # runs make install =head1 DESCRIPTION C<CPANPLUS::Dist::MM> is a distribution class for MakeMaker related modules. Using this package, you can create, install and uninstall perl modules. It inherits from C<CPANPLUS::Dist>. =head1 ACCESSORS =over 4 =item parent() Returns the C<CPANPLUS::Module> object that parented this object. =item status() Returns the C<Object::Accessor> object that keeps the status for this module. =back =head1 STATUS ACCESSORS All accessors can be accessed as follows: $mm->status->ACCESSOR =over 4 =item makefile () Location of the Makefile (or Build file). Set to 0 explicitly if something went wrong. =item make () BOOL indicating if the C<make> (or C<Build>) command was successful. =item test () BOOL indicating if the C<make test> (or C<Build test>) command was successful. =item prepared () BOOL indicating if the C<prepare> call exited successfully This gets set after C<perl Makefile.PL> =item distdir () Full path to the directory in which the C<prepare> call took place, set after a call to C<prepare>. =item created () BOOL indicating if the C<create> call exited successfully. This gets set after C<make> and C<make test>. =item installed () BOOL indicating if the module was installed. This gets set after C<make install> (or C<Build install>) exits successfully. =item uninstalled () BOOL indicating if the module was uninstalled properly. =item _create_args () Storage of the arguments passed to C<create> for this object. Used for recursive calls when satisfying prerequisites. =item _install_args () Storage of the arguments passed to C<install> for this object. Used for recursive calls when satisfying prerequisites. =back =cut =head1 METHODS =head2 $bool = $dist->format_available(); Returns a boolean indicating whether or not you can use this package to create and install modules in your environment. =cut ### check if the format is available ### sub format_available { my $dist = shift; ### we might be called as $class->format_available =/ require CPANPLUS::Internals; my $cb = CPANPLUS::Internals->_retrieve_id( CPANPLUS::Internals->_last_id ); my $conf = $cb->configure_object; my $mod = "ExtUtils::MakeMaker"; unless( can_load( modules => { $mod => 0.0 } ) ) { error( loc( "You do not have '%1' -- '%2' not available", $mod, __PACKAGE__ ) ); return; } for my $pgm ( qw[make] ) { unless( $conf->get_program( $pgm ) ) { error(loc( "You do not have '%1' in your path -- '%2' not available\n" . "Please check your config entry for '%1'", $pgm, __PACKAGE__ , $pgm )); return; } } return 1; } =pod =head2 $bool = $dist->init(); Sets up the C<CPANPLUS::Dist::MM> object for use. Effectively creates all the needed status accessors. Called automatically whenever you create a new C<CPANPLUS::Dist> object. =cut sub init { my $dist = shift; my $status = $dist->status; $status->mk_accessors(qw[makefile make test created installed uninstalled bin_make _prepare_args _create_args _install_args] ); return 1; } =pod =head2 $bool = $dist->prepare([perl => '/path/to/perl', makemakerflags => 'EXTRA=FLAGS', force => BOOL, verbose => BOOL]) C<prepare> preps a distribution for installation. This means it will run C<perl Makefile.PL> and determine what prerequisites this distribution declared. If you set C<force> to true, it will go over all the stages of the C<prepare> process again, ignoring any previously cached results. When running C<perl Makefile.PL>, the environment variable C<PERL5_CPANPLUS_IS_EXECUTING> will be set to the full path of the C<Makefile.PL> that is being executed. This enables any code inside the C<Makefile.PL> to know that it is being installed via CPANPLUS. Returns true on success and false on failure. You may then call C<< $dist->create >> on the object to create the installable files. =cut sub prepare { ### just in case you already did a create call for this module object ### just via a different dist object my $dist = shift; my $self = $dist->parent; ### we're also the cpan_dist, since we don't need to have anything ### prepared $dist = $self->status->dist_cpan if $self->status->dist_cpan; $self->status->dist_cpan( $dist ) unless $self->status->dist_cpan; my $cb = $self->parent; my $conf = $cb->configure_object; my %hash = @_; my $dir; unless( $dir = $self->status->extract ) { error( loc( "No dir found to operate on!" ) ); return; } my $args; my( $force, $verbose, $perl, $mmflags, $prereq_target, $prereq_format, $prereq_build ); { local $Params::Check::ALLOW_UNKNOWN = 1; my $tmpl = { perl => { default => $^X, store => \$perl }, makemakerflags => { default => $conf->get_conf('makemakerflags') || '', store => \$mmflags }, force => { default => $conf->get_conf('force'), store => \$force }, verbose => { default => $conf->get_conf('verbose'), store => \$verbose }, prereq_target => { default => '', store => \$prereq_target }, prereq_format => { default => '', store => \$prereq_format }, prereq_build => { default => 0, store => \$prereq_build }, }; $args = check( $tmpl, \%hash ) or return; } my @mmflags = $dist->_split_like_shell( $mmflags ); ### maybe we already ran a create on this object? ### return 1 if $dist->status->prepared && !$force; ### store the arguments, so ->install can use them in recursive loops ### $dist->status->_prepare_args( $args ); ### chdir to work directory ### my $orig = cwd(); unless( $cb->_chdir( dir => $dir ) ) { error( loc( "Could not chdir to build directory '%1'", $dir ) ); return; } my $fail; RUN: { ### we resolve 'configure requires' here, so we can run the 'perl ### Makefile.PL' command ### XXX for tests: mock f_c_r to something that *can* resolve and ### something that *doesn't* resolve. Check the error log for ok ### on this step or failure ### XXX make a separate tarball to test for this scenario: simply ### containing a makefile.pl/build.pl for test purposes? { my $configure_requires = $dist->find_configure_requires; my $ok = $dist->_resolve_prereqs( format => $prereq_format, verbose => $verbose, prereqs => $configure_requires, target => $prereq_target, force => $force, prereq_build => $prereq_build, ); unless( $ok ) { #### use $dist->flush to reset the cache ### error( loc( "Unable to satisfy '%1' for '%2' " . "-- aborting install", 'configure_requires', $self->module ) ); $dist->status->prepared(0); $fail++; last RUN; } ### end of prereq resolving ### } ### don't run 'perl makefile.pl' again if there's a makefile already if( -e MAKEFILE->() && (-M MAKEFILE->() < -M $dir) && !$force ) { msg(loc("'%1' already exists, not running '%2 %3' again ". " unless you force", MAKEFILE->(), $perl, MAKEFILE_PL->() ), $verbose ); } else { unless( -e MAKEFILE_PL->() ) { msg(loc("No '%1' found - attempting to generate one", MAKEFILE_PL->() ), $verbose ); $dist->write_makefile_pl( verbose => $verbose, force => $force ); ### bail out if there's no makefile.pl ### unless( -e MAKEFILE_PL->() ) { error( loc( "Could not find '%1' - cannot continue", MAKEFILE_PL->() ) ); ### mark that we screwed up ### $dist->status->makefile(0); $fail++; last RUN; } } ### you can turn off running this verbose by changing ### the config setting below, although it is really not ### recommended my $run_verbose = $verbose || $conf->get_conf('allow_build_interactivity') || 0; ### this makes MakeMaker use defaults if possible, according ### to schwern. See ticket 8047 for details. local $ENV{PERL_MM_USE_DEFAULT} = 1 unless $run_verbose; ### turn off our PERL5OPT so no modules from CPANPLUS::inc get ### included in the makefile.pl -- it should build without ### also, modules that run in taint mode break if we leave ### our code ref in perl5opt ### XXX we've removed the ENV settings from cp::inc, so only need ### to reset the @INC #local $ENV{PERL5OPT} = CPANPLUS::inc->original_perl5opt || ''; ### make sure it's a string, so that mmflags that have more than ### one key value pair are passed as is, rather than as: ### perl Makefile.PL "key=val key=>val" #### XXX this needs to be the absolute path to the Makefile.PL ### since cpanp-run-perl uses 'do' to execute the file, and do() ### checks your @INC.. so, if there's _another_ makefile.pl in ### your @INC, it will execute that one... my $makefile_pl = MAKEFILE_PL->( $cb->_safe_path( path => $dir ) ); ### setting autoflush to true fixes issue from rt #8047 ### XXX this means that we need to keep the path to CPANPLUS ### in @INC, stopping us from resolving dependencies on CPANPLUS ### at bootstrap time properly. my @run_perl = ( '-e', PERL_WRAPPER ); my $cmd = [$perl, @run_perl, $makefile_pl, @mmflags]; ### set ENV var to tell underlying code this is what we're ### executing. my $captured; my $rv = do { my $env = ENV_CPANPLUS_IS_EXECUTING; local $ENV{$env} = $makefile_pl; scalar run( command => $cmd, buffer => \$captured, verbose => $run_verbose, # may be interactive ); }; unless( $rv ) { error( loc( "Could not run '%1 %2': %3 -- cannot continue", $perl, MAKEFILE_PL->(), $captured ) ); $dist->status->makefile(0); $fail++; last RUN; } ### put the output on the stack, don't print it msg( $captured, 0 ); } ### so, nasty feature in Module::Build, that when a Makefile.PL ### is a disguised Build.PL, it generates a Build file, not a ### Makefile. this breaks everything :( see rt bug #19741 if( not -e MAKEFILE->( $dir ) and -e BUILD_PL->( $dir ) ) { error(loc( "We just ran '%1' without errors, but no '%2' is ". "present. However, there is a '%3' file, so this may ". "be related to bug #19741 in %4, which describes a ". "fake '%5' which generates a '%6' file instead of a '%7'. ". "You could try to work around this issue by setting '%8' ". "to false and trying again. This will attempt to use the ". "'%9' instead.", "$^X ".MAKEFILE_PL->(), MAKEFILE->(), BUILD_PL->(), 'Module::Build', MAKEFILE_PL->(), 'Build', MAKEFILE->(), 'prefer_makefile', BUILD_PL->() )); $fail++, last RUN; } ### if we got here, we managed to make a 'makefile' ### $dist->status->makefile( MAKEFILE->($dir) ); ### Make (haha) sure that Makefile.PL is older than the Makefile ### we just generated. eval { my $makestat = ( stat MAKEFILE->( $dir ) )[9]; my $mplstat = ( stat MAKEFILE_PL->( $cb->_safe_path( path => $dir ) ) )[9]; if ( $makestat < $mplstat ) { my $ftime = $makestat - 60; utime $ftime, $ftime, MAKEFILE_PL->( $cb->_safe_path( path => $dir ) ); } }; ### start resolving prereqs ### my $prereqs = $self->status->prereqs; ### a hashref of prereqs on success, undef on failure ### $prereqs ||= $dist->_find_prereqs( verbose => $verbose, file => $dist->status->makefile ); unless( $prereqs ) { error( loc( "Unable to scan '%1' for prereqs", $dist->status->makefile ) ); $fail++; last RUN; } } unless( $cb->_chdir( dir => $orig ) ) { error( loc( "Could not chdir back to start dir '%1'", $orig ) ); } ### save where we wrote this stuff -- same as extract dir in normal ### installer circumstances $dist->status->distdir( $self->status->extract ); return $dist->status->prepared( $fail ? 0 : 1); } =pod =head2 $href = $dist->_find_prereqs( file => '/path/to/Makefile', [verbose => BOOL]) Parses a C<Makefile> for C<PREREQ_PM> entries and distills from that any prerequisites mentioned in the C<Makefile> Returns a hash with module-version pairs on success and false on failure. =cut sub _find_prereqs { my $dist = shift; my $self = $dist->parent; my $cb = $self->parent; my $conf = $cb->configure_object; my %hash = @_; my ($verbose, $file); my $tmpl = { verbose => { default => $conf->get_conf('verbose'), store => \$verbose }, file => { required => 1, allow => FILE_READABLE, store => \$file }, }; my $args = check( $tmpl, \%hash ) or return; ### see if we got prereqs from MYMETA my $prereqs = $dist->find_mymeta_requires(); ### we found some prereqs, we'll trust MYMETA ### but we do need to run it through the callback return $cb->_callbacks->filter_prereqs->( $cb, $prereqs ) if keys %$prereqs; my $fh = FileHandle->new(); unless( $fh->open( $file ) ) { error( loc( "Cannot open '%1': %2", $file, $! ) ); return; } my %p; while( local $_ = <$fh> ) { my ($found) = m|^[\#]\s+PREREQ_PM\s+=>\s+(.+)|; next unless $found; while( $found =~ m/(?:\s)([\w\:]+)=>(?:q\[(.*?)\],?|undef)/g ) { if( defined $p{$1} ) { my $ver = $cb->_version_to_number(version => $2); $p{$1} = $ver if $cb->_vcmp( $ver, $p{$1} ) > 0; } else { $p{$1} = $cb->_version_to_number(version => $2); } } last; } my $href = $cb->_callbacks->filter_prereqs->( $cb, \%p ); $self->status->prereqs( $href ); ### just to make sure it's not the same reference ### return { %$href }; } =pod =head2 $bool = $dist->create([perl => '/path/to/perl', make => '/path/to/make', makeflags => 'EXTRA=FLAGS', prereq_target => TARGET, skiptest => BOOL, force => BOOL, verbose => BOOL]) C<create> creates the files necessary for installation. This means it will run C<make> and C<make test>. This will also scan for and attempt to satisfy any prerequisites the module may have. If you set C<skiptest> to true, it will skip the C<make test> stage. If you set C<force> to true, it will go over all the stages of the C<make> process again, ignoring any previously cached results. It will also ignore a bad return value from C<make test> and still allow the operation to return true. Returns true on success and false on failure. You may then call C<< $dist->install >> on the object to actually install it. =cut sub create { ### just in case you already did a create call for this module object ### just via a different dist object my $dist = shift; my $self = $dist->parent; ### we're also the cpan_dist, since we don't need to have anything ### prepared $dist = $self->status->dist_cpan if $self->status->dist_cpan; $self->status->dist_cpan( $dist ) unless $self->status->dist_cpan; my $cb = $self->parent; my $conf = $cb->configure_object; my %hash = @_; my $dir; unless( $dir = $self->status->extract ) { error( loc( "No dir found to operate on!" ) ); return; } my $args; my( $force, $verbose, $make, $makeflags, $skiptest, $prereq_target, $perl, @mmflags, $prereq_format, $prereq_build); { local $Params::Check::ALLOW_UNKNOWN = 1; my $tmpl = { perl => { default => $^X, store => \$perl }, force => { default => $conf->get_conf('force'), store => \$force }, verbose => { default => $conf->get_conf('verbose'), store => \$verbose }, make => { default => $conf->get_program('make'), store => \$make }, makeflags => { default => $conf->get_conf('makeflags'), store => \$makeflags }, skiptest => { default => $conf->get_conf('skiptest'), store => \$skiptest }, prereq_target => { default => '', store => \$prereq_target }, ### don't set the default prereq format to 'makemaker' -- wrong! prereq_format => { #default => $self->status->installer_type, default => '', store => \$prereq_format }, prereq_build => { default => 0, store => \$prereq_build }, }; $args = check( $tmpl, \%hash ) or return; } my @makeflags = $dist->_split_like_shell( $makeflags ); ### maybe we already ran a create on this object? ### make sure we add to include path again, just in case we came from ### ->save_state, at which point we need to restore @INC/$PERL5LIB if( $dist->status->created && !$force ) { $self->add_to_includepath; return 1; } ### store the arguments, so ->install can use them in recursive loops ### $dist->status->_create_args( $args ); unless( $dist->status->prepared ) { error( loc( "You have not successfully prepared a '%2' distribution ". "yet -- cannot create yet", __PACKAGE__ ) ); return; } ### chdir to work directory ### my $orig = cwd(); unless( $cb->_chdir( dir => $dir ) ) { error( loc( "Could not chdir to build directory '%1'", $dir ) ); return; } my $fail; my $prereq_fail; my $test_fail; my $status = { }; RUN: { ### this will set the directory back to the start ### dir, so we must chdir /again/ my $ok = $dist->_resolve_prereqs( format => $prereq_format, verbose => $verbose, prereqs => $self->status->prereqs, target => $prereq_target, force => $force, prereq_build => $prereq_build, ); unless( $cb->_chdir( dir => $dir ) ) { error( loc( "Could not chdir to build directory '%1'", $dir ) ); return; } unless( $ok ) { #### use $dist->flush to reset the cache ### error( loc( "Unable to satisfy prerequisites for '%1' " . "-- aborting install", $self->module ) ); $dist->status->make(0); $fail++; $prereq_fail++; last RUN; } ### end of prereq resolving ### my $captured; ### 'make' section ### if( -d BLIB->($dir) && (-M BLIB->($dir) < -M $dir) && !$force ) { msg(loc("Already ran '%1' for this module [%2] -- " . "not running again unless you force", $make, $self->module ), $verbose ); } else { unless(scalar run( command => [$make, @makeflags], buffer => \$captured, verbose => $verbose ) ) { error( loc( "MAKE failed: %1 %2", $!, $captured ) ); if ( $conf->get_conf('cpantest') ) { $status->{stage} = 'build'; $status->{capture} = $captured; } $dist->status->make(0); $fail++; last RUN; } ### put the output on the stack, don't print it msg( $captured, 0 ); $dist->status->make(1); ### add this directory to your lib ### $self->add_to_includepath(); ### dont bail out here, there's a conditional later on #last RUN if $skiptest; } ### 'make test' section ### unless( $skiptest ) { ### turn off our PERL5OPT so no modules from CPANPLUS::inc get ### included in make test -- it should build without ### also, modules that run in taint mode break if we leave ### our code ref in perl5opt ### XXX CPANPLUS::inc functionality is now obsolete. #local $ENV{PERL5OPT} = CPANPLUS::inc->original_perl5opt || ''; ### you can turn off running this verbose by changing ### the config setting below, although it is really not ### recommended my $run_verbose = $verbose || $conf->get_conf('allow_build_interactivity') || 0; ### XXX need to add makeflags here too? ### yes, but they should really be split out -- see bug #4143 if( scalar run( command => [$make, 'test', @makeflags], buffer => \$captured, verbose => $run_verbose, ) ) { ### tests might pass because it doesn't have any tests defined ### log this occasion non-verbosely, so our test reporter can ### pick up on this if ( NO_TESTS_DEFINED->( $captured ) ) { msg( NO_TESTS_DEFINED->( $captured ), 0 ) } else { msg( loc( "MAKE TEST passed: %1", $captured ), 0 ); } if ( $conf->get_conf('cpantest') ) { $status->{stage} = 'test'; $status->{capture} = $captured; } $dist->status->test(1); } else { error( loc( "MAKE TEST failed: %1", $captured ), ( $run_verbose ? 0 : 1 ) ); if ( $conf->get_conf('cpantest') ) { $status->{stage} = 'test'; $status->{capture} = $captured; } ### send out error report here? or do so at a higher level? ### --higher level --kane. $dist->status->test(0); ### mark specifically *test* failure.. so we dont ### send success on force... $test_fail++; if( !$force and !$cb->_callbacks->proceed_on_test_failure->( $self, $captured ) ) { $fail++; last RUN; } } } } #</RUN> unless( $cb->_chdir( dir => $orig ) ) { error( loc( "Could not chdir back to start dir '%1'", $orig ) ); } ### TODO: Add $stage to _send_report() ### send out test report? ### only do so if the failure is this module, not its prereq if( $conf->get_conf('cpantest') and not $prereq_fail) { $cb->_send_report( module => $self, failed => $test_fail || $fail, buffer => CPANPLUS::Error->stack_as_string, status => $status, verbose => $verbose, force => $force, ) or error(loc("Failed to send test report for '%1'", $self->module ) ); } return $dist->status->created( $fail ? 0 : 1); } =pod =head2 $bool = $dist->install([make => '/path/to/make', makemakerflags => 'EXTRA=FLAGS', force => BOOL, verbose => BOOL]) C<install> runs the following command: make install Returns true on success, false on failure. =cut sub install { ### just in case you did the create with ANOTHER dist object linked ### to the same module object my $dist = shift(); my $self = $dist->parent; $dist = $self->status->dist_cpan if $self->status->dist_cpan; my $cb = $self->parent; my $conf = $cb->configure_object; my %hash = @_; unless( $dist->status->created ) { error(loc("You have not successfully created a '%2' distribution yet " . "-- cannot install yet", __PACKAGE__ )); return; } my $dir; unless( $dir = $self->status->extract ) { error( loc( "No dir found to operate on!" ) ); return; } my $args; my($force,$verbose,$make,$makeflags); { local $Params::Check::ALLOW_UNKNOWN = 1; my $tmpl = { force => { default => $conf->get_conf('force'), store => \$force }, verbose => { default => $conf->get_conf('verbose'), store => \$verbose }, make => { default => $conf->get_program('make'), store => \$make }, makeflags => { default => $conf->get_conf('makeflags'), store => \$makeflags }, }; $args = check( $tmpl, \%hash ) or return; } ### value set and false -- means failure ### if( defined $self->status->installed && !$self->status->installed && !$force ) { error( loc( "Module '%1' has failed to install before this session " . "-- aborting install", $self->module ) ); return; } my @makeflags = $dist->_split_like_shell( $makeflags ); $dist->status->_install_args( $args ); my $orig = cwd(); unless( $cb->_chdir( dir => $dir ) ) { error( loc( "Could not chdir to build directory '%1'", $dir ) ); return; } my $fail; my $captured; ### 'make install' section ### ### XXX need makeflags here too? ### yes, but they should really be split out.. see bug #4143 my $cmd = [$make, 'install', @makeflags]; my $sudo = $conf->get_program('sudo'); unshift @$cmd, $sudo if $sudo and $>; $cb->flush('lib'); unless(scalar run( command => $cmd, verbose => $verbose, buffer => \$captured, ) ) { error( loc( "MAKE INSTALL failed: %1 %2", $!, $captured ) ); $fail++; } ### put the output on the stack, don't print it msg( $captured, 0 ); unless( $cb->_chdir( dir => $orig ) ) { error( loc( "Could not chdir back to start dir '%1'", $orig ) ); } return $dist->status->installed( $fail ? 0 : 1 ); } =pod =head2 $bool = $dist->write_makefile_pl([force => BOOL, verbose => BOOL]) This routine can write a C<Makefile.PL> from the information in a module object. It is used to write a C<Makefile.PL> when the original author forgot it (!!). Returns 1 on success and false on failure. The file gets written to the directory the module's been extracted to. =cut sub write_makefile_pl { ### just in case you already did a call for this module object ### just via a different dist object my $dist = shift; my $self = $dist->parent; $dist = $self->status->dist_cpan if $self->status->dist_cpan; $self->status->dist_cpan( $dist ) unless $self->status->dist_cpan; my $cb = $self->parent; my $conf = $cb->configure_object; my %hash = @_; my $dir; unless( $dir = $self->status->extract ) { error( loc( "No dir found to operate on!" ) ); return; } my ($force, $verbose); my $tmpl = { force => { default => $conf->get_conf('force'), store => \$force }, verbose => { default => $conf->get_conf('verbose'), store => \$verbose }, }; my $args = check( $tmpl, \%hash ) or return; my $file = MAKEFILE_PL->($dir); if( -s $file && !$force ) { msg(loc("Already created '%1' - not doing so again without force", $file ), $verbose ); return 1; } ### due to a bug with AS perl 5.8.4 built 810 (and maybe others) ### opening files with content in them already does nasty things; ### seek to pos 0 and then print, but not truncating the file ### bug reported to activestate on 19 sep 2004: ### http://bugs.activestate.com/show_bug.cgi?id=34051 unlink $file if $force; my $fh = new FileHandle; unless( $fh->open( ">$file" ) ) { error( loc( "Could not create file '%1': %2", $file, $! ) ); return; } my $mf = MAKEFILE_PL->(); my $name = $self->module; my $version = $self->version; my $author = $self->author->author; my $href = $self->status->prereqs; my $prereqs = join ",\n", map { (' ' x 25) . "'$_'\t=> '$href->{$_}'" } keys %$href; $prereqs ||= ''; # just in case there are none; print $fh qq| ### Auto-generated $mf by CPANPLUS ### use ExtUtils::MakeMaker; WriteMakefile( NAME => '$name', VERSION => '$version', AUTHOR => '$author', PREREQ_PM => { $prereqs }, ); \n|; $fh->close; return 1; } sub dist_dir { ### just in case you already did a call for this module object ### just via a different dist object my $dist = shift; my $self = $dist->parent; $dist = $self->status->dist_cpan if $self->status->dist_cpan; $self->status->dist_cpan( $dist ) unless $self->status->dist_cpan; my $cb = $self->parent; my $conf = $cb->configure_object; my %hash = @_; my $make; my $verbose; { local $Params::Check::ALLOW_UNKNOWN = 1; my $tmpl = { make => { default => $conf->get_program('make'), store => \$make }, verbose => { default => $conf->get_conf('verbose'), store => \$verbose }, }; check( $tmpl, \%hash ) or return; } my $dir; unless( $dir = $self->status->extract ) { error( loc( "No dir found to operate on!" ) ); return; } ### chdir to work directory ### my $orig = cwd(); unless( $cb->_chdir( dir => $dir ) ) { error( loc( "Could not chdir to build directory '%1'", $dir ) ); return; } my $fail; my $distdir; TRY: { $dist->prepare( @_ ) or (++$fail, last TRY); my $captured; unless(scalar run( command => [$make, 'distdir'], buffer => \$captured, verbose => $verbose ) ) { error( loc( "MAKE DISTDIR failed: %1 %2", $!, $captured ) ); ++$fail, last TRY; } ### /path/to/Foo-Bar-1.2/Foo-Bar-1.2 $distdir = File::Spec->catdir( $dir, $self->package_name . '-' . $self->package_version ); unless( -d $distdir ) { error(loc("Do not know where '%1' got created", 'distdir')); ++$fail, last TRY; } } unless( $cb->_chdir( dir => $orig ) ) { error( loc( "Could not chdir to start directory '%1'", $orig ) ); return; } return if $fail; return $distdir; } sub _split_like_shell { my ($self, $string) = @_; return () unless defined($string); return @$string if ref $string eq 'ARRAY'; $string =~ s/^\s+|\s+$//g; return () unless length($string); require Text::ParseWords; return Text::ParseWords::shellwords($string); } 1; # Local variables: # c-indentation-style: bsd # c-basic-offset: 4 # indent-tabs-mode: nil # End: # vim: expandtab shiftwidth=4:
Bjay1435/capstone
rootfs/usr/share/perl/5.18.2/CPANPLUS/Dist/MM.pm
Perl
mit
34,382
# 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 Apache::TestUtil; use strict; use warnings FATAL => 'all'; use File::Find (); use File::Path (); use Exporter (); use Carp (); use Config; use File::Basename qw(dirname); use File::Spec::Functions qw(catfile catdir file_name_is_absolute tmpdir); use Symbol (); use Fcntl qw(SEEK_END); use Apache::Test (); use Apache::TestConfig (); use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %CLEAN); $VERSION = '0.02'; @ISA = qw(Exporter); @EXPORT = qw(t_cmp t_debug t_append_file t_write_file t_open_file t_mkdir t_rmtree t_is_equal t_filepath_cmp t_write_test_lib t_server_log_error_is_expected t_server_log_warn_is_expected t_client_log_error_is_expected t_client_log_warn_is_expected ); @EXPORT_OK = qw(t_write_perl_script t_write_shell_script t_chown t_catfile_apache t_catfile t_file_watch_for t_start_error_log_watch t_finish_error_log_watch t_start_file_watch t_read_file_watch t_finish_file_watch); %CLEAN = (); $Apache::TestUtil::DEBUG_OUTPUT = \*STDOUT; # 5.005's Data::Dumper has problems to dump certain datastructures use constant HAS_DUMPER => eval { $] >= 5.6 && require Data::Dumper; }; use constant INDENT => 4; { my %files; sub t_start_file_watch (;$) { my $name = defined $_[0] ? $_[0] : 'error_log'; $name = File::Spec->catfile(Apache::Test::vars->{t_logs}, $name) unless (File::Spec->file_name_is_absolute($name)); if (open my $fh, '<', $name) { seek $fh, 0, SEEK_END; $files{$name} = $fh; } else { delete $files{$name}; } return; } sub t_finish_file_watch (;$) { my $name = defined $_[0] ? $_[0] : 'error_log'; $name = File::Spec->catfile(Apache::Test::vars->{t_logs}, $name) unless (File::Spec->file_name_is_absolute($name)); my $fh = delete $files{$name}; unless (defined $fh) { open $fh, '<', $name or return; return readline $fh; } return readline $fh; } sub t_read_file_watch (;$) { my $name = defined $_[0] ? $_[0] : 'error_log'; $name = File::Spec->catfile(Apache::Test::vars->{t_logs}, $name) unless (File::Spec->file_name_is_absolute($name)); my $fh = $files{$name}; unless (defined $fh) { open $fh, '<', $name or return; $files{$name} = $fh; } return readline $fh; } sub t_file_watch_for ($$$) { my ($name, $re, $timeout) = @_; local $/ = "\n"; $re = qr/$re/ unless ref $re; $timeout *= 10; my $buf = ''; my @acc; while ($timeout >= 0) { my $line = t_read_file_watch $name; unless (defined $line) { # EOF select undef, undef, undef, 0.1; $timeout--; next; } $buf .= $line; next unless $buf =~ /\n$/; # incomplete line # found a complete line $line = $buf; $buf = ''; push @acc, $line; return wantarray ? @acc : $line if $line =~ $re; } return; } sub t_start_error_log_watch { t_start_file_watch; } sub t_finish_error_log_watch { local $/ = "\n"; return my @lines = t_finish_file_watch; } } # because of the prototype and recursive call to itself a forward # declaration is needed sub t_is_equal ($$); # compare any two datastructures (must pass references for non-scalars) # undef()'s are valid args sub t_is_equal ($$) { my ($a, $b) = @_; return 0 unless @_ == 2; # this was added in Apache::Test::VERSION 1.12 - remove deprecated # logic sometime around 1.15 or mid September, 2004. if (UNIVERSAL::isa($a, 'Regexp')) { my @warning = ("WARNING!!! t_is_equal() argument order has changed.", "use of a regular expression as the first argument", "is deprecated. support will be removed soon."); t_debug(@warning); ($a, $b) = ($b, $a); } if (defined $a && defined $b) { my $ref_a = ref $a; my $ref_b = ref $b; if (!$ref_a && !$ref_b) { return $a eq $b; } elsif ($ref_a eq 'ARRAY' && $ref_b eq 'ARRAY') { return 0 unless @$a == @$b; for my $i (0..$#$a) { t_is_equal($a->[$i], $b->[$i]) || return 0; } } elsif ($ref_a eq 'HASH' && $ref_b eq 'HASH') { return 0 unless (keys %$a) == (keys %$b); for my $key (sort keys %$a) { return 0 unless exists $b->{$key}; t_is_equal($a->{$key}, $b->{$key}) || return 0; } } elsif ($ref_b eq 'Regexp') { return $a =~ $b; } else { # try to compare the references return $a eq $b; } } else { # undef == undef! a valid test return (defined $a || defined $b) ? 0 : 1; } return 1; } sub t_cmp ($$;$) { Carp::carp(join(":", (caller)[1..2]) . ' usage: $res = t_cmp($received, $expected, [$comment])') if @_ < 2 || @_ > 3; my ($received, $expected) = @_; # this was added in Apache::Test::VERSION 1.12 - remove deprecated # logic sometime around 1.15 or mid September, 2004. if (UNIVERSAL::isa($_[0], 'Regexp')) { my @warning = ("WARNING!!! t_cmp() argument order has changed.", "use of a regular expression as the first argument", "is deprecated. support will be removed soon."); t_debug(@warning); ($received, $expected) = ($expected, $received); } t_debug("testing : " . pop) if @_ == 3; t_debug("expected: " . struct_as_string(0, $expected)); t_debug("received: " . struct_as_string(0, $received)); return t_is_equal($received, $expected); } # Essentially t_cmp, but on Win32, first converts pathnames # to their DOS long name. sub t_filepath_cmp ($$;$) { my @a = (shift, shift); if (Apache::TestConfig::WIN32) { $a[0] = Win32::GetLongPathName($a[0]) if defined $a[0]; $a[1] = Win32::GetLongPathName($a[1]) if defined $a[1]; } return @_ == 1 ? t_cmp($a[0], $a[1], $_[0]) : t_cmp($a[0], $a[1]); } *expand = HAS_DUMPER ? sub { map { ref $_ ? Data::Dumper::Dumper($_) : $_ } @_ } : sub { @_ }; sub t_debug { my $out = $Apache::TestUtil::DEBUG_OUTPUT; print $out map {"# $_\n"} map {split /\n/} grep {defined} expand(@_); } sub t_open_file { my $file = shift; die "must pass a filename" unless defined $file; # create the parent dir if it doesn't exist yet makepath(dirname $file); my $fh = Symbol::gensym(); open $fh, ">$file" or die "can't open $file: $!"; t_debug("writing file: $file"); $CLEAN{files}{$file}++; return $fh; } sub _temp_package_dir { return catdir(tmpdir(), 'apache_test'); } sub t_write_test_lib { my $file = shift; die "must pass a filename" unless defined $file; t_write_file(catdir(_temp_package_dir(), $file), @_); } sub t_write_file { my $file = shift; die "must pass a filename" unless defined $file; # create the parent dir if it doesn't exist yet makepath(dirname $file); my $fh = Symbol::gensym(); open $fh, ">$file" or die "can't open $file: $!"; t_debug("writing file: $file"); print $fh join '', @_ if @_; close $fh; $CLEAN{files}{$file}++; } sub t_append_file { my $file = shift; die "must pass a filename" unless defined $file; # create the parent dir if it doesn't exist yet makepath(dirname $file); # add to the cleanup list only if we created it now $CLEAN{files}{$file}++ unless -e $file; my $fh = Symbol::gensym(); open $fh, ">>$file" or die "can't open $file: $!"; print $fh join '', @_ if @_; close $fh; } sub t_write_shell_script { my $file = shift; my $code = join '', @_; my($ext, $shebang); if (Apache::TestConfig::WIN32()) { $code =~ s/echo$/echo./mg; #required to echo newline $ext = 'bat'; $shebang = "\@echo off\nREM this is a bat"; } else { $ext = 'sh'; $shebang = '#!/bin/sh'; } $file .= ".$ext"; t_write_file($file, "$shebang\n", $code); $ext; } sub t_write_perl_script { my $file = shift; my $shebang = "#!$Config{perlpath}\n"; my $warning = Apache::TestConfig->thaw->genwarning($file); t_write_file($file, $shebang, $warning, @_); chmod 0755, $file; } sub t_mkdir { my $dir = shift; makepath($dir); } # returns a list of dirs successfully created sub makepath { my($path) = @_; return if !defined($path) || -e $path; my $full_path = $path; # remember which dirs were created and should be cleaned up while (1) { $CLEAN{dirs}{$path} = 1; $path = dirname $path; last if -e $path; } return File::Path::mkpath($full_path, 0, 0755); } sub t_rmtree { die "must pass a dirname" unless defined $_[0]; File::Path::rmtree((@_ > 1 ? \@_ : $_[0]), 0, 1); } #chown a file or directory to the test User/Group #noop if chown is unsupported sub t_chown { my $file = shift; my $config = Apache::Test::config(); my($uid, $gid); eval { #XXX cache this lookup ($uid, $gid) = (getpwnam($config->{vars}->{user}))[2,3]; }; if ($@) { if ($@ =~ /^The getpwnam function is unimplemented/) { #ok if unsupported, e.g. win32 return 1; } else { die $@; } } CORE::chown($uid, $gid, $file) || die "chown $file: $!"; } # $string = struct_as_string($indent_level, $var); # # return any nested datastructure via Data::Dumper or ala Data::Dumper # as a string. undef() is a valid arg. # # $indent_level should be 0 (used for nice indentation during # recursive datastructure traversal) sub struct_as_string{ return "???" unless @_ == 2; my $level = shift; return "undef" unless defined $_[0]; my $pad = ' ' x (($level + 1) * INDENT); my $spad = ' ' x ($level * INDENT); if (HAS_DUMPER) { local $Data::Dumper::Terse = 1; $Data::Dumper::Terse = $Data::Dumper::Terse; # warn my $data = Data::Dumper::Dumper(@_); $data =~ s/\n$//; # \n is handled by the caller return $data; } else { if (ref($_[0]) eq 'ARRAY') { my @data = (); for my $i (0..$#{ $_[0] }) { push @data, struct_as_string($level+1, $_[0]->[$i]); } return join "\n", "[", map({"$pad$_,"} @data), "$spad\]"; } elsif ( ref($_[0])eq 'HASH') { my @data = (); for my $key (keys %{ $_[0] }) { push @data, "$key => " . struct_as_string($level+1, $_[0]->{$key}); } return join "\n", "{", map({"$pad$_,"} @data), "$spad\}"; } else { return $_[0]; } } } my $banner_format = "\n*** The following %s expected and harmless ***\n"; sub is_expected_banner { my $type = shift; my $count = @_ ? shift : 1; sprintf $banner_format, $count == 1 ? "$type entry is" : "$count $type entries are"; } sub t_server_log_is_expected { print STDERR is_expected_banner(@_); } sub t_client_log_is_expected { my $vars = Apache::Test::config()->{vars}; my $log_file = catfile $vars->{serverroot}, "logs", "error_log"; my $fh = Symbol::gensym(); open $fh, ">>$log_file" or die "Can't open $log_file: $!"; my $oldfh = select($fh); $| = 1; select($oldfh); print $fh is_expected_banner(@_); close $fh; } sub t_server_log_error_is_expected { t_server_log_is_expected("error", @_);} sub t_server_log_warn_is_expected { t_server_log_is_expected("warn", @_); } sub t_client_log_error_is_expected { t_client_log_is_expected("error", @_);} sub t_client_log_warn_is_expected { t_client_log_is_expected("warn", @_); } END { # remove files that were created via this package for (grep {-e $_ && -f _ } keys %{ $CLEAN{files} } ) { t_debug("removing file: $_"); unlink $_; } # remove dirs that were created via this package for (grep {-e $_ && -d _ } keys %{ $CLEAN{dirs} } ) { t_debug("removing dir tree: $_"); t_rmtree($_); } } # essentially File::Spec->catfile, but on Win32 # returns the long path name, if the file is absolute sub t_catfile { my $f = catfile(@_); return $f unless file_name_is_absolute($f); return Apache::TestConfig::WIN32 ? Win32::GetLongPathName($f) : $f; } # Apache uses a Unix-style specification for files, with # forward slashes for directory separators. This is # essentially File::Spec::Unix->catfile, but on Win32 # returns the long path name, if the file is absolute sub t_catfile_apache { my $f = File::Spec::Unix->catfile(@_); return $f unless file_name_is_absolute($f); return Apache::TestConfig::WIN32 ? Win32::GetLongPathName($f) : $f; } 1; __END__ =encoding utf8 =head1 NAME Apache::TestUtil - Utility functions for writing tests =head1 SYNOPSIS use Apache::Test; use Apache::TestUtil; ok t_cmp("foo", "foo", "sanity check"); t_write_file("filename", @content); my $fh = t_open_file($filename); t_mkdir("/foo/bar"); t_rmtree("/foo/bar"); t_is_equal($a, $b); =head1 DESCRIPTION C<Apache::TestUtil> automatically exports a number of functions useful in writing tests. All the files and directories created using the functions from this package will be automatically destroyed at the end of the program execution (via END block). You should not use these functions other than from within tests which should cleanup all the created directories and files at the end of the test. =head1 FUNCTIONS =over =item t_cmp() t_cmp($received, $expected, $comment); t_cmp() prints the values of I<$comment>, I<$expected> and I<$received>. e.g.: t_cmp(1, 1, "1 == 1?"); prints: # testing : 1 == 1? # expected: 1 # received: 1 then it returns the result of comparison of the I<$expected> and the I<$received> variables. Usually, the return value of this function is fed directly to the ok() function, like this: ok t_cmp(1, 1, "1 == 1?"); the third argument (I<$comment>) is optional, mostly useful for telling what the comparison is trying to do. It is valid to use C<undef> as an expected value. Therefore: my $foo; t_cmp(undef, $foo, "undef == undef?"); will return a I<true> value. You can compare any two data-structures with t_cmp(). Just make sure that if you pass non-scalars, you have to pass their references. The datastructures can be deeply nested. For example you can compare: t_cmp({1 => [2..3,{5..8}], 4 => [5..6]}, {1 => [2..3,{5..8}], 4 => [5..6]}, "hash of array of hashes"); You can also compare the second argument against the first as a regex. Use the C<qr//> function in the second argument. For example: t_cmp("abcd", qr/^abc/, "regex compare"); will do: "abcd" =~ /^abc/; This function is exported by default. =item t_filepath_cmp() This function is used to compare two filepaths via t_cmp(). For non-Win32, it simply uses t_cmp() for the comparison, but for Win32, Win32::GetLongPathName() is invoked to convert the first two arguments to their DOS long pathname. This is useful when there is a possibility the two paths being compared are not both represented by their long or short pathname. This function is exported by default. =item t_debug() t_debug("testing feature foo"); t_debug("test", [1..3], 5, {a=>[1..5]}); t_debug() prints out any datastructure while prepending C<#> at the beginning of each line, to make the debug printouts comply with C<Test::Harness>'s requirements. This function should be always used for debug prints, since if in the future the debug printing will change (e.g. redirected into a file) your tests won't need to be changed. the special global variable $Apache::TestUtil::DEBUG_OUTPUT can be used to redirect the output from t_debug() and related calls such as t_write_file(). for example, from a server-side test you would probably need to redirect it to STDERR: sub handler { plan $r, tests => 1; local $Apache::TestUtil::DEBUG_OUTPUT = \*STDERR; t_write_file('/tmp/foo', 'bar'); ... } left to its own devices, t_debug() will collide with the standard HTTP protocol during server-side tests, resulting in a situation both confusing difficult to debug. but STDOUT is left as the default, since you probably don't want debug output under normal circumstances unless running under verbose mode. This function is exported by default. =item t_write_test_lib() t_write_test_lib($filename, @lines) t_write_test_lib() creates a new file at I<$filename> or overwrites the existing file with the content passed in I<@lines>. The file is created in a temporary directory which is added to @INC at test configuration time. It is intended to be used for creating temporary packages for testing which can be modified at run time, see the Apache::Reload unit tests for an example. =item t_write_file() t_write_file($filename, @lines); t_write_file() creates a new file at I<$filename> or overwrites the existing file with the content passed in I<@lines>. If only the I<$filename> is passed, an empty file will be created. If parent directories of C<$filename> don't exist they will be automagically created. The generated file will be automatically deleted at the end of the program's execution. This function is exported by default. =item t_append_file() t_append_file($filename, @lines); t_append_file() is similar to t_write_file(), but it doesn't clobber existing files and appends C<@lines> to the end of the file. If the file doesn't exist it will create it. If parent directories of C<$filename> don't exist they will be automagically created. The generated file will be registered to be automatically deleted at the end of the program's execution, only if the file was created by t_append_file(). This function is exported by default. =item t_write_shell_script() Apache::TestUtil::t_write_shell_script($filename, @lines); Similar to t_write_file() but creates a portable shell/batch script. The created filename is constructed from C<$filename> and an appropriate extension automatically selected according to the platform the code is running under. It returns the extension of the created file. =item t_write_perl_script() Apache::TestUtil::t_write_perl_script($filename, @lines); Similar to t_write_file() but creates a executable Perl script with correctly set shebang line. =item t_open_file() my $fh = t_open_file($filename); t_open_file() opens a file I<$filename> for writing and returns the file handle to the opened file. If parent directories of C<$filename> don't exist they will be automagically created. The generated file will be automatically deleted at the end of the program's execution. This function is exported by default. =item t_mkdir() t_mkdir($dirname); t_mkdir() creates a directory I<$dirname>. The operation will fail if the parent directory doesn't exist. If parent directories of C<$dirname> don't exist they will be automagically created. The generated directory will be automatically deleted at the end of the program's execution. This function is exported by default. =item t_rmtree() t_rmtree(@dirs); t_rmtree() deletes the whole directories trees passed in I<@dirs>. This function is exported by default. =item t_chown() Apache::TestUtil::t_chown($file); Change ownership of $file to the test's I<User>/I<Group>. This function is noop on platforms where chown(2) is unsupported (e.g. Win32). =item t_is_equal() t_is_equal($a, $b); t_is_equal() compares any two datastructures and returns 1 if they are exactly the same, otherwise 0. The datastructures can be nested hashes, arrays, scalars, undefs or a combination of any of these. See t_cmp() for an example. If C<$b> is a regex reference, the regex comparison C<$a =~ $b> is performed. For example: t_is_equal($server_version, qr{^Apache}); If comparing non-scalars make sure to pass the references to the datastructures. This function is exported by default. =item t_server_log_error_is_expected() If the handler's execution results in an error or a warning logged to the I<error_log> file which is expected, it's a good idea to have a disclaimer printed before the error itself, so one can tell real problems with tests from expected errors. For example when testing how the package behaves under error conditions the I<error_log> file might be loaded with errors, most of which are expected. For example if a handler is about to generate a run-time error, this function can be used as: use Apache::TestUtil; ... sub handler { my $r = shift; ... t_server_log_error_is_expected(); die "failed because ..."; } After running this handler the I<error_log> file will include: *** The following error entry is expected and harmless *** [Tue Apr 01 14:00:21 2003] [error] failed because ... When more than one entry is expected, an optional numerical argument, indicating how many entries to expect, can be passed. For example: t_server_log_error_is_expected(2); will generate: *** The following 2 error entries are expected and harmless *** If the error is generated at compile time, the logging must be done in the BEGIN block at the very beginning of the file: BEGIN { use Apache::TestUtil; t_server_log_error_is_expected(); } use DOES_NOT_exist; After attempting to run this handler the I<error_log> file will include: *** The following error entry is expected and harmless *** [Tue Apr 01 14:04:49 2003] [error] Can't locate "DOES_NOT_exist.pm" in @INC (@INC contains: ... Also see C<t_server_log_warn_is_expected()> which is similar but used for warnings. This function is exported by default. =item t_server_log_warn_is_expected() C<t_server_log_warn_is_expected()> generates a disclaimer for expected warnings. See the explanation for C<t_server_log_error_is_expected()> for more details. This function is exported by default. =item t_client_log_error_is_expected() C<t_client_log_error_is_expected()> generates a disclaimer for expected errors. But in contrast to C<t_server_log_error_is_expected()> called by the client side of the script. See the explanation for C<t_server_log_error_is_expected()> for more details. For example the following client script fails to find the handler: use Apache::Test; use Apache::TestUtil; use Apache::TestRequest qw(GET); plan tests => 1; t_client_log_error_is_expected(); my $url = "/error_document/cannot_be_found"; my $res = GET($url); ok t_cmp(404, $res->code, "test 404"); After running this test the I<error_log> file will include an entry similar to the following snippet: *** The following error entry is expected and harmless *** [Tue Apr 01 14:02:55 2003] [error] [client 127.0.0.1] File does not exist: /tmp/test/t/htdocs/error When more than one entry is expected, an optional numerical argument, indicating how many entries to expect, can be passed. For example: t_client_log_error_is_expected(2); will generate: *** The following 2 error entries are expected and harmless *** This function is exported by default. =item t_client_log_warn_is_expected() C<t_client_log_warn_is_expected()> generates a disclaimer for expected warnings on the client side. See the explanation for C<t_client_log_error_is_expected()> for more details. This function is exported by default. =item t_catfile('a', 'b', 'c') This function is essentially C<File::Spec-E<gt>catfile>, but on Win32 will use C<Win32::GetLongpathName()> to convert the result to a long path name (if the result is an absolute file). The function is not exported by default. =item t_catfile_apache('a', 'b', 'c') This function is essentially C<File::Spec::Unix-E<gt>catfile>, but on Win32 will use C<Win32::GetLongpathName()> to convert the result to a long path name (if the result is an absolute file). It is useful when comparing something to that returned by Apache, which uses a Unix-style specification with forward slashes for directory separators. The function is not exported by default. =item t_start_error_log_watch(), t_finish_error_log_watch() This pair of functions provides an easy interface for checking the presence or absense of any particular message or messages in the httpd error_log that were generated by the httpd daemon as part of a test suite. It is likely, that you should proceed this with a call to one of the t_*_is_expected() functions. t_start_error_log_watch(); do_it; ok grep {...} t_finish_error_log_watch(); Another usage case could be a handler that emits some debugging messages to the error_log. Now, if this handler is called in a series of other test cases it can be hard to find the relevant messages manually. In such cases the following sequence in the test file may help: t_start_error_log_watch(); GET '/this/or/that'; t_debug t_finish_error_log_watch(); =item t_start_file_watch() Apache::TestUtil::t_start_file_watch('access_log'); This function is similar to C<t_start_error_log_watch()> but allows for other files than C<error_log> to be watched. It opens the given file and positions the file pointer at its end. Subsequent calls to C<t_read_file_watch()> or C<t_finish_file_watch()> will read lines that have been appended after this call. A file name can be passed as parameter. If omitted or undefined the C<error_log> is opened. Relative file name are evaluated relative to the directory containing C<error_log>. If the specified file does not exist (yet) no error is returned. It is assumed that it will appear soon. In this case C<t_{read,finish}_file_watch()> will open the file silently and read from the beginning. =item t_read_file_watch(), t_finish_file_watch() local $/ = "\n"; $line1=Apache::TestUtil::t_read_file_watch('access_log'); $line2=Apache::TestUtil::t_read_file_watch('access_log'); @lines=Apache::TestUtil::t_finish_file_watch('access_log'); This pair of functions reads the file opened by C<t_start_error_log_watch()>. As does the core C<readline> function, they return one line if called in scalar context, otherwise all lines until end of file. Before calling C<readline> these functions do not set C<$/> as does C<t_finish_error_log_watch>. So, if the file has for example a fixed record length use this: { local $/=\$record_length; @lines=t_finish_file_watch($name); } =item t_file_watch_for() @lines=Apache::TestUtil::t_file_watch_for('access_log', qr/condition/, $timeout); This function reads the file from the current position and looks for the first line that matches C<qr/condition/>. If no such line could be found until end of file the function pauses and retries until either such a line is found or the timeout (in seconds) is reached. In scalar or void context only the matching line is returned. In list context all read lines are returned with the matching one in last position. The function uses C<\n> and end-of-line marker and waits for complete lines. The timeout although it can be specified with sub-second precision is not very accurate. It is simply multiplied by 10. The result is used as a maximum loop count. For the intented purpose this should be good enough. Use this function to check for logfile entries when you cannot be sure that they are already written when the test program reaches the point, for example to check for messages that are written in a PerlCleanupHandler or a PerlLogHandler. ok t_file_watch_for 'access_log', qr/expected log entry/, 2; This call reads the C<access_log> and waits for maximum 2 seconds for the expected entry to appear. =back =head1 AUTHOR Stas Bekman <stas@stason.org>, Torsten Förtsch <torsten.foertsch@gmx.net> =head1 SEE ALSO perl(1) =cut
Distrotech/mod_perl
Apache-Test/lib/Apache/TestUtil.pm
Perl
apache-2.0
28,948
# Copyright (C) 2003, 2004, 2006, 2007 Free Software Foundation, Inc. # 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, 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 General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. package Automake::Rule; use strict; use Carp; use Automake::Item; use Automake::RuleDef; use Automake::ChannelDefs; use Automake::Channels; use Automake::Options; use Automake::Condition qw (TRUE FALSE); use Automake::DisjConditions; require Exporter; use vars '@ISA', '@EXPORT', '@EXPORT_OK'; @ISA = qw/Automake::Item Exporter/; @EXPORT = qw (reset register_suffix_rule suffix_rules_count suffixes rules $suffix_rules $KNOWN_EXTENSIONS_PATTERN depend %dependencies %actions accept_extensions reject_rule msg_rule msg_cond_rule err_rule err_cond_rule rule rrule ruledef rruledef); =head1 NAME Automake::Rule - support for rules definitions =head1 SYNOPSIS use Automake::Rule; use Automake::RuleDef; =head1 DESCRIPTION This package provides support for Makefile rule definitions. An C<Automake::Rule> is a rule name associated to possibly many conditional definitions. These definitions are instances of C<Automake::RuleDef>. Therefore obtaining the value of a rule under a given condition involves two lookups. One to look up the rule, and one to look up the conditional definition: my $rule = rule $name; if ($rule) { my $def = $rule->def ($cond); if ($def) { return $def->location; } ... } ... when it is known that the rule and the definition being looked up exist, the above can be simplified to return rule ($name)->def ($cond)->location; # do not write this. but is better written return rrule ($name)->rrule ($cond)->location; or even return rruledef ($name, $cond)->location; The I<r> variants of the C<rule>, C<def>, and C<ruledef> methods add an extra test to ensure that the lookup succeeded, and will diagnose failures as internal errors (with a message which is much more informative than Perl's warning about calling a method on a non-object). =head2 Global variables =over 4 =cut my $_SUFFIX_RULE_PATTERN = '^(\.[a-zA-Z0-9_(){}$+@\-]+)(\.[a-zA-Z0-9_(){}$+@\-]+)' . "\$"; # Suffixes found during a run. use vars '@_suffixes'; # Same as $suffix_rules (declared below), but records only the # default rules supplied by the languages Automake supports. use vars '$_suffix_rules_default'; =item C<%dependencies> Holds the dependencies of targets which dependencies are factored. Typically, C<.PHONY> will appear in plenty of F<*.am> files, but must be output once. Arguably all pure dependencies could be subject to this factorization, but it is not unpleasant to have paragraphs in Makefile: keeping related stuff altogether. =cut use vars '%dependencies'; =item <%actions> Holds the factored actions. Tied to C<%dependencies>, i.e., filled only when keys exists in C<%dependencies>. =cut use vars '%actions'; =item <$suffix_rules> This maps the source extension for all suffix rule seen to a C<hash> whose keys are the possible output extensions. Note that this is transitively closed by construction: if we have exists $suffix_rules{$ext1}{$ext2} && exists $suffix_rules{$ext2}{$ext3} then we also have exists $suffix_rules{$ext1}{$ext3} So it's easy to check whether C<.foo> can be transformed to C<.$(OBJEXT)> by checking whether C<$suffix_rules{'.foo'}{'.$(OBJEXT)'}> exists. This will work even if transforming C<.foo> to C<.$(OBJEXT)> involves a chain of several suffix rules. The value of C<$suffix_rules{$ext1}{$ext2}> is a pair C<[ $next_sfx, $dist ]> where C<$next_sfx> is target suffix for the next rule to use to reach C<$ext2>, and C<$dist> the distance to C<$ext2'>. The content of this variable should be updated via the C<register_suffix_rule> function. =cut use vars '$suffix_rules'; =item C<$KNOWN_EXTENSIONS_PATTERN> Pattern that matches all know input extensions (i.e. extensions used by the languages supported by Automake). Using this pattern (instead of `\..*$') to match extensions allows Automake to support dot-less extensions. New extensions should be registered with C<accept_extensions>. =cut use vars qw ($KNOWN_EXTENSIONS_PATTERN @_known_extensions_list); $KNOWN_EXTENSIONS_PATTERN = ""; @_known_extensions_list = (); =back =head2 Error reporting functions In these functions, C<$rule> can be either a rule name, or an instance of C<Automake::Rule>. =over 4 =item C<err_rule ($rule, $message, [%options])> Uncategorized errors about rules. =cut sub err_rule ($$;%) { msg_rule ('error', @_); } =item C<err_cond_rule ($cond, $rule, $message, [%options])> Uncategorized errors about conditional rules. =cut sub err_cond_rule ($$$;%) { msg_cond_rule ('error', @_); } =item C<msg_cond_rule ($channel, $cond, $rule, $message, [%options])> Messages about conditional rules. =cut sub msg_cond_rule ($$$$;%) { my ($channel, $cond, $rule, $msg, %opts) = @_; my $r = ref ($rule) ? $rule : rrule ($rule); msg $channel, $r->rdef ($cond)->location, $msg, %opts; } =item C<msg_rule ($channel, $targetname, $message, [%options])> Messages about rules. =cut sub msg_rule ($$$;%) { my ($channel, $rule, $msg, %opts) = @_; my $r = ref ($rule) ? $rule : rrule ($rule); # Don't know which condition is concerned. Pick any. my $cond = $r->conditions->one_cond; msg_cond_rule ($channel, $cond, $r, $msg, %opts); } =item C<$bool = reject_rule ($rule, $error_msg)> Bail out with C<$error_msg> if a rule with name C<$rule> has been defined. Return true iff C<$rule> is defined. =cut sub reject_rule ($$) { my ($rule, $msg) = @_; if (rule ($rule)) { err_rule $rule, $msg; return 1; } return 0; } =back =head2 Administrative functions =over 4 =item C<accept_extensions (@exts)> Update C<$KNOWN_EXTENSIONS_PATTERN> to recognize the extensions listed C<@exts>. Extensions should contain a dot if needed. =cut sub accept_extensions (@) { push @_known_extensions_list, @_; $KNOWN_EXTENSIONS_PATTERN = '(?:' . join ('|', map (quotemeta, @_known_extensions_list)) . ')'; } =item C<rules> Returns the list of all L<Automake::Rule> instances. (I.e., all rules defined so far.) =cut use vars '%_rule_dict'; sub rules () { return values %_rule_dict; } =item C<Automake::Rule::reset> The I<forget all> function. Clears all know rules and reset some other internal data. =cut sub reset() { %_rule_dict = (); @_suffixes = (); # The first time we initialize the variables, # we save the value of $suffix_rules. if (defined $_suffix_rules_default) { $suffix_rules = $_suffix_rules_default; } else { $_suffix_rules_default = $suffix_rules; } %dependencies = ( # Texinfoing. 'dvi' => [], 'dvi-am' => [], 'pdf' => [], 'pdf-am' => [], 'ps' => [], 'ps-am' => [], 'info' => [], 'info-am' => [], 'html' => [], 'html-am' => [], # Installing/uninstalling. 'install-data-am' => [], 'install-exec-am' => [], 'uninstall-am' => [], 'install-man' => [], 'uninstall-man' => [], 'install-dvi' => [], 'install-dvi-am' => [], 'install-html' => [], 'install-html-am' => [], 'install-info' => [], 'install-info-am' => [], 'install-pdf' => [], 'install-pdf-am' => [], 'install-ps' => [], 'install-ps-am' => [], 'installcheck-am' => [], # Cleaning. 'clean-am' => [], 'mostlyclean-am' => [], 'maintainer-clean-am' => [], 'distclean-am' => [], 'clean' => [], 'mostlyclean' => [], 'maintainer-clean' => [], 'distclean' => [], # Tarballing. 'dist-all' => [], # Phoning. '.PHONY' => [], # Recursive install targets (so `make -n install' works for BSD Make). '.MAKE' => [], ); %actions = (); } =item C<register_suffix_rule ($where, $src, $dest)> Register a suffix rules defined on C<$where> that transform files ending in C<$src> into files ending in C<$dest>. This upgrades the C<$suffix_rules> variables. =cut sub register_suffix_rule ($$$) { my ($where, $src, $dest) = @_; verb "Sources ending in $src become $dest"; push @_suffixes, $src, $dest; # When transforming sources to objects, Automake uses the # %suffix_rules to move from each source extension to # `.$(OBJEXT)', not to `.o' or `.obj'. However some people # define suffix rules for `.o' or `.obj', so internally we will # consider these extensions equivalent to `.$(OBJEXT)'. We # CANNOT rewrite the target (i.e., automagically replace `.o' # and `.obj' by `.$(OBJEXT)' in the output), or warn the user # that (s)he'd better use `.$(OBJEXT)', because Automake itself # output suffix rules for `.o' or `.obj'... $dest = '.$(OBJEXT)' if ($dest eq '.o' || $dest eq '.obj'); # Reading the comments near the declaration of $suffix_rules might # help to understand the update of $suffix_rules that follows... # Register $dest as a possible destination from $src. # We might have the create the \hash. if (exists $suffix_rules->{$src}) { $suffix_rules->{$src}{$dest} = [ $dest, 1 ]; } else { $suffix_rules->{$src} = { $dest => [ $dest, 1 ] }; } # If we know how to transform $dest in something else, then # we know how to transform $src in that "something else". if (exists $suffix_rules->{$dest}) { for my $dest2 (keys %{$suffix_rules->{$dest}}) { my $dist = $suffix_rules->{$dest}{$dest2}[1] + 1; # Overwrite an existing $src->$dest2 path only if # the path via $dest which is shorter. if (! exists $suffix_rules->{$src}{$dest2} || $suffix_rules->{$src}{$dest2}[1] > $dist) { $suffix_rules->{$src}{$dest2} = [ $dest, $dist ]; } } } # Similarly, any extension that can be derived into $src # can be derived into the same extensions as $src can. my @dest2 = keys %{$suffix_rules->{$src}}; for my $src2 (keys %$suffix_rules) { if (exists $suffix_rules->{$src2}{$src}) { for my $dest2 (@dest2) { my $dist = $suffix_rules->{$src}{$dest2} + 1; # Overwrite an existing $src2->$dest2 path only if # the path via $src is shorter. if (! exists $suffix_rules->{$src2}{$dest2} || $suffix_rules->{$src2}{$dest2}[1] > $dist) { $suffix_rules->{$src2}{$dest2} = [ $src, $dist ]; } } } } } =item C<$count = suffix_rules_count> Return the number of suffix rules added while processing the current F<Makefile> (excluding predefined suffix rules). =cut sub suffix_rules_count () { return (scalar keys %$suffix_rules) - (scalar keys %$_suffix_rules_default); } =item C<@list = suffixes> Return the list of known suffixes. =cut sub suffixes () { return @_suffixes; } =item C<rule ($rulename)> Return the C<Automake::Rule> object for the rule named C<$rulename> if defined. Return 0 otherwise. =cut sub rule ($) { my ($name) = @_; # Strip $(EXEEXT) from $name, so we can diagnose # a clash if `ctags$(EXEEXT):' is redefined after `ctags:'. $name =~ s,\$\(EXEEXT\)$,,; return $_rule_dict{$name} if exists $_rule_dict{$name}; return 0; } =item C<ruledef ($rulename, $cond)> Return the C<Automake::RuleDef> object for the rule named C<$rulename> if defined in condition C<$cond>. Return false if the condition or the rule does not exist. =cut sub ruledef ($$) { my ($name, $cond) = @_; my $rule = rule $name; return $rule && $rule->def ($cond); } =item C<rrule ($rulename) Return the C<Automake::Rule> object for the variable named C<$rulename>. Abort with an internal error if the variable was not defined. The I<r> in front of C<var> stands for I<required>. One should call C<rvar> to assert the rule's existence. =cut sub rrule ($) { my ($name) = @_; my $r = rule $name; prog_error ("undefined rule $name\n" . &rules_dump) unless $r; return $r; } =item C<rruledef ($varname, $cond)> Return the C<Automake::RuleDef> object for the rule named C<$rulename> if defined in condition C<$cond>. Abort with an internal error if the condition or the rule does not exist. =cut sub rruledef ($$) { my ($name, $cond) = @_; return rrule ($name)->rdef ($cond); } # Create the variable if it does not exist. # This is used only by other functions in this package. sub _crule ($) { my ($name) = @_; my $r = rule $name; return $r if $r; return _new Automake::Rule $name; } sub _new ($$) { my ($class, $name) = @_; # Strip $(EXEEXT) from $name, so we can diagnose # a clash if `ctags$(EXEEXT):' is redefined after `ctags:'. (my $keyname = $name) =~ s,\$\(EXEEXT\)$,,; my $self = Automake::Item::new ($class, $name); $_rule_dict{$keyname} = $self; return $self; } =item C<@conds = define ($rulename, $source, $owner, $cond, $where)> Define a new rule. C<$rulename> is the list of targets. C<$source> is the filename the rule comes from. C<$owner> is the owner of the rule (C<RULE_AUTOMAKE> or C<RULE_USER>). C<$cond> is the C<Automake::Condition> under which the rule is defined. C<$where> is the C<Automake::Location> where the rule is defined. Returns a (possibly empty) list of C<Automake::Condition>s where the rule's definition should be output. =cut sub define ($$$$$) { my ($target, $source, $owner, $cond, $where) = @_; prog_error "$where is not a reference" unless ref $where; prog_error "$cond is not a reference" unless ref $cond; # Don't even think about defining a rule in condition FALSE. return () if $cond == FALSE; # For now `foo:' will override `foo$(EXEEXT):'. This is temporary, # though, so we emit a warning. (my $noexe = $target) =~ s,\$\(EXEEXT\)$,,; my $noexerule = rule $noexe; my $tdef = $noexerule ? $noexerule->def ($cond) : undef; if ($noexe ne $target && $tdef && $noexerule->name ne $target) { # The no-exeext option enables this feature. if (! option 'no-exeext') { msg ('obsolete', $tdef->location, "deprecated feature: target `$noexe' overrides " . "`$noexe\$(EXEEXT)'\n" . "change your target to read `$noexe\$(EXEEXT)'"); msg ('obsolete', $where, "target `$target' was defined here"); } # Don't `return ()' now, as this might hide target clashes # detected below. } # A GNU make-style pattern rule has a single "%" in the target name. msg ('portability', $where, "`%'-style pattern rules are a GNU make extension") if $target =~ /^[^%]*%[^%]*$/; # Diagnose target redefinitions. if ($tdef) { my $oldowner = $tdef->owner; # Ok, it's the name target, but the name maybe different because # `foo$(EXEEXT)' and `foo' have the same key in our table. my $oldname = $tdef->name; # Don't mention true conditions in diagnostics. my $condmsg = $cond == TRUE ? '' : " in condition `" . $cond->human . "'"; if ($owner == RULE_USER) { if ($oldowner == RULE_USER) { # Ignore `%'-style pattern rules. We'd need the # dependencies to detect duplicates, and they are # already diagnosed as unportable by -Wportability. if ($target !~ /^[^%]*%[^%]*$/) { ## FIXME: Presently we can't diagnose duplicate user rules ## because we don't distinguish rules with commands ## from rules that only add dependencies. E.g., ## .PHONY: foo ## .PHONY: bar ## is legitimate. (This is phony.test.) # msg ('syntax', $where, # "redefinition of `$target'$condmsg...", partial => 1); # msg_cond_rule ('syntax', $cond, $target, # "... `$target' previously defined here"); } # Return so we don't redefine the rule in our tables, # don't check for ambiguous condition, etc. The rule # will be output anyway because &read_am_file ignore the # return code. return (); } else { # Since we parse the user Makefile.am before reading # the Automake fragments, this condition should never happen. prog_error ("user target `$target'$condmsg seen after Automake's" . " definition\nfrom " . $tdef->source); } } else # $owner == RULE_AUTOMAKE { if ($oldowner == RULE_USER) { # -am targets listed in %dependencies support a -local # variant. If the user tries to override TARGET or # TARGET-am for which there exists a -local variant, # just tell the user to use it. my $hint = 0; my $noam = $target; $noam =~ s/-am$//; if (exists $dependencies{"$noam-am"}) { $hint = "consider using $noam-local instead of $target"; } msg_cond_rule ('override', $cond, $target, "user target `$target' defined here" . "$condmsg...", partial => 1); msg ('override', $where, "... overrides Automake target `$oldname' defined here", partial => $hint); msg_cond_rule ('override', $cond, $target, $hint) if $hint; # Don't overwrite the user definition of TARGET. return (); } else # $oldowner == RULE_AUTOMAKE { # Automake should ignore redefinitions of its own # rules if they came from the same file. This makes # it easier to process a Makefile fragment several times. # However it's an error if the target is defined in many # files. E.g., the user might be using bin_PROGRAMS = ctags # which clashes with our `ctags' rule. # (It would be more accurate if we had a way to compare # the *content* of both rules. Then $targets_source would # be useless.) my $oldsource = $tdef->source; return () if $source eq $oldsource && $target eq $oldname; msg ('syntax', $where, "redefinition of `$target'$condmsg...", partial => 1); msg_cond_rule ('syntax', $cond, $target, "... `$oldname' previously defined here"); return (); } } # Never reached. prog_error ("Unreachable place reached."); } # Conditions for which the rule should be defined. my @conds = $cond; # Check ambiguous conditional definitions. my $rule = _crule $target; my ($message, $ambig_cond) = $rule->conditions->ambiguous_p ($target, $cond); if ($message) # We have an ambiguity. { if ($owner == RULE_USER) { # For user rules, just diagnose the ambiguity. msg 'syntax', $where, "$message ...", partial => 1; msg_cond_rule ('syntax', $ambig_cond, $target, "... `$target' previously defined here"); return (); } else { # FIXME: for Automake rules, we can't diagnose ambiguities yet. # The point is that Automake doesn't propagate conditions # everywhere. For instance &handle_PROGRAMS doesn't care if # bin_PROGRAMS was defined conditionally or not. # On the following input # if COND1 # foo: # ... # else # bin_PROGRAMS = foo # endif # &handle_PROGRAMS will attempt to define a `foo:' rule # in condition TRUE (which conflicts with COND1). Fixing # this in &handle_PROGRAMS and siblings seems hard: you'd # have to explain &file_contents what to do with a # condition. So for now we do our best *here*. If `foo:' # was already defined in condition COND1 and we want to define # it in condition TRUE, then define it only in condition !COND1. # (See cond14.test and cond15.test for some test cases.) @conds = $rule->not_always_defined_in_cond ($cond)->conds; # No conditions left to define the rule. # Warn, because our workaround is meaningless in this case. if (scalar @conds == 0) { msg 'syntax', $where, "$message ...", partial => 1; msg_cond_rule ('syntax', $ambig_cond, $target, "... `$target' previously defined here"); return (); } } } # Finally define this rule. for my $c (@conds) { my $def = new Automake::RuleDef ($target, '', $where->clone, $owner, $source); $rule->set ($c, $def); } # We honor inference rules with multiple targets because many # make support this and people use it. However this is disallowed # by POSIX. We'll print a warning later. my $target_count = 0; my $inference_rule_count = 0; for my $t (split (' ', $target)) { ++$target_count; # Check if the rule is a suffix rule: either it's a rule for # two known extensions... if ($t =~ /^($KNOWN_EXTENSIONS_PATTERN)($KNOWN_EXTENSIONS_PATTERN)$/ # ...or it's a rule with unknown extensions (i.e., the rule # looks like `.foo.bar:' but `.foo' or `.bar' are not # declared in SUFFIXES and are not known language # extensions). Automake will complete SUFFIXES from # @suffixes automatically (see handle_footer). || ($t =~ /$_SUFFIX_RULE_PATTERN/o && accept_extensions($1))) { ++$inference_rule_count; register_suffix_rule ($where, $1, $2); } } # POSIX allows multiple targets before the colon, but disallows # definitions of multiple inference rules. It's also # disallowed to mix plain targets with inference rules. msg ('portability', $where, "Inference rules can have only one target before the colon (POSIX).") if $inference_rule_count > 0 && $target_count > 1; return @conds; } =item C<depend ($target, @deps)> Adds C<@deps> to the dependencies of target C<$target>. This should be used only with factored targets (those appearing in C<%dependees>). =cut sub depend ($@) { my ($category, @dependees) = @_; push (@{$dependencies{$category}}, @dependees); } =back =head1 SEE ALSO L<Automake::RuleDef>, L<Automake::Condition>, L<Automake::DisjConditions>, L<Automake::Location>. =cut 1; ### Setup "GNU" style for perl-mode and cperl-mode. ## Local Variables: ## perl-indent-level: 2 ## perl-continued-statement-offset: 2 ## perl-continued-brace-offset: 0 ## perl-brace-offset: 0 ## perl-brace-imaginary-offset: 0 ## perl-label-offset: -2 ## cperl-indent-level: 2 ## cperl-brace-offset: 0 ## cperl-continued-brace-offset: 0 ## cperl-label-offset: -2 ## cperl-extra-newline-before-brace: t ## cperl-merge-trailing-else: nil ## cperl-continued-statement-offset: 2 ## End:
racker/omnibus
source/automake-1.10.3/lib/Automake/Rule.pm
Perl
apache-2.0
23,018
# Part of get-flash-videos. See get_flash_videos for copyright. package FlashVideo::Site::Ehow; use strict; use FlashVideo::Utils; use URI::Escape; sub find_video { my ($self, $browser) = @_; # Get the video ID my $uri; if ($browser->content =~ /source=(.*?)[ &]/) { $uri = $1; } else { die "Couldn't extract video location from page"; } my $title; if ($browser->content =~ /<h1[^>]* class="[^"]*articleTitle[^"]*"[^>]*>(.*?)<\/h1>/x) { $title = $1; } if($uri =~ /^http:/) { return $uri, title_to_filename($title); } elsif($uri =~ /http:%3A/) { # This is the embed, and it's the same but encoded. $uri = uri_unescape($1); # Title is also probably wrong if ($browser->content =~ /<a[^>]*>(.*?)<\/a>/) { $title = $1; } return $uri, title_to_filename($title); } else { die "Couldn't extract Flash video URL from embed page"; } } 1;
monsieurvideo/get-flash-videos
lib/FlashVideo/Site/Ehow.pm
Perl
apache-2.0
897
#!/usr/bin/perl -s ## ## Crypt::Primes -- Provable Prime Number Generator ## for Cryptographic Applications. ## ## Copyright (c) 1998-2000, Vipul Ved Prakash. All rights reserved. ## This code is free software; you can redistribute it and/or modify ## it under the same terms as Perl itself. ## ## $Id: Primes.pm,v 0.49 2001/06/11 01:04:23 vipul Exp vipul $ package Crypt::Primes; require Exporter; use vars qw($VERSION @EXPORT_OK); use Crypt::Random qw( makerandom makerandom_itv ); use Math::Pari qw( PARI Mod floor sqrt); *import = \&Exporter::import; @EXPORT_OK = qw( maurer trialdiv rsaparams ); ( $VERSION ) = '$Revision: 0.50 $' =~ /(\d+\.\d+)/; ## list of small primes for trial division. @PRIMES = qw( 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997 1009 1013 1019 1021 1031 1033 1039 1049 1051 1061 1063 1069 1087 1091 1093 1097 1103 1109 1117 1123 1129 1151 1153 1163 1171 1181 1187 1193 1201 1213 1217 1223 1229 1231 1237 1249 1259 1277 1279 1283 1289 1291 1297 1301 1303 1307 1319 1321 1327 1361 1367 1373 1381 1399 1409 1423 1427 1429 1433 1439 1447 1451 1453 1459 1471 1481 1483 1487 1489 1493 1499 1511 1523 1531 1543 1549 1553 1559 1567 1571 1579 1583 1597 1601 1607 1609 1613 1619 1621 1627 1637 1657 1663 1667 1669 1693 1697 1699 1709 1721 1723 1733 1741 1747 1753 1759 1777 1783 1787 1789 1801 1811 1823 1831 1847 1861 1867 1871 1873 1877 1879 1889 1901 1907 1913 1931 1933 1949 1951 1973 1979 1987 1993 1997 1999 2003 2011 2017 2027 2029 2039 2053 2063 2069 2081 2083 2087 2089 2099 2111 2113 2129 2131 2137 2141 2143 2153 2161 2179 2203 2207 2213 2221 2237 2239 2243 2251 2267 2269 2273 2281 2287 2293 2297 2309 2311 2333 2339 2341 2347 2351 2357 2371 2377 2381 2383 2389 2393 2399 2411 2417 2423 2437 2441 2447 2459 2467 2473 2477 2503 2521 2531 2539 2543 2549 2551 2557 2579 2591 2593 2609 2617 2621 2633 2647 2657 2659 2663 2671 2677 2683 2687 2689 2693 2699 2707 2711 2713 2719 2729 2731 2741 2749 2753 2767 2777 2789 2791 2797 2801 2803 2819 2833 2837 2843 2851 2857 2861 2879 2887 2897 2903 2909 2917 2927 2939 2953 2957 2963 2969 2971 2999 3001 3011 3019 3023 3037 3041 3049 3061 3067 3079 3083 3089 3109 3119 3121 3137 3163 3167 3169 3181 3187 3191 3203 3209 3217 3221 3229 3251 3253 3257 3259 3271 3299 3301 3307 3313 3319 3323 3329 3331 3343 3347 3359 3361 3371 3373 3389 3391 3407 3413 3433 3449 3457 3461 3463 3467 3469 3491 3499 3511 3517 3527 3529 3533 3539 3541 3547 3557 3559 3571 3581 3583 3593 3607 3613 3617 3623 3631 3637 3643 3659 3671 3673 3677 3691 3697 3701 3709 3719 3727 3733 3739 3761 3767 3769 3779 3793 3797 3803 3821 3823 3833 3847 3851 3853 3863 3877 3881 3889 3907 3911 3917 3919 3923 3929 3931 3943 3947 3967 3989 4001 4003 4007 4013 4019 4021 4027 4049 4051 4057 4073 4079 4091 4093 4099 4111 4127 4129 4133 4139 4153 4157 4159 4177 4201 4211 4217 4219 4229 4231 4241 4243 4253 4259 4261 4271 4273 4283 4289 4297 4327 4337 4339 4349 4357 4363 4373 4391 4397 4409 4421 4423 4441 4447 4451 4457 4463 4481 4483 4493 4507 4513 4517 4519 4523 4547 4549 4561 4567 4583 4591 4597 4603 4621 4637 4639 4643 4649 4651 4657 4663 4673 4679 4691 4703 4721 4723 4729 4733 4751 4759 4783 4787 4789 4793 4799 4801 4813 4817 4831 4861 4871 4877 4889 4903 4909 4919 4931 4933 4937 4943 4951 4957 4967 4969 4973 4987 4993 4999 5003 5009 5011 5021 5023 5039 5051 5059 5077 5081 5087 5099 5101 5107 5113 5119 5147 5153 5167 5171 5179 5189 5197 5209 5227 5231 5233 5237 5261 5273 5279 5281 5297 5303 5309 5323 5333 5347 5351 5381 5387 5393 5399 5407 5413 5417 5419 5431 5437 5441 5443 5449 5471 5477 5479 5483 5501 5503 5507 5519 5521 5527 5531 5557 5563 5569 5573 5581 5591 5623 5639 5641 5647 5651 5653 5657 5659 5669 5683 5689 5693 5701 5711 5717 5737 5741 5743 5749 5779 5783 5791 5801 5807 5813 5821 5827 5839 5843 5849 5851 5857 5861 5867 5869 5879 5881 5897 5903 5923 5927 5939 5953 5981 5987 6007 6011 6029 6037 6043 6047 6053 6067 6073 6079 6089 6091 6101 6113 6121 6131 6133 6143 6151 6163 6173 6197 6199 6203 6211 6217 6221 6229 6247 6257 6263 6269 6271 6277 6287 6299 6301 6311 6317 6323 6329 6337 6343 6353 6359 6361 6367 6373 6379 6389 6397 6421 6427 6449 6451 6469 6473 6481 6491 6521 6529 6547 6551 6553 6563 6569 6571 6577 6581 6599 6607 6619 6637 6653 6659 6661 6673 6679 6689 6691 6701 6703 6709 6719 6733 6737 6761 6763 6779 6781 6791 6793 6803 6823 6827 6829 6833 6841 6857 6863 6869 6871 6883 6899 6907 6911 6917 6947 6949 6959 6961 6967 6971 6977 6983 6991 6997 7001 7013 7019 7027 7039 7043 7057 7069 7079 7103 7109 7121 7127 7129 7151 7159 7177 7187 7193 7207 7211 7213 7219 7229 7237 7243 7247 7253 7283 7297 7307 7309 7321 7331 7333 7349 7351 7369 7393 7411 7417 7433 7451 7457 7459 7477 7481 7487 7489 7499 7507 7517 7523 7529 7537 7541 7547 7549 7559 7561 7573 7577 7583 7589 7591 7603 7607 7621 7639 7643 7649 7669 7673 7681 7687 7691 7699 7703 7717 7723 7727 7741 7753 7757 7759 7789 7793 7817 7823 7829 7841 7853 7867 7873 7877 7879 7883 7901 7907 7919 7927 7933 7937 7949 7951 7963 7993 8009 8011 8017 8039 8053 8059 8069 8081 8087 8089 8093 8101 8111 8117 8123 8147 8161 8167 8171 8179 8191 8209 8219 8221 8231 8233 8237 8243 8263 8269 8273 8287 8291 8293 8297 8311 8317 8329 8353 8363 8369 8377 8387 8389 8419 8423 8429 8431 8443 8447 8461 8467 8501 8513 8521 8527 8537 8539 8543 8563 8573 8581 8597 8599 8609 8623 8627 8629 8641 8647 8663 8669 8677 8681 8689 8693 8699 8707 8713 8719 8731 8737 8741 8747 8753 8761 8779 8783 8803 8807 8819 8821 8831 8837 8839 8849 8861 8863 8867 8887 8893 8923 8929 8933 8941 8951 8963 8969 8971 8999 9001 9007 9011 9013 9029 9041 9043 9049 9059 9067 9091 9103 9109 9127 9133 9137 9151 9157 9161 9173 9181 9187 9199 9203 9209 9221 9227 9239 9241 9257 9277 9281 9283 9293 9311 9319 9323 9337 9341 9343 9349 9371 9377 9391 9397 9403 9413 9419 9421 9431 9433 9437 9439 9461 9463 9467 9473 9479 9491 9497 9511 9521 9533 9539 9547 9551 9587 9601 9613 9619 9623 9629 9631 9643 9649 9661 9677 9679 9689 9697 9719 9721 9733 9739 9743 9749 9767 9769 9781 9787 9791 9803 9811 9817 9829 9833 9839 9851 9857 9859 9871 9883 9887 9901 9907 9923 9929 9931 9941 9949 9967 9973 10007 10009 10037 10039 10061 10067 10069 10079 10091 10093 10099 10103 10111 10133 10139 10141 10151 10159 10163 10169 10177 10181 10193 10211 10223 10243 10247 10253 10259 10267 10271 10273 10289 10301 10303 10313 10321 10331 10333 10337 10343 10357 10369 10391 10399 10427 10429 10433 10453 10457 10459 10463 10477 10487 10499 10501 10513 10529 10531 10559 10567 10589 10597 10601 10607 10613 10627 10631 10639 10651 10657 10663 10667 10687 10691 10709 10711 10723 10729 10733 10739 10753 10771 10781 10789 10799 10831 10837 10847 10853 10859 10861 10867 10883 10889 10891 10903 10909 10937 10939 10949 10957 10973 10979 10987 10993 11003 11027 11047 11057 11059 11069 11071 11083 11087 11093 11113 11117 11119 11131 11149 11159 11161 11171 11173 11177 11197 11213 11239 11243 11251 11257 11261 11273 11279 11287 11299 11311 11317 11321 11329 11351 11353 11369 11383 11393 11399 11411 11423 11437 11443 11447 11467 11471 11483 11489 11491 11497 11503 11519 11527 11549 11551 11579 11587 11593 11597 11617 11621 11633 11657 11677 11681 11689 11699 11701 11717 11719 11731 11743 11777 11779 11783 11789 11801 11807 11813 11821 11827 11831 11833 11839 11863 11867 11887 11897 11903 11909 11923 11927 11933 11939 11941 11953 11959 11969 11971 11981 11987 12007 12011 12037 12041 12043 12049 12071 12073 12097 12101 12107 12109 12113 12119 12143 12149 12157 12161 12163 12197 12203 12211 12227 12239 12241 12251 12253 12263 12269 12277 12281 12289 12301 12323 12329 12343 12347 12373 12377 12379 12391 12401 12409 12413 12421 12433 12437 12451 12457 12473 12479 12487 12491 12497 12503 12511 12517 12527 12539 12541 12547 12553 12569 12577 12583 12589 12601 12611 12613 12619 12637 12641 12647 12653 12659 12671 12689 12697 12703 12713 12721 12739 12743 12757 12763 12781 12791 12799 12809 12821 12823 12829 12841 12853 12889 12893 12899 12907 12911 12917 12919 12923 12941 12953 12959 12967 12973 12979 12983 13001 13003 13007 13009 13033 13037 13043 13049 13063 13093 13099 13103 13109 13121 13127 13147 13151 13159 13163 13171 13177 13183 13187 13217 13219 13229 13241 13249 13259 13267 13291 13297 13309 13313 13327 13331 13337 13339 13367 13381 13397 13399 13411 13417 13421 13441 13451 13457 13463 13469 13477 13487 13499 13513 13523 13537 13553 13567 13577 13591 13597 13613 13619 13627 13633 13649 13669 13679 13681 13687 13691 13693 13697 13709 13711 13721 13723 13729 13751 13757 13759 13763 13781 13789 13799 13807 13829 13831 13841 13859 13873 13877 13879 13883 13901 13903 13907 13913 13921 13931 13933 13963 13967 13997 13999 14009 14011 14029 14033 14051 14057 14071 14081 14083 14087 14107 14143 14149 14153 14159 14173 14177 14197 14207 14221 14243 14249 14251 14281 14293 14303 14321 14323 14327 14341 14347 14369 14387 14389 14401 14407 14411 14419 14423 14431 14437 14447 14449 14461 14479 14489 14503 14519 14533 14537 14543 14549 14551 14557 14561 14563 14591 14593 14621 14627 14629 14633 14639 14653 14657 14669 14683 14699 14713 14717 14723 14731 14737 14741 14747 14753 14759 14767 14771 14779 14783 14797 14813 14821 14827 14831 14843 14851 14867 14869 14879 14887 14891 14897 14923 14929 14939 14947 14951 14957 14969 14983 15013 15017 15031 15053 15061 15073 15077 15083 15091 15101 15107 15121 15131 15137 15139 15149 15161 15173 15187 15193 15199 15217 15227 15233 15241 15259 15263 15269 15271 15277 15287 15289 15299 15307 15313 15319 15329 15331 15349 15359 15361 15373 15377 15383 15391 15401 15413 15427 15439 15443 15451 15461 15467 15473 15493 15497 15511 15527 15541 15551 15559 15569 15581 15583 15601 15607 15619 15629 15641 15643 15647 15649 15661 15667 15671 15679 15683 15727 15731 15733 15737 15739 15749 15761 15767 15773 15787 15791 15797 15803 15809 15817 15823 15859 15877 15881 15887 15889 15901 15907 15913 15919 15923 15937 15959 15971 15973 15991 16001 16007 16033 16057 16061 16063 16067 16069 16073 16087 16091 16097 16103 16111 16127 16139 16141 16183 16187 16189 16193 16217 16223 16229 16231 16249 16253 16267 16273 16301 16319 16333 16339 16349 16361 16363 16369 16381 16411 16417 16421 16427 16433 16447 16451 16453 16477 16481 16487 16493 16519 16529 16547 16553 16561 16567 16573 16603 16607 16619 16631 16633 16649 16651 16657 16661 16673 16691 16693 16699 16703 16729 16741 16747 16759 16763 16787 16811 16823 16829 16831 16843 16871 16879 16883 16889 16901 16903 16921 16927 16931 16937 16943 16963 16979 16981 16987 16993 17011 17021 17027 17029 17033 17041 17047 17053 17077 17093 17099 17107 17117 17123 17137 17159 17167 17183 17189 17191 17203 17207 17209 17231 17239 17257 17291 17293 17299 17317 17321 17327 17333 17341 17351 17359 17377 17383 17387 17389 17393 17401 17417 17419 17431 17443 17449 17467 17471 17477 17483 17489 17491 17497 17509 17519 17539 17551 17569 17573 17579 17581 17597 17599 17609 17623 17627 17657 17659 17669 17681 17683 17707 17713 17729 17737 17747 17749 17761 17783 17789 17791 17807 17827 17837 17839 17851 17863 17881 17891 17903 17909 17911 17921 17923 17929 17939 17957 17959 17971 17977 17981 17987 17989 18013 18041 18043 18047 18049 18059 18061 18077 18089 18097 18119 18121 18127 18131 18133 18143 18149 18169 18181 18191 18199 18211 18217 18223 18229 18233 18251 18253 18257 18269 18287 18289 18301 18307 18311 18313 18329 18341 18353 18367 18371 18379 18397 18401 18413 18427 18433 18439 18443 18451 18457 18461 18481 18493 18503 18517 18521 18523 18539 18541 18553 18583 18587 18593 18617 18637 18661 18671 18679 18691 18701 18713 18719 18731 18743 18749 18757 18773 18787 18793 18797 18803 18839 18859 18869 18899 18911 18913 18917 18919 18947 18959 18973 18979 19001 19009 19013 19031 19037 19051 19069 19073 19079 19081 19087 19121 19139 19141 19157 19163 19181 19183 19207 19211 19213 19219 19231 19237 19249 19259 19267 19273 19289 19301 19309 19319 19333 19373 19379 19381 19387 19391 19403 19417 19421 19423 19427 19429 19433 19441 19447 19457 19463 19469 19471 19477 19483 19489 19501 19507 19531 19541 19543 19553 19559 19571 19577 19583 19597 19603 19609 19661 19681 19687 19697 19699 19709 19717 19727 19739 19751 19753 19759 19763 19777 19793 19801 19813 19819 19841 19843 19853 19861 19867 19889 19891 19913 19919 19927 19937 19949 19961 19963 19973 19979 19991 19993 19997 20011 20021 20023 20029 20047 20051 20063 20071 20089 20101 20107 20113 20117 20123 20129 20143 20147 20149 20161 20173 20177 20183 20201 20219 20231 20233 20249 20261 20269 20287 20297 20323 20327 20333 20341 20347 20353 20357 20359 20369 20389 20393 20399 20407 20411 20431 20441 20443 20477 20479 20483 20507 20509 20521 20533 20543 20549 20551 20563 20593 20599 20611 20627 20639 20641 20663 20681 20693 20707 20717 20719 20731 20743 20747 20749 20753 20759 20771 20773 20789 20807 20809 20849 20857 20873 20879 20887 20897 20899 20903 20921 20929 20939 20947 20959 20963 20981 20983 21001 21011 21013 21017 21019 21023 21031 21059 21061 21067 21089 21101 21107 21121 21139 21143 21149 21157 21163 21169 21179 21187 21191 21193 21211 21221 21227 21247 21269 21277 21283 21313 21317 21319 21323 21341 21347 21377 21379 21383 21391 21397 21401 21407 21419 21433 21467 21481 21487 21491 21493 21499 21503 21517 21521 21523 21529 21557 21559 21563 21569 21577 21587 21589 21599 21601 21611 21613 21617 21647 21649 21661 21673 21683 21701 21713 21727 21737 21739 21751 21757 21767 21773 21787 21799 21803 21817 21821 21839 21841 21851 21859 21863 21871 21881 21893 21911 21929 21937 21943 21961 21977 21991 21997 22003 22013 22027 22031 22037 22039 22051 22063 22067 22073 22079 22091 22093 22109 22111 22123 22129 22133 22147 22153 22157 22159 22171 22189 22193 22229 22247 22259 22271 22273 22277 22279 22283 22291 22303 22307 22343 22349 22367 22369 22381 22391 22397 22409 22433 22441 22447 22453 22469 22481 22483 22501 22511 22531 22541 22543 22549 22567 22571 22573 22613 22619 22621 22637 22639 22643 22651 22669 22679 22691 22697 22699 22709 22717 22721 22727 22739 22741 22751 22769 22777 22783 22787 22807 22811 22817 22853 22859 22861 22871 22877 22901 22907 22921 22937 22943 22961 22963 22973 22993 23003 23011 23017 23021 23027 23029 23039 23041 23053 23057 23059 23063 23071 23081 23087 23099 23117 23131 23143 23159 23167 23173 23189 23197 23201 23203 23209 23227 23251 23269 23279 23291 23293 23297 23311 23321 23327 23333 23339 23357 23369 23371 23399 23417 23431 23447 23459 23473 23497 23509 23531 23537 23539 23549 23557 23561 23563 23567 23581 23593 23599 23603 23609 23623 23627 23629 23633 23663 23669 23671 23677 23687 23689 23719 23741 23743 23747 23753 23761 23767 23773 23789 23801 23813 23819 23827 23831 23833 23857 23869 23873 23879 23887 23893 23899 23909 23911 23917 23929 23957 23971 23977 23981 23993 24001 24007 24019 24023 24029 24043 24049 24061 24071 24077 24083 24091 24097 24103 24107 24109 24113 24121 24133 24137 24151 24169 24179 24181 24197 24203 24223 24229 24239 24247 24251 24281 24317 24329 24337 24359 24371 24373 24379 24391 24407 24413 24419 24421 24439 24443 24469 24473 24481 24499 24509 24517 24527 24533 24547 24551 24571 24593 24611 24623 24631 24659 24671 24677 24683 24691 24697 24709 24733 24749 24763 24767 24781 24793 24799 24809 24821 24841 24847 24851 24859 24877 24889 24907 24917 24919 24923 24943 24953 24967 24971 24977 24979 24989 25013 25031 25033 25037 25057 25073 25087 25097 25111 25117 25121 25127 25147 25153 25163 25169 25171 25183 25189 25219 25229 25237 25243 25247 25253 25261 25301 25303 25307 25309 25321 25339 25343 25349 25357 25367 25373 25391 25409 25411 25423 25439 25447 25453 25457 25463 25469 25471 25523 25537 25541 25561 25577 25579 25583 25589 25601 25603 25609 25621 25633 25639 25643 25657 25667 25673 25679 25693 25703 25717 25733 25741 25747 25759 25763 25771 25793 25799 25801 25819 25841 25847 25849 25867 25873 25889 25903 25913 25919 25931 25933 25939 25943 25951 25969 25981 25997 25999 26003 26017 26021 26029 26041 26053 26083 26099 26107 26111 26113 26119 26141 26153 26161 26171 26177 26183 26189 26203 26209 26227 26237 26249 26251 26261 26263 26267 26293 26297 26309 26317 26321 26339 26347 26357 26371 26387 26393 26399 26407 26417 26423 26431 26437 26449 26459 26479 26489 26497 26501 26513 26539 26557 26561 26573 26591 26597 26627 26633 26641 26647 26669 26681 26683 26687 26693 26699 26701 26711 26713 26717 26723 26729 26731 26737 26759 26777 26783 26801 26813 26821 26833 26839 26849 26861 26863 26879 26881 26891 26893 26903 26921 26927 26947 26951 26953 26959 26981 26987 26993 27011 27017 27031 27043 27059 27061 27067 27073 27077 27091 27103 27107 27109 27127 27143 27179 27191 27197 27211 27239 27241 27253 27259 27271 27277 27281 27283 27299 27329 27337 27361 27367 27397 27407 27409 27427 27431 27437 27449 27457 27479 27481 27487 27509 27527 27529 27539 27541 27551 27581 27583 27611 27617 27631 27647 27653 27673 27689 27691 27697 27701 27733 27737 27739 27743 27749 27751 27763 27767 27773 27779 27791 27793 27799 27803 27809 27817 27823 27827 27847 27851 27883 27893 27901 27917 27919 27941 27943 27947 27953 27961 27967 27983 27997 28001 28019 28027 28031 28051 28057 28069 28081 28087 28097 28099 28109 28111 28123 28151 28163 28181 28183 28201 28211 28219 28229 28277 28279 28283 28289 28297 28307 28309 28319 28349 28351 28387 28393 28403 28409 28411 28429 28433 28439 28447 28463 28477 28493 28499 28513 28517 28537 28541 28547 28549 28559 28571 28573 28579 28591 28597 28603 28607 28619 28621 28627 28631 28643 28649 28657 28661 28663 28669 28687 28697 28703 28711 28723 28729 28751 28753 28759 28771 28789 28793 28807 28813 28817 28837 28843 28859 28867 28871 28879 28901 28909 28921 28927 28933 28949 28961 28979 29009 29017 29021 29023 29027 29033 29059 29063 29077 29101 29123 29129 29131 29137 29147 29153 29167 29173 29179 29191 29201 29207 29209 29221 29231 29243 29251 29269 29287 29297 29303 29311 29327 29333 29339 29347 29363 29383 29387 29389 29399 29401 29411 29423 29429 29437 29443 29453 29473 29483 29501 29527 29531 29537 29567 29569 29573 29581 29587 29599 29611 29629 29633 29641 29663 29669 29671 29683 29717 29723 29741 29753 29759 29761 29789 29803 29819 29833 29837 29851 29863 29867 29873 29879 29881 29917 29921 29927 29947 29959 29983 29989 30011 30013 30029 30047 30059 30071 30089 30091 30097 30103 30109 30113 30119 30133 30137 30139 30161 30169 30181 30187 30197 30203 30211 30223 30241 30253 30259 30269 30271 30293 30307 30313 30319 30323 30341 30347 30367 30389 30391 30403 30427 30431 30449 30467 30469 30491 30493 30497 30509 30517 30529 30539 30553 30557 30559 30577 30593 30631 30637 30643 30649 30661 30671 30677 30689 30697 30703 30707 30713 30727 30757 30763 30773 30781 30803 30809 30817 30829 30839 30841 30851 30853 30859 30869 30871 30881 30893 30911 30931 30937 30941 30949 30971 30977 30983 31013 31019 31033 31039 31051 31063 31069 31079 31081 31091 31121 31123 31139 31147 31151 31153 31159 31177 31181 31183 31189 31193 31219 31223 31231 31237 31247 31249 31253 31259 31267 31271 31277 31307 31319 31321 31327 31333 31337 31357 31379 31387 31391 31393 31397 31469 31477 31481 31489 31511 31513 31517 31531 31541 31543 31547 31567 31573 31583 31601 31607 31627 31643 31649 31657 31663 31667 31687 31699 31721 31723 31727 31729 31741 31751 31769 31771 31793 31799 31817 31847 31849 31859 31873 31883 31891 31907 31957 31963 31973 31981 31991 32003 32009 32027 32029 32051 32057 32059 32063 32069 32077 32083 32089 32099 32117 32119 32141 32143 32159 32173 32183 32189 32191 32203 32213 32233 32237 32251 32257 32261 32297 32299 32303 32309 32321 32323 32327 32341 32353 32359 32363 32369 32371 32377 32381 32401 32411 32413 32423 32429 32441 32443 32467 32479 32491 32497 32503 32507 32531 32533 32537 32561 32563 32569 32573 32579 32587 32603 32609 32611 32621 32633 32647 32653 32687 32693 32707 32713 32717 32719 32749 32771 32779 32783 32789 32797 32801 32803 32831 32833 32839 32843 32869 32887 32909 32911 32917 32933 32939 32941 32957 32969 32971 32983 32987 32993 32999 33013 33023 33029 33037 33049 33053 33071 33073 33083 33091 33107 33113 33119 33149 33151 33161 33179 33181 33191 33199 33203 33211 33223 33247 33287 33289 33301 33311 33317 33329 33331 33343 33347 33349 33353 33359 33377 33391 33403 33409 33413 33427 33457 33461 33469 33479 33487 33493 33503 33521 33529 33533 33547 33563 33569 33577 33581 33587 33589 33599 33601 33613 33617 33619 33623 33629 33637 33641 33647 33679 33703 33713 33721 33739 33749 33751 33757 33767 33769 33773 33791 33797 33809 33811 33827 33829 33851 33857 33863 33871 33889 33893 33911 33923 33931 33937 33941 33961 33967 33997 34019 34031 34033 34039 34057 34061 34123 34127 34129 34141 34147 34157 34159 34171 34183 34211 34213 34217 34231 34253 34259 34261 34267 34273 34283 34297 34301 34303 34313 34319 34327 34337 34351 34361 34367 34369 34381 34403 34421 34429 34439 34457 34469 34471 34483 34487 34499 34501 34511 34513 34519 34537 34543 34549 34583 34589 34591 34603 34607 34613 34631 34649 34651 34667 34673 34679 34687 34693 34703 34721 34729 34739 34747 34757 34759 34763 34781 34807 34819 34841 34843 34847 34849 34871 34877 34883 34897 34913 34919 34939 34949 34961 34963 34981 35023 35027 35051 35053 35059 35069 35081 35083 35089 35099 35107 35111 35117 35129 35141 35149 35153 35159 35171 35201 35221 35227 35251 35257 35267 35279 35281 35291 35311 35317 35323 35327 35339 35353 35363 35381 35393 35401 35407 35419 35423 35437 35447 35449 35461 35491 35507 35509 35521 35527 35531 35533 35537 35543 35569 35573 35591 35593 35597 35603 35617 35671 35677 35729 35731 35747 35753 35759 35771 35797 35801 35803 35809 35831 35837 35839 35851 35863 35869 35879 35897 35899 35911 35923 35933 35951 35963 35969 35977 35983 35993 35999 36007 36011 36013 36017 36037 36061 36067 36073 36083 36097 36107 36109 36131 36137 36151 36161 36187 36191 36209 36217 36229 36241 36251 36263 36269 36277 36293 36299 36307 36313 36319 36341 36343 36353 36373 36383 36389 36433 36451 36457 36467 36469 36473 36479 36493 36497 36523 36527 36529 36541 36551 36559 36563 36571 36583 36587 36599 36607 36629 36637 36643 36653 36671 36677 36683 36691 36697 36709 36713 36721 36739 36749 36761 36767 36779 36781 36787 36791 36793 36809 36821 36833 36847 36857 36871 36877 36887 36899 36901 36913 36919 36923 36929 36931 36943 36947 36973 36979 36997 37003 37013 37019 37021 37039 37049 37057 37061 37087 37097 37117 37123 37139 37159 37171 37181 37189 37199 37201 37217 37223 37243 37253 37273 37277 37307 37309 37313 37321 37337 37339 37357 37361 37363 37369 37379 37397 37409 37423 37441 37447 37463 37483 37489 37493 37501 37507 37511 37517 37529 37537 37547 37549 37561 37567 37571 37573 37579 37589 37591 37607 37619 37633 37643 37649 37657 37663 37691 37693 37699 37717 37747 37781 37783 37799 37811 37813 37831 37847 37853 37861 37871 37879 37889 37897 37907 37951 37957 37963 37967 37987 37991 37993 37997 38011 38039 38047 38053 38069 38083 38113 38119 38149 38153 38167 38177 38183 38189 38197 38201 38219 38231 38237 38239 38261 38273 38281 38287 38299 38303 38317 38321 38327 38329 38333 38351 38371 38377 38393 38431 38447 38449 38453 38459 38461 38501 38543 38557 38561 38567 38569 38593 38603 38609 38611 38629 38639 38651 38653 38669 38671 38677 38693 38699 38707 38711 38713 38723 38729 38737 38747 38749 38767 38783 38791 38803 38821 38833 38839 38851 38861 38867 38873 38891 38903 38917 38921 38923 38933 38953 38959 38971 38977 38993 39019 39023 39041 39043 39047 39079 39089 39097 39103 39107 39113 39119 39133 39139 39157 39161 39163 39181 39191 39199 39209 39217 39227 39229 39233 39239 39241 39251 39293 39301 39313 39317 39323 39341 39343 39359 39367 39371 39373 39383 39397 39409 39419 39439 39443 39451 39461 39499 39503 39509 39511 39521 39541 39551 39563 39569 39581 39607 39619 39623 39631 39659 39667 39671 39679 39703 39709 39719 39727 39733 39749 39761 39769 39779 39791 39799 39821 39827 39829 39839 39841 39847 39857 39863 39869 39877 39883 39887 39901 39929 39937 39953 39971 39979 39983 39989 40009 40013 40031 40037 40039 40063 40087 40093 40099 40111 40123 40127 40129 40151 40153 40163 40169 40177 40189 40193 40213 40231 40237 40241 40253 40277 40283 40289 40343 40351 40357 40361 40387 40423 40427 40429 40433 40459 40471 40483 40487 40493 40499 40507 40519 40529 40531 40543 40559 40577 40583 40591 40597 40609 40627 40637 40639 40693 40697 40699 40709 40739 40751 40759 40763 40771 40787 40801 40813 40819 40823 40829 40841 40847 40849 40853 40867 40879 40883 40897 40903 40927 40933 40939 40949 40961 40973 40993 41011 41017 41023 41039 41047 41051 41057 41077 41081 41113 41117 41131 41141 41143 41149 41161 41177 41179 41183 41189 41201 41203 41213 41221 41227 41231 41233 41243 41257 41263 41269 41281 41299 41333 41341 41351 41357 41381 41387 41389 41399 41411 41413 41443 41453 41467 41479 41491 41507 41513 41519 41521 41539 41543 41549 41579 41593 41597 41603 41609 41611 41617 41621 41627 41641 41647 41651 41659 41669 41681 41687 41719 41729 41737 41759 41761 41771 41777 41801 41809 41813 41843 41849 41851 41863 41879 41887 41893 41897 41903 41911 41927 41941 41947 41953 41957 41959 41969 41981 41983 41999 42013 42017 42019 42023 42043 42061 42071 42073 42083 42089 42101 42131 42139 42157 42169 42179 42181 42187 42193 42197 42209 42221 42223 42227 42239 42257 42281 42283 42293 42299 42307 42323 42331 42337 42349 42359 42373 42379 42391 42397 42403 42407 42409 42433 42437 42443 42451 42457 42461 42463 42467 42473 42487 42491 42499 42509 42533 42557 42569 42571 42577 42589 42611 42641 42643 42649 42667 42677 42683 42689 42697 42701 42703 42709 42719 42727 42737 42743 42751 42767 42773 42787 42793 42797 42821 42829 42839 42841 42853 42859 42863 42899 42901 42923 42929 42937 42943 42953 42961 42967 42979 42989 43003 43013 43019 43037 43049 43051 43063 43067 43093 43103 43117 43133 43151 43159 43177 43189 43201 43207 43223 43237 43261 43271 43283 43291 43313 43319 43321 43331 43391 43397 43399 43403 43411 43427 43441 43451 43457 43481 43487 43499 43517 43541 43543 43573 43577 43579 43591 43597 43607 43609 43613 43627 43633 43649 43651 43661 43669 43691 43711 43717 43721 43753 43759 43777 43781 43783 43787 43789 43793 43801 43853 43867 43889 43891 43913 43933 43943 43951 43961 43963 43969 43973 43987 43991 43997 44017 44021 44027 44029 44041 44053 44059 44071 44087 44089 44101 44111 44119 44123 44129 44131 44159 44171 44179 44189 44201 44203 44207 44221 44249 44257 44263 44267 44269 44273 44279 44281 44293 44351 44357 44371 44381 44383 44389 44417 44449 44453 44483 44491 44497 44501 44507 44519 44531 44533 44537 44543 44549 44563 44579 44587 44617 44621 44623 44633 44641 44647 44651 44657 44683 44687 44699 44701 44711 44729 44741 44753 44771 44773 44777 44789 44797 44809 44819 44839 44843 44851 44867 44879 44887 44893 44909 44917 44927 44939 44953 44959 44963 44971 44983 44987 45007 45013 45053 45061 45077 45083 45119 45121 45127 45131 45137 45139 45161 45179 45181 45191 45197 45233 45247 45259 45263 45281 45289 45293 45307 45317 45319 45329 45337 45341 45343 45361 45377 45389 45403 45413 45427 45433 45439 45481 45491 45497 45503 45523 45533 45541 45553 45557 45569 45587 45589 45599 45613 45631 45641 45659 45667 45673 45677 45691 45697 45707 45737 45751 45757 45763 45767 45779 45817 45821 45823 45827 45833 45841 45853 45863 45869 45887 45893 45943 45949 45953 45959 45971 45979 45989 46021 46027 46049 46051 46061 46073 46091 46093 46099 46103 46133 46141 46147 46153 46171 46181 46183 46187 46199 46219 46229 46237 46261 46271 46273 46279 46301 46307 46309 46327 46337 46349 46351 46381 46399 46411 46439 46441 46447 46451 46457 46471 46477 46489 46499 46507 46511 46523 46549 46559 46567 46573 46589 46591 46601 46619 46633 46639 46643 46649 46663 46679 46681 46687 46691 46703 46723 46727 46747 46751 46757 46769 46771 46807 46811 46817 46819 46829 46831 46853 46861 46867 46877 46889 46901 46919 46933 46957 46993 46997 47017 47041 47051 47057 47059 47087 47093 47111 47119 47123 47129 47137 47143 47147 47149 47161 47189 47207 47221 47237 47251 47269 47279 47287 47293 47297 47303 47309 47317 47339 47351 47353 47363 47381 47387 47389 47407 47417 47419 47431 47441 47459 47491 47497 47501 47507 47513 47521 47527 47533 47543 47563 47569 47581 47591 47599 47609 47623 47629 47639 47653 47657 47659 47681 47699 47701 47711 47713 47717 47737 47741 47743 47777 47779 47791 47797 47807 47809 47819 47837 47843 47857 47869 47881 47903 47911 47917 47933 47939 47947 47951 47963 47969 47977 47981 48017 48023 48029 48049 48073 48079 48091 48109 48119 48121 48131 48157 48163 48179 48187 48193 48197 48221 48239 48247 48259 48271 48281 48299 48311 48313 48337 48341 48353 48371 48383 48397 48407 48409 48413 48437 48449 48463 48473 48479 48481 48487 48491 48497 48523 48527 48533 48539 48541 48563 48571 48589 48593 48611 48619 48623 48647 48649 48661 48673 48677 48679 48731 48733 48751 48757 48761 48767 48779 48781 48787 48799 48809 48817 48821 48823 48847 48857 48859 48869 48871 48883 48889 48907 48947 48953 48973 48989 48991 49003 49009 49019 49031 49033 49037 49043 49057 49069 49081 49103 49109 49117 49121 49123 49139 49157 49169 49171 49177 49193 49199 49201 49207 49211 49223 49253 49261 49277 49279 49297 49307 49331 49333 49339 49363 49367 49369 49391 49393 49409 49411 49417 49429 49433 49451 49459 49463 49477 49481 49499 49523 49529 49531 49537 49547 49549 49559 49597 49603 49613 49627 49633 49639 49663 49667 49669 49681 49697 49711 49727 49739 49741 49747 49757 49783 49787 49789 49801 49807 49811 49823 49831 49843 49853 49871 49877 49891 49919 49921 49927 49937 49939 49943 49957 49991 49993 49999 50021 50023 50033 50047 50051 50053 50069 50077 50087 50093 50101 50111 50119 50123 50129 50131 50147 50153 50159 50177 50207 50221 50227 50231 50261 50263 50273 50287 50291 50311 50321 50329 50333 50341 50359 50363 50377 50383 50387 50411 50417 50423 50441 50459 50461 50497 50503 50513 50527 50539 50543 50549 50551 50581 50587 50591 50593 50599 50627 50647 50651 50671 50683 50707 50723 50741 50753 50767 50773 50777 50789 50821 50833 50839 50849 50857 50867 50873 50891 50893 50909 50923 50929 50951 50957 50969 50971 50989 50993 51001 51031 51043 51047 51059 51061 51071 51109 51131 51133 51137 51151 51157 51169 51193 51197 51199 51203 51217 51229 51239 51241 51257 51263 51283 51287 51307 51329 51341 51343 51347 51349 51361 51383 51407 51413 51419 51421 51427 51431 51437 51439 51449 51461 51473 51479 51481 51487 51503 51511 51517 51521 51539 51551 51563 51577 51581 51593 51599 51607 51613 51631 51637 51647 51659 51673 51679 51683 51691 51713 51719 51721 51749 51767 51769 51787 51797 51803 51817 51827 51829 51839 51853 51859 51869 51871 51893 51899 51907 51913 51929 51941 51949 51971 51973 51977 51991 52009 52021 52027 52051 52057 52067 52069 52081 52103 52121 52127 52147 52153 52163 52177 52181 52183 52189 52201 52223 52237 52249 52253 52259 52267 52289 52291 52301 52313 52321 52361 52363 52369 52379 52387 52391 52433 52453 52457 52489 52501 52511 52517 52529 52541 52543 52553 52561 52567 52571 52579 52583 52609 52627 52631 52639 52667 52673 52691 52697 52709 52711 52721 52727 52733 52747 52757 52769 52783 52807 52813 52817 52837 52859 52861 52879 52883 52889 52901 52903 52919 52937 52951 52957 52963 52967 52973 52981 52999 53003 53017 53047 53051 53069 53077 53087 53089 53093 53101 53113 53117 53129 53147 53149 53161 53171 53173 53189 53197 53201 53231 53233 53239 53267 53269 53279 53281 53299 53309 53323 53327 53353 53359 53377 53381 53401 53407 53411 53419 53437 53441 53453 53479 53503 53507 53527 53549 53551 53569 53591 53593 53597 53609 53611 53617 53623 53629 53633 53639 53653 53657 53681 53693 53699 53717 53719 53731 53759 53773 53777 53783 53791 53813 53819 53831 53849 53857 53861 53881 53887 53891 53897 53899 53917 53923 53927 53939 53951 53959 53987 53993 54001 54011 54013 54037 54049 54059 54083 54091 54101 54121 54133 54139 54151 54163 54167 54181 54193 54217 54251 54269 54277 54287 54293 54311 54319 54323 54331 54347 54361 54367 54371 54377 54401 54403 54409 54413 54419 54421 54437 54443 54449 54469 54493 54497 54499 54503 54517 54521 54539 54541 54547 54559 54563 54577 54581 54583 54601 54617 54623 54629 54631 54647 54667 54673 54679 54709 54713 54721 54727 54751 54767 54773 54779 54787 54799 54829 54833 54851 54869 54877 54881 54907 54917 54919 54941 54949 54959 54973 54979 54983 55001 55009 55021 55049 55051 55057 55061 55073 55079 55103 55109 55117 55127 55147 55163 55171 55201 55207 55213 55217 55219 55229 55243 55249 55259 55291 55313 55331 55333 55337 55339 55343 55351 55373 55381 55399 55411 55439 55441 55457 55469 55487 55501 55511 55529 55541 55547 55579 55589 55603 55609 55619 55621 55631 55633 55639 55661 55663 55667 55673 55681 55691 55697 55711 55717 55721 55733 55763 55787 55793 55799 55807 55813 55817 55819 55823 55829 55837 55843 55849 55871 55889 55897 55901 55903 55921 55927 55931 55933 55949 55967 55987 55997 56003 56009 56039 56041 56053 56081 56087 56093 56099 56101 56113 56123 56131 56149 56167 56171 56179 56197 56207 56209 56237 56239 56249 56263 56267 56269 56299 56311 56333 56359 56369 56377 56383 56393 56401 56417 56431 56437 56443 56453 56467 56473 56477 56479 56489 56501 56503 56509 56519 56527 56531 56533 56543 56569 56591 56597 56599 56611 56629 56633 56659 56663 56671 56681 56687 56701 56711 56713 56731 56737 56747 56767 56773 56779 56783 56807 56809 56813 56821 56827 56843 56857 56873 56891 56893 56897 56909 56911 56921 56923 56929 56941 56951 56957 56963 56983 56989 56993 56999 57037 57041 57047 57059 57073 57077 57089 57097 57107 57119 57131 57139 57143 57149 57163 57173 57179 57191 57193 57203 57221 57223 57241 57251 57259 57269 57271 57283 57287 57301 57329 57331 57347 57349 57367 57373 57383 57389 57397 57413 57427 57457 57467 57487 57493 57503 57527 57529 57557 57559 57571 57587 57593 57601 57637 57641 57649 57653 57667 57679 57689 57697 57709 57713 57719 57727 57731 57737 57751 57773 57781 57787 57791 57793 57803 57809 57829 57839 57847 57853 57859 57881 57899 57901 57917 57923 57943 57947 57973 57977 57991 58013 58027 58031 58043 58049 58057 58061 58067 58073 58099 58109 58111 58129 58147 58151 58153 58169 58171 58189 58193 58199 58207 58211 58217 58229 58231 58237 58243 58271 58309 58313 58321 58337 58363 58367 58369 58379 58391 58393 58403 58411 58417 58427 58439 58441 58451 58453 58477 58481 58511 58537 58543 58549 58567 58573 58579 58601 58603 58613 58631 58657 58661 58679 58687 58693 58699 58711 58727 58733 58741 58757 58763 58771 58787 58789 58831 58889 58897 58901 58907 58909 58913 58921 58937 58943 58963 58967 58979 58991 58997 59009 59011 59021 59023 59029 59051 59053 59063 59069 59077 59083 59093 59107 59113 59119 59123 59141 59149 59159 59167 59183 59197 59207 59209 59219 59221 59233 59239 59243 59263 59273 59281 59333 59341 59351 59357 59359 59369 59377 59387 59393 59399 59407 59417 59419 59441 59443 59447 59453 59467 59471 59473 59497 59509 59513 59539 59557 59561 59567 59581 59611 59617 59621 59627 59629 59651 59659 59663 59669 59671 59693 59699 59707 59723 59729 59743 59747 59753 59771 59779 59791 59797 59809 59833 59863 59879 59887 59921 59929 59951 59957 59971 59981 59999 60013 60017 60029 60037 60041 60077 60083 60089 60091 60101 60103 60107 60127 60133 60139 60149 60161 60167 60169 60209 60217 60223 60251 60257 60259 60271 60289 60293 60317 60331 60337 60343 60353 60373 60383 60397 60413 60427 60443 60449 60457 60493 60497 60509 60521 60527 60539 60589 60601 60607 60611 60617 60623 60631 60637 60647 60649 60659 60661 60679 60689 60703 60719 60727 60733 60737 60757 60761 60763 60773 60779 60793 60811 60821 60859 60869 60887 60889 60899 60901 60913 60917 60919 60923 60937 60943 60953 60961 61001 61007 61027 61031 61043 61051 61057 61091 61099 61121 61129 61141 61151 61153 61169 61211 61223 61231 61253 61261 61283 61291 61297 61331 61333 61339 61343 61357 61363 61379 61381 61403 61409 61417 61441 61463 61469 61471 61483 61487 61493 61507 61511 61519 61543 61547 61553 61559 61561 61583 61603 61609 61613 61627 61631 61637 61643 61651 61657 61667 61673 61681 61687 61703 61717 61723 61729 61751 61757 61781 61813 61819 61837 61843 61861 61871 61879 61909 61927 61933 61949 61961 61967 61979 61981 61987 61991 62003 62011 62017 62039 62047 62053 62057 62071 62081 62099 62119 62129 62131 62137 62141 62143 62171 62189 62191 62201 62207 62213 62219 62233 62273 62297 62299 62303 62311 62323 62327 62347 62351 62383 62401 62417 62423 62459 62467 62473 62477 62483 62497 62501 62507 62533 62539 62549 62563 62581 62591 62597 62603 62617 62627 62633 62639 62653 62659 62683 62687 62701 62723 62731 62743 62753 62761 62773 62791 62801 62819 62827 62851 62861 62869 62873 62897 62903 62921 62927 62929 62939 62969 62971 62981 62983 62987 62989 63029 63031 63059 63067 63073 63079 63097 63103 63113 63127 63131 63149 63179 63197 63199 63211 63241 63247 63277 63281 63299 63311 63313 63317 63331 63337 63347 63353 63361 63367 63377 63389 63391 63397 63409 63419 63421 63439 63443 63463 63467 63473 63487 63493 63499 63521 63527 63533 63541 63559 63577 63587 63589 63599 63601 63607 63611 63617 63629 63647 63649 63659 63667 63671 63689 63691 63697 63703 63709 63719 63727 63737 63743 63761 63773 63781 63793 63799 63803 63809 63823 63839 63841 63853 63857 63863 63901 63907 63913 63929 63949 63977 63997 64007 64013 64019 64033 64037 64063 64067 64081 64091 64109 64123 64151 64153 64157 64171 64187 64189 64217 64223 64231 64237 64271 64279 64283 64301 64303 64319 64327 64333 64373 64381 64399 64403 64433 64439 64451 64453 64483 64489 64499 64513 64553 64567 64577 64579 64591 64601 64609 64613 64621 64627 64633 64661 64663 64667 64679 64693 64709 64717 64747 64763 64781 64783 64793 64811 64817 64849 64853 64871 64877 64879 64891 64901 64919 64921 64927 64937 64951 64969 64997 65003 65011 65027 65029 65033 65053 65063 65071 65089 65099 65101 65111 65119 65123 65129 65141 65147 65167 65171 65173 65179 65183 65203 65213 65239 65257 65267 65269 65287 65293 65309 65323 65327 65353 65357 65371 65381 65393 65407 65413 65419 65423 65437 65447 65449 65479 65497 65519 65521 ); my $l; my @used; my @gens; sub rsaparams { my (%params) = @_; @used = (); my %paramsrsa = (%params, (Relprime => 1)); my $p = maurer (%paramsrsa); print "\n" if $params{Verbosity}; my $q = maurer (%paramsrsa); print "\n" if $params{Verbosity}; return { p => $p, q => $q, e => 65537 } } sub maurer { my ( %params ) = @_; my $k = $params { Size }; #-- bitsize of the required prime. my $v = $params { Verbosity }; #-- process reporting verbosity. #-- whether to find intermediate generators. my $p0 = 20; #-- generate primes of bitsize less #-- than $p0 with nextprime(). my $maxfact = 140; #-- bitsize of the biggest number we #-- can factor easily. $| = 1; if ( $k <= $p0 ) { my $spr = makerandom Size => $k; return Math::Pari::nextprime ( $spr ); } my $c_opt = 0.09; my $m = 20; my $B = floor ( $c_opt * ( $k ** 2 ) ); my $r = PARI ( 2 ** ( ( rand ) - 1 ) ); srand ( makerandom ( Size => 32, Strength => 0 ) ); if ( $k > ( 2 * $m ) ) { my $frs = 0; until ( $frs ) { $r = 2 ** ( (rand) - 1 ); my $rbits = $k-($r*$k); $frs = 1 if $rbits > $m; $frs = 0 if ($params{Generator} && ($rbits > $maxfact)); } } else { $r = 0.5; } my $q = maurer ( Size => floor ( $r * $k ) + 2, Verbosity => $v, Generator => $params{Generator}, Intermediates => $params{Intermediates} ); if ($params{Relprime}) { while ((grep /$q/, @used)) { print "<" if $v == 1; $q = maurer ( Size => floor ( $r * $k ) + 2, Verbosity => $v, Relprime => 1, Generator => $params{Generator}, Intermediates => $params{Intermediates} ); } } $q = $q->{Prime} if (ref $q eq 'HASH'); print "B = $B, r = $r, k = $k, q = $q\n" if $v == 2; push @used, $q; my $o1 = PARI ( 2 * $q ); my $o2 = PARI '2' ** PARI "@{[$k - 1]}"; my $I = floor ( $o2 / $o1 ); my $n = PARI (); while (1) { my $R = PARI ( makerandom_itv ( Lower => $I + 1, Upper => 2 * $I ) ); $n = floor( 2 * $R * $q + 1 ); print "n = $n\n" if $v == 2; print "." if $v == 1; my $a = PARI(); if ( trialdiv ( $n, $B ) ) { BASE: { print "(passes trial division)\n" if $v == 2; print "+" if $v == 1; $a = makerandom_itv( Lower => 2, Upper=> $n - 2 ); $a = makerandom_itv( Lower => 2, Upper=> $R ) if $params{Generator}; my $t1 = Mod (2, $n); my $t2 = Mod ($a, $n); my $b = $t2 ** ( $n - 1 ); if ( ($b == 1) && ( $q > $n ** (1/3.0) ) ) { print "$n is prime! a = $a, R = $R\n" if $v == 2; print "($k)" if $v == 1; my @s; if ($params{Generator}) { print "computing a generator...\n" if $v == 2; print "# " if $v == 1; @s = Math::Pari::factor($R) =~ m:[\[\(\;](\d+)(?=,):g; push @s, ($q,2); my $p = PARI (1); for (@s) { $p *= $_ }; for (@s) { my $b = Mod ($a, $p) ** PARI($p/$_); if ($b == 1) { print "@!" if $v == 1; print "$a is not a generator\n" if $v == 2; next BASE; } } } my @factors = ( Factors => \@s, R => $R ) if $params{Factors}; my @intermediates = ( Intermediates => \@used ) if $params{Intermediates}; return { @factors, @intermediates, Prime => $n, Generator => $a } if $params{Generator}; return { @factors, @intermediates, Prime => $n } if $params{Factors} or $params{Intermediates}; return $n; } } } } } sub trialdiv { my ( $n, $limit, $v ) = @_; my $end = _trialdiv_limit ( $n, $limit ); for ( $i=0; $i <= $end; $i++ ) { return undef unless Math::Pari::gmod ( $n, $PRIMES[ $i ] ); } return 1; } sub _trialdiv_limit { my ($n, $limit) = @_; my $start = 0; my $mid; my $end = $#PRIMES; $limit = int(sqrt($n)) unless $limit; if ( $limit <= $PRIMES[ $end ] ) { while ( ( $start + 1 ) != $end ) { use integer; $mid = int (( $end + $start ) / 2); no integer; $start = $mid if $limit > $PRIMES[ $mid ]; $end = $mid if $limit <= $PRIMES[ $mid ]; } } return $end; } "True Value"; =head1 NAME Crypt::Primes - Provable Prime Number Generator suitable for Cryptographic Applications. =head1 VERSION $Revision: 0.49 $ $Date: 2001/06/11 01:04:23 $ =head1 SYNOPSIS # generate a random, provable 512-bit prime. use Crypt::Primes qw(maurer); my $prime = maurer (Size => 512); # generate a random, provable 2048-bit prime and report # progress on console. my $another_prime = maurer ( Size => 2048, Verbosity => 1 ); # generate a random 1024-bit prime and a group # generator of Z*(n). my $hash_ref = maurer ( Size => 1024, Generator => 1, Verbosity => 1 ); =head1 WARNING The codebase is stable, but the API will most definitely change in a future release. =head1 DESCRIPTION This module implements Ueli Maurer's algorithm for generating large I<provable> primes and secure parameters for public-key cryptosystems. The generated primes are almost uniformly distributed over the set of primes of the specified bitsize and expected time for generation is less than the time required for generating a pseudo-prime of the same size with Miller-Rabin tests. Detailed description and running time analysis of the algorithm can be found in Maurer's paper[1]. Crypt::Primes is a pure perl implementation. It uses Math::Pari for multiple precision integer arithmetic and number theoretic functions. Random numbers are gathered with Crypt::Random, a perl interface to /dev/u?random devices found on most modern Unix operating systems. =head1 FUNCTIONS The following functions are availble for import. They must be explicitely imported. =over 4 =item B<maurer(%params)> Generates a prime number of the specified bitsize. Takes a hash as parameter and returns a Math::Pari object (prime number) or a hash reference (prime number and generator) when group generator computation is requested. Following hash keys are understood: =back =over 0 =item B<Size> Bitsize of the required prime number. =item B<Verbosity> Level of verbosity of progress reporting. Report is printed on STDOUT. Level of 1 indicates normal, terse reporting. Level of 2 prints lots of intermediate computations, useful for debugging. =item B<Generator> When Generator key is set to a non-zero value, a group generator of Z*(n) is computed. Group generators are required key material in public-key cryptosystems like Elgamal and Diffie-Hellman that are based on intractability of the discrete logarithm problem. When this option is present, maurer() returns a hash reference that contains two keys, Prime and Generator. =item B<Relprime> When set to 1, maurer() stores intermediate primes in a class array, and ensures they are not used during construction of primes in the future calls to maurer() with Reprime => 1. This is used by rsaparams(). =item B<Intermediates> When set to 1, maurer() returns a hash reference that contains (corresponding to the key 'Intermediates') a reference to an array of intermediate primes generated. =item B<Factors> When set to 1, maurer() returns a hash reference that contains (corresponding to the key 'Factors') a reference to an array of factors of p-1 where p is the prime generated, and also (corresponding to the key 'R') a divisor of p. =back =over 4 =item B<rsaparams(%params)> Generates two primes (p,q) and public exponent (e) of a RSA key pair. The key pair generated with this method is resistant to iterative encryption attack. See Appendix 2 of [1] for more information. rsaparams() takes the same arguments as maurer() with the exception of `Generator' and `Relprime'. Size specifies the common bitsize of p an q. Returns a hash reference with keys p, q and e. =item B<trialdiv($n,$limit)> Performs trial division on $n to ensure it's not divisible by any prime smaller than or equal to $limit. The module maintains a lookup table of primes (from 2 to 65521) for this purpose. If $limit is not provided, a suitable value is computed automatically. trialdiv() is used by maurer() to weed out composite random numbers before performing computationally intensive modular exponentiation tests. It is, however, documented should you need to use it directly. =back =head1 IMPLEMENTATION NOTE This module implements a modified FastPrime, as described in [1], to facilitate group generator computation. (Refer to [1] and [2] for description and pseudo-code of FastPrime). The modification involves introduction of an additional constraint on relative size r of q. While computing r, we ensure k * r is always greater than maxfact, where maxfact is the bitsize of the largest number we can factor easily. This value defaults to 140 bits. As a result, R is always smaller than maxfact, which allows us to get a complete factorization of 2Rq and use it to find a generator of the cyclic group Z*(2Rq). =head1 RUNNING TIME Crypt::Primes generates 512-bit primes in 7 seconds (on average), and 1024-bit primes in 37 seconds (on average), on my PII 300 Mhz notebook. There are no computational limits by design; primes upto 8192-bits were generated to stress test the code. For detailed runtime analysis see [1]. =head1 SEE ALSO largeprimes(1), Crypt::Random(3), Math::Pari(3) =head1 BIBLIOGRAPHY =over 4 =item 1 Fast Generation of Prime Numbers and Secure Public-Key Cryptographic Parameters, Ueli Maurer (1994). =item 2 Corrections to Fast Generation of Prime Numbers and Secure Public-Key Cryptographic Parameters, Ueli Maurer (1996). =item 3 Handbook of Applied Cryptography by Menezes, Paul C. van Oorschot and Scott Vanstone (1997). =item Documents 1 & 2 can be found under docs/ of the source distribution. =back =head1 AUTHOR Vipul Ved Prakash, E<lt>mail@vipul.netE<gt> =cut =head1 LICENSE Copyright (c) 1998-2001, Vipul Ved Prakash. All rights reserved. This code is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 TODO Maurer's algorithm generates primes of progressively larger bitsize using a recursive construction method. The algorithm enters recursion with a prime number and bitsize of the next prime to be generated. (Bitsizes of the intermediate primes are computed using a probability distribution that ensures generated primes are sufficiently random.) This recursion can be distributed over multiple machines, participating in a competitive computation model, to achieve close to best running time of the algorithm. Support for this will be implemented some day, possibly when the next version of Penguin hits CPAN.
Dokaponteam/ITF_Project
xampp/perl/vendor/lib/Crypt/Primes.pm
Perl
mit
52,398
#!/usr/bin/perl # $Id: 20120722$ # $Date: 2012-07-22 17:37:43$ # $Author: Marek Lukaszuk$ # clearing a bit the output of "get tech" use strict; use warnings; use integer; my $empty = 0; while(<>){ if (/^\s*$/){ $empty++; }else{ $empty = 0; } next if ($empty > 1); s/(\x07)+/\n/g; s/--- more --- //; s/---\(more\)---(\x0d\s+\x0d)?//; s/---\(more \d+%\)---(\x0d\s+\x0d)?//; s/(\x08|\x0d)//g; s/---\(more\)---(\ ){39}//; print; }
mmmonk/crap
jnpr/screenos/cjc.pl
Perl
mit
476
#!/usr/bin/perl use strict; use warnings; use feature qw(say); my($pid, @cmd) = @ARGV; if( !$pid || !@cmd ) { say "usage ./run_after.pl pid command..."; exit 1; } if( !kill(0, $pid) ) { say "process $pid doesn't exist."; exit 1; } say "process $pid is running, keep an eye on it..."; { if( !kill(0, $pid) ) { say "process $pid ended. RUN @cmd!"; system("@cmd"); exit 0; } select undef, undef, undef, .1; redo; }
CindyLinz/Toolkit
run_after.pl
Perl
mit
473
package Dancer::Session::Abstract; use strict; use warnings; use Carp; use base 'Dancer::Engine'; use Dancer::Config 'setting'; use Dancer::Cookies; use File::Spec; __PACKAGE__->attributes('id'); # args: ($class, $id) # receives a session id and should return a session object if found, or undef # otherwise. sub retrieve { confess "retrieve not implemented"; } # args: ($class) # create a new empty session, flush it and return it. sub create { confess "create not implemented"; } # args: ($self) # write the (serialized) current session to the session storage sub flush { confess "flush not implemented"; } # args: ($self) # remove the session from the session storage sub destroy { confess "destroy not implemented"; } # does nothing in most cases (exception is YAML) sub reset { return; } # if subclass overrides to true, flush will not be called after write # and subclass or application must call flush (perhaps in an after hook) sub is_lazy { 0 }; # This is the default constructor for the session object, the only mandatory # attribute is 'id'. The whole object should be serialized by the session # engine. # If you override this constructor, remember to call $self->SUPER::init() so # that the session ID is still generated. sub init { my ($self) = @_; $self->id(build_id()); } # this method can be overwritten in any Dancer::Session::* module sub session_name { setting('session_name') || 'dancer.session'; } # Methods below this line should not be overloaded. # we try to make the best random number # with native Perl 5 code. # to rebuild a session id, an attacker should know: # - the running PID of the server # - the current timestamp of the time it was built # - the path of the installation directory # - guess the correct number between 0 and 1000000000 # - should be able to reproduce that 3 times sub build_id { my $session_id = ""; foreach my $seed (rand(1000), rand(1000), rand(1000)) { my $c = 0; $c += ord($_) for (split //, File::Spec->rel2abs(File::Spec->curdir)); my $current = int($seed * 1000000000) + time + $$ + $c; $session_id .= $current; } return $session_id; } sub read_session_id { my ($class) = @_; my $name = $class->session_name(); my $c = Dancer::Cookies->cookies->{$name}; return (defined $c) ? $c->value : undef; } sub write_session_id { my ($class, $id) = @_; my $name = $class->session_name(); my %cookie = ( name => $name, value => $id, domain => setting('session_domain'), secure => setting('session_secure'), http_only => defined(setting("session_is_http_only")) ? setting("session_is_http_only") : 1, ); if (my $expires = setting('session_expires')) { # It's # of seconds from the current time # Otherwise just feed it through. $expires = Dancer::Cookie::_epoch_to_gmtstring(time + $expires) if $expires =~ /^\d+$/; $cookie{expires} = $expires; } my $c = Dancer::Cookie->new(%cookie); Dancer::Cookies->set_cookie_object($name => $c); } 1; __END__ =pod =head1 NAME Dancer::Session::Abstract - abstract class for session engine =head1 SPEC =over 4 =item B<role> A Dancer::Session object represents a session engine and should provide anything needed to manipulate a session, whatever its storing engine is. =item B<id> The session id will be written to a cookie, by default named C<dancer.session>, it is assumed that a client must accept cookies to be able to use a session-aware Dancer webapp. (The cookie name can be change using the C<session_name> config setting.) =item B<storage engine> When the session engine is enabled, a I<before> filter takes care to initialize the appropriate session engine (according to the setting C<session>). Then, the filter looks for a cookie named C<dancer.session> (or whatever you've set the C<session_name> setting to, if you've used it) in order to I<retrieve> the current session object. If not found, a new session object is I<created> and its id written to the cookie. Whenever a session call is made within a route handler, the singleton representing the current session object is modified. A I<flush> is made to the session object after every modification unless the session engine overrides the C<is_lazy> method to return true. =back =head1 DESCRIPTION This virtual class describes how to build a session engine for Dancer. This is done in order to allow multiple session storage backends with a common interface. Any session engine must inherit from Dancer::Session::Abstract and implement the following abstract methods. =head2 Configuration These settings control how a session acts. =head3 session_name The default session name is "dancer_session". This can be set in your config file: setting session_name: "mydancer_session" =head3 session_domain Allows you to set the domain property on the cookie, which will override the default. This is useful for setting the session cookie's domain to something like C<.domain.com> so that the same cookie will be applicable and usable across subdomains of a base domain. =head3 session_secure The user's session id is stored in a cookie. If true, this cookie will be made "secure" meaning it will only be served over https. =head3 session_expires When the session should expire. The format is either the number of seconds in the future, or the human readable offset from L<Dancer::Cookie/expires>. By default, there is no expiration. =head3 session_is_http_only This setting defaults to 1 and instructs the session cookie to be created with the C<HttpOnly> option active, meaning that JavaScript will not be able to access to its value. =head2 Abstract Methods =over 4 =item B<retrieve($id)> Look for a session with the given id, return the session object if found, undef if not. =item B<create()> Create a new session, return the session object. =item B<flush()> Write the session object to the storage engine. =item B<destroy()> Remove the current session object from the storage engine. =item B<session_name> (optional) Returns a string with the name of cookie used for storing the session ID. You should probably not override this; the user can control the cookie name using the C<session_name> setting. =back =head2 Inherited Methods The following methods are not supposed to be overloaded, they are generic and should be OK for each session engine. =over 4 =item B<build_id> Build a new uniq id. =item B<read_session_id> Reads the C<dancer.session> cookie. =item B<write_session_id> Write the current session id to the C<dancer.session> cookie. =item B<is_lazy> Default is false. If true, session data will not be flushed after every modification and the session engine (or application) will need to ensure that a flush is called before the end of the request. =back =cut
dimpu/AravindCom
api/perl/MAP/Modules/Dancer-1.3124/lib/Dancer/Session/Abstract.pm
Perl
mit
6,934
=pod =head1 NAME ec - Elliptic Curve functions =head1 SYNOPSIS #include <openssl/ec.h> #include <openssl/bn.h> const EC_METHOD *EC_GFp_simple_method(void); const EC_METHOD *EC_GFp_mont_method(void); const EC_METHOD *EC_GFp_nist_method(void); const EC_METHOD *EC_GFp_nistp224_method(void); const EC_METHOD *EC_GFp_nistp256_method(void); const EC_METHOD *EC_GFp_nistp521_method(void); const EC_METHOD *EC_GF2m_simple_method(void); EC_GROUP *EC_GROUP_new(const EC_METHOD *meth); void EC_GROUP_free(EC_GROUP *group); void EC_GROUP_clear_free(EC_GROUP *group); int EC_GROUP_copy(EC_GROUP *dst, const EC_GROUP *src); EC_GROUP *EC_GROUP_dup(const EC_GROUP *src); const EC_METHOD *EC_GROUP_method_of(const EC_GROUP *group); int EC_METHOD_get_field_type(const EC_METHOD *meth); int EC_GROUP_set_generator(EC_GROUP *group, const EC_POINT *generator, const BIGNUM *order, const BIGNUM *cofactor); const EC_POINT *EC_GROUP_get0_generator(const EC_GROUP *group); int EC_GROUP_get_order(const EC_GROUP *group, BIGNUM *order, BN_CTX *ctx); int EC_GROUP_get_cofactor(const EC_GROUP *group, BIGNUM *cofactor, BN_CTX *ctx); void EC_GROUP_set_curve_name(EC_GROUP *group, int nid); int EC_GROUP_get_curve_name(const EC_GROUP *group); void EC_GROUP_set_asn1_flag(EC_GROUP *group, int flag); int EC_GROUP_get_asn1_flag(const EC_GROUP *group); void EC_GROUP_set_point_conversion_form(EC_GROUP *group, point_conversion_form_t form); point_conversion_form_t EC_GROUP_get_point_conversion_form(const EC_GROUP *); unsigned char *EC_GROUP_get0_seed(const EC_GROUP *x); size_t EC_GROUP_get_seed_len(const EC_GROUP *); size_t EC_GROUP_set_seed(EC_GROUP *, const unsigned char *, size_t len); int EC_GROUP_set_curve_GFp(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); int EC_GROUP_get_curve_GFp(const EC_GROUP *group, BIGNUM *p, BIGNUM *a, BIGNUM *b, BN_CTX *ctx); int EC_GROUP_set_curve_GF2m(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); int EC_GROUP_get_curve_GF2m(const EC_GROUP *group, BIGNUM *p, BIGNUM *a, BIGNUM *b, BN_CTX *ctx); int EC_GROUP_get_degree(const EC_GROUP *group); int EC_GROUP_check(const EC_GROUP *group, BN_CTX *ctx); int EC_GROUP_check_discriminant(const EC_GROUP *group, BN_CTX *ctx); int EC_GROUP_cmp(const EC_GROUP *a, const EC_GROUP *b, BN_CTX *ctx); EC_GROUP *EC_GROUP_new_curve_GFp(const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); EC_GROUP *EC_GROUP_new_curve_GF2m(const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); EC_GROUP *EC_GROUP_new_by_curve_name(int nid); size_t EC_get_builtin_curves(EC_builtin_curve *r, size_t nitems); EC_POINT *EC_POINT_new(const EC_GROUP *group); void EC_POINT_free(EC_POINT *point); void EC_POINT_clear_free(EC_POINT *point); int EC_POINT_copy(EC_POINT *dst, const EC_POINT *src); EC_POINT *EC_POINT_dup(const EC_POINT *src, const EC_GROUP *group); const EC_METHOD *EC_POINT_method_of(const EC_POINT *point); int EC_POINT_set_to_infinity(const EC_GROUP *group, EC_POINT *point); int EC_POINT_set_Jprojective_coordinates_GFp(const EC_GROUP *group, EC_POINT *p, const BIGNUM *x, const BIGNUM *y, const BIGNUM *z, BN_CTX *ctx); int EC_POINT_get_Jprojective_coordinates_GFp(const EC_GROUP *group, const EC_POINT *p, BIGNUM *x, BIGNUM *y, BIGNUM *z, BN_CTX *ctx); int EC_POINT_set_affine_coordinates_GFp(const EC_GROUP *group, EC_POINT *p, const BIGNUM *x, const BIGNUM *y, BN_CTX *ctx); int EC_POINT_get_affine_coordinates_GFp(const EC_GROUP *group, const EC_POINT *p, BIGNUM *x, BIGNUM *y, BN_CTX *ctx); int EC_POINT_set_compressed_coordinates_GFp(const EC_GROUP *group, EC_POINT *p, const BIGNUM *x, int y_bit, BN_CTX *ctx); int EC_POINT_set_affine_coordinates_GF2m(const EC_GROUP *group, EC_POINT *p, const BIGNUM *x, const BIGNUM *y, BN_CTX *ctx); int EC_POINT_get_affine_coordinates_GF2m(const EC_GROUP *group, const EC_POINT *p, BIGNUM *x, BIGNUM *y, BN_CTX *ctx); int EC_POINT_set_compressed_coordinates_GF2m(const EC_GROUP *group, EC_POINT *p, const BIGNUM *x, int y_bit, BN_CTX *ctx); size_t EC_POINT_point2oct(const EC_GROUP *group, const EC_POINT *p, point_conversion_form_t form, unsigned char *buf, size_t len, BN_CTX *ctx); int EC_POINT_oct2point(const EC_GROUP *group, EC_POINT *p, const unsigned char *buf, size_t len, BN_CTX *ctx); BIGNUM *EC_POINT_point2bn(const EC_GROUP *, const EC_POINT *, point_conversion_form_t form, BIGNUM *, BN_CTX *); EC_POINT *EC_POINT_bn2point(const EC_GROUP *, const BIGNUM *, EC_POINT *, BN_CTX *); char *EC_POINT_point2hex(const EC_GROUP *, const EC_POINT *, point_conversion_form_t form, BN_CTX *); EC_POINT *EC_POINT_hex2point(const EC_GROUP *, const char *, EC_POINT *, BN_CTX *); int EC_POINT_add(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a, const EC_POINT *b, BN_CTX *ctx); int EC_POINT_dbl(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a, BN_CTX *ctx); int EC_POINT_invert(const EC_GROUP *group, EC_POINT *a, BN_CTX *ctx); int EC_POINT_is_at_infinity(const EC_GROUP *group, const EC_POINT *p); int EC_POINT_is_on_curve(const EC_GROUP *group, const EC_POINT *point, BN_CTX *ctx); int EC_POINT_cmp(const EC_GROUP *group, const EC_POINT *a, const EC_POINT *b, BN_CTX *ctx); int EC_POINT_make_affine(const EC_GROUP *group, EC_POINT *point, BN_CTX *ctx); int EC_POINTs_make_affine(const EC_GROUP *group, size_t num, EC_POINT *points[], BN_CTX *ctx); int EC_POINTs_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *n, size_t num, const EC_POINT *p[], const BIGNUM *m[], BN_CTX *ctx); int EC_POINT_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *n, const EC_POINT *q, const BIGNUM *m, BN_CTX *ctx); int EC_GROUP_precompute_mult(EC_GROUP *group, BN_CTX *ctx); int EC_GROUP_have_precompute_mult(const EC_GROUP *group); int EC_GROUP_get_basis_type(const EC_GROUP *); int EC_GROUP_get_trinomial_basis(const EC_GROUP *, unsigned int *k); int EC_GROUP_get_pentanomial_basis(const EC_GROUP *, unsigned int *k1, unsigned int *k2, unsigned int *k3); EC_GROUP *d2i_ECPKParameters(EC_GROUP **, const unsigned char **in, long len); int i2d_ECPKParameters(const EC_GROUP *, unsigned char **out); #define d2i_ECPKParameters_bio(bp,x) ASN1_d2i_bio_of(EC_GROUP,NULL,d2i_ECPKParameters,bp,x) #define i2d_ECPKParameters_bio(bp,x) ASN1_i2d_bio_of_const(EC_GROUP,i2d_ECPKParameters,bp,x) #define d2i_ECPKParameters_fp(fp,x) (EC_GROUP *)ASN1_d2i_fp(NULL, \ (char *(*)())d2i_ECPKParameters,(fp),(unsigned char **)(x)) #define i2d_ECPKParameters_fp(fp,x) ASN1_i2d_fp(i2d_ECPKParameters,(fp), \ (unsigned char *)(x)) int ECPKParameters_print(BIO *bp, const EC_GROUP *x, int off); int ECPKParameters_print_fp(FILE *fp, const EC_GROUP *x, int off); EC_KEY *EC_KEY_new(void); int EC_KEY_get_flags(const EC_KEY *key); void EC_KEY_set_flags(EC_KEY *key, int flags); void EC_KEY_clear_flags(EC_KEY *key, int flags); EC_KEY *EC_KEY_new_by_curve_name(int nid); void EC_KEY_free(EC_KEY *key); EC_KEY *EC_KEY_copy(EC_KEY *dst, const EC_KEY *src); EC_KEY *EC_KEY_dup(const EC_KEY *src); int EC_KEY_up_ref(EC_KEY *key); const EC_GROUP *EC_KEY_get0_group(const EC_KEY *key); int EC_KEY_set_group(EC_KEY *key, const EC_GROUP *group); const BIGNUM *EC_KEY_get0_private_key(const EC_KEY *key); int EC_KEY_set_private_key(EC_KEY *key, const BIGNUM *prv); const EC_POINT *EC_KEY_get0_public_key(const EC_KEY *key); int EC_KEY_set_public_key(EC_KEY *key, const EC_POINT *pub); unsigned EC_KEY_get_enc_flags(const EC_KEY *key); void EC_KEY_set_enc_flags(EC_KEY *eckey, unsigned int flags); point_conversion_form_t EC_KEY_get_conv_form(const EC_KEY *key); void EC_KEY_set_conv_form(EC_KEY *eckey, point_conversion_form_t cform); void *EC_KEY_get_key_method_data(EC_KEY *key, void *(*dup_func)(void *), void (*free_func)(void *), void (*clear_free_func)(void *)); void EC_KEY_insert_key_method_data(EC_KEY *key, void *data, void *(*dup_func)(void *), void (*free_func)(void *), void (*clear_free_func)(void *)); void EC_KEY_set_asn1_flag(EC_KEY *eckey, int asn1_flag); int EC_KEY_precompute_mult(EC_KEY *key, BN_CTX *ctx); int EC_KEY_generate_key(EC_KEY *key); int EC_KEY_check_key(const EC_KEY *key); int EC_KEY_set_public_key_affine_coordinates(EC_KEY *key, BIGNUM *x, BIGNUM *y); EC_KEY *d2i_ECPrivateKey(EC_KEY **key, const unsigned char **in, long len); int i2d_ECPrivateKey(EC_KEY *key, unsigned char **out); EC_KEY *d2i_ECParameters(EC_KEY **key, const unsigned char **in, long len); int i2d_ECParameters(EC_KEY *key, unsigned char **out); EC_KEY *o2i_ECPublicKey(EC_KEY **key, const unsigned char **in, long len); int i2o_ECPublicKey(EC_KEY *key, unsigned char **out); int ECParameters_print(BIO *bp, const EC_KEY *key); int EC_KEY_print(BIO *bp, const EC_KEY *key, int off); int ECParameters_print_fp(FILE *fp, const EC_KEY *key); int EC_KEY_print_fp(FILE *fp, const EC_KEY *key, int off); #define ECParameters_dup(x) ASN1_dup_of(EC_KEY,i2d_ECParameters,d2i_ECParameters,x) #define EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx, nid) \ EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, EVP_PKEY_OP_PARAMGEN, \ EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID, nid, NULL) =head1 DESCRIPTION This library provides an extensive set of functions for performing operations on elliptic curves over finite fields. In general an elliptic curve is one with an equation of the form: y^2 = x^3 + ax + b An B<EC_GROUP> structure is used to represent the definition of an elliptic curve. Points on a curve are stored using an B<EC_POINT> structure. An B<EC_KEY> is used to hold a private/public key pair, where a private key is simply a BIGNUM and a public key is a point on a curve (represented by an B<EC_POINT>). The library contains a number of alternative implementations of the different functions. Each implementation is optimised for different scenarios. No matter which implementation is being used, the interface remains the same. The library handles calling the correct implementation when an interface function is invoked. An implementation is represented by an B<EC_METHOD> structure. The creation and destruction of B<EC_GROUP> objects is described in L<EC_GROUP_new(3)>. Functions for manipulating B<EC_GROUP> objects are described in L<EC_GROUP_copy(3)>. Functions for creating, destroying and manipulating B<EC_POINT> objects are explained in L<EC_POINT_new(3)>, whilst functions for performing mathematical operations and tests on B<EC_POINTs> are covered in L<EC_POINT_add(3)>. For working with private and public keys refer to L<EC_KEY_new(3)>. Implementations are covered in L<EC_GFp_simple_method(3)>. For information on encoding and decoding curve parameters to and from ASN1 see L<d2i_ECPKParameters(3)>. =head1 SEE ALSO L<crypto(3)>, L<EC_GROUP_new(3)>, L<EC_GROUP_copy(3)>, L<EC_POINT_new(3)>, L<EC_POINT_add(3)>, L<EC_KEY_new(3)>, L<EC_GFp_simple_method(3)>, L<d2i_ECPKParameters(3)> =cut
vbloodv/blood
extern/openssl.orig/doc/crypto/ec.pod
Perl
mit
10,952
#!/usr/bin/perl $Path = "/home/bluewand/data/ash"; print "Content-type: text/html\n\n"; print qq! <html> <body bgcolor=white> <font face=arial color=white> <table width=70% height=85% border=0> <TR> <TD valign=middle align=middle> <Table border=0 width=598 height=398 cellspacing=0 cellpadding=0 bgcolor=white bordercolor=#B3B5FF> <TR><TD valign=top><font face=verdana<BR><BR><div align=justify> <center> <BR><img src="http://www.bluewand.com/images/ASHButton2.jpg" border=0><BR><BR> </center> <font face=arial size=-1><div align=justify> The war.... The war has been raging for an eternity. The armoured boots of millions have trampled the once-fertile earth into barren nothingness. The lands have been scorched by flame, corrupted by death. All that is old has been lost. The once powerful cabal nations which made up the western hemisphere have been reduced to a squabbling collection of primitive, decaying city-states. The East is nothing more than a faded memory, burned into the minds of the billions by nuclear flames. <BR><BR> The end of recorded time draws near, as mankind plunges backwards at an accelerating pace. Disease runs rampant, plague after plague ending the lives of countless millions.... And yet, the war rages on, without end in sight. Every hour, thousands more young men and women are sent to the front, never to see their familes again. Factories pour smoke and soot into an already ruined sky, blocking out the sun for weeks at a time. Scientists devote their lives to developing new weapons of destruction, new ways to bring the world to an end at a faster pace. In the darkened streets of the city-states, a different war rages, one not fought by superior numbers, but by technology and skill. The Can-American ELITE program of the mid 21st century has given birth to a new breed of soldier, faster, stronger, more powerful than anything before it. Skilled mercenaries, the remaning ELITEs sell their services to the highest bidder, waging a war of assassination and sabotage against those who they are paid to destroy.<BR><BR> It is into this world which you are born, and it is this world which you must fight to save. There is only one way to prevent the destruction of the planet, and that is through the destruction of the enemy. Ally yourself under the banner of one of the remaining Super-Empires, and give hope to humanity once again.<BR><BR> <center><a href="http://www.bluewand.com/ash/FactionBackground.html">Faction Descriptions</A><BR><BR> <form method=POST action="http://www.bluewand.com/cgi-bin/ash/create.pl"> <table border=0 cellspacing=0 width=80%> <TR> <TD><font face=verdana size=-1>Country Name</TD> <TD><font face=verdana size=-1><input type=text maxsize=20 size=18 name=cname></TD> </TR> <TR> <TD><font face=verdana size=-1>User (login) Name</TD> <TD><font face=verdana size=-1><input type=text maxsize=20 size=18 name=uname></TD> </TR> <TR> <TD><font face=verdana size=-1>Leader Name</TD> <TD><font face=verdana size=-1><input type=text maxsize=20 size=18 name=lname></TD> </TR> <TR> <TD><font face=verdana size=-1>Alignment</TD> <TD><font face=verdana size=-1><select name=alignment><option value=0>Random</option>!; $Val = 1; while ($Val < 4) { open (IN, "$Path/$Val") or print $!; flock (IN, 1); @Numbers[$Val - 1] = <IN>; close (IN); $Total += @Numbers[$Val - 1]; $Val ++; } $Total ++; unless (@Numbers[0] / $Total > 0.35) {print qq!<option value=1>Terran Liberation Army</option>!;} unless (@Numbers[1] / $Total > 0.35) {print qq!<option value=2>Free Republic</option>!;} unless (@Numbers[2] / $Total > 0.35) {print qq!<option value=3>Socialist Federation</option>!;} print "@Numbers<BR>"; print qq! </select></TD> </TR> <TR> <TD><font face=verdana size=-1>Password</TD> <TD><font face=verdana size=-1><input type=password maxsize=20 size=18 name=pword1></TD> </TR> <TR> <TD><font face=verdana size=-1>Confirm</TD> <TD><font face=verdana size=-1><input type=password maxsize=20 size=18 name=pword2></TD> </TR> <TR> <TD><font face=verdana size=-1>E-mail Address</TD> <TD><font face=verdana size=-1><input type=text maxsize=20 size=18 name=email></TD> </TR> </table><BR><BR> <input type=submit name=submit value="Create Account"> </form> </TD> </tR> </table> </TD></TR> </table> </td> </TR> </table> </body> </html> !;
cpraught/arcadian-duck
initial.pl
Perl
mit
4,487
package # Date::Manip::TZ::atsout00; # Copyright (c) 2008-2015 Sullivan Beck. All rights reserved. # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. # This file was automatically generated. Any changes to this file will # be lost the next time 'tzdata' is run. # Generated on: Wed Nov 25 11:33:39 EST 2015 # Data version: tzdata2015g # Code version: tzcode2015g # This module contains data from the zoneinfo time zone database. The original # data was obtained from the URL: # ftp://ftp.iana.org/tz use strict; use warnings; require 5.010000; our (%Dates,%LastRule); END { undef %Dates; undef %LastRule; } our ($VERSION); $VERSION='6.52'; END { undef $VERSION; } %Dates = ( 1 => [ [ [1,1,2,0,0,0],[1,1,1,21,33,52],'-02:26:08',[-2,-26,-8], 'LMT',0,[1890,1,1,2,26,7],[1889,12,31,23,59,59], '0001010200:00:00','0001010121:33:52','1890010102:26:07','1889123123:59:59' ], ], 1890 => [ [ [1890,1,1,2,26,8],[1890,1,1,0,26,8],'-02:00:00',[-2,0,0], 'GST',0,[9999,12,31,0,0,0],[9999,12,30,22,0,0], '1890010102:26:08','1890010100:26:08','9999123100:00:00','9999123022:00:00' ], ], ); %LastRule = ( ); 1;
jkb78/extrajnm
local/lib/perl5/Date/Manip/TZ/atsout00.pm
Perl
mit
1,283
#!/usr/bin/env perl =head1 NAME load_assembly_from_fasta.pl - Populates a core Ensembl DB with FASTA data =head1 SYNOPSIS perl load_assembly_from_fasta.pl [options] fasta_file(s) Options: -h|--help -m|--man -e|--ensembl_registry file -s|--species species_name -a|--assembly_version -co|--coord_system name -ch|--chunk_size size -n|--no_insert =head1 OPTIONS Reads the B<fpc_file>, and uses its data to populate A. the seq_region table and B. the assembly table of the core Ensembl DB. B<-h --help> Print a brief help message and exits. B<-m --man> Print man page and exit B<-r --registry_file> Use this Ensembl registry file for database connection info. Default is <ENSEMBLHOME>/conf/ensembl.registry B<-s --species> Use this species entry from the registry file [REQUIRED]. B<-a --assembly_version> Use this string to indicate the assembly version (def 'unspecified'). B<-co --coord_system> The coordinate system appropriate for the sequences (e.g. clone, scaffold, contig, chromosome). B<-ch --chunk_size> Split the FASTA entries into chunks of this number of basepairs (typically 100000). B<-n --no_insert> Do not make changes to the database. Useful for debug. =head1 DESCRIPTION B<This program> Populates the dna, seq_region and coord_system tables of an 'empty' core Ensembl DB with data provided by one or more fasta files. It also populates various species and assembly-related tables in the meta table of the db. To create an empty ensembl database, first create an appropriately named db from the MySQL client, then load the schema using the file in <ENSEMBL_API_ROOT>/ensembl/table.sql If the B<--chunk_size> argument is provided, the original sequence will be split into seq_region chunks of this size against a sequence_level coord_system of 'chunk'. The mapping from the chunks to the original B<--coord_system> seq_regions will be loaded into the assembly table. This approach is useful for loading whole chromosomes where the length of the sequences are larger than the size of data that can be loaded into the dna table, or sensibly manipulated by the Ensembl API. TODO: Add option to chunk sequences where long strings of 'N' characters are found. Maintained by Will Spooner <whs@ebi.ac.uk> =cut BEGIN { $ENV{'GrameneDir'} ||= '/usr/local/gramene/'; $ENV{'GrameneEnsemblDir'} ||= '/usr/local/gramene_ensembl/'; } use strict; use warnings; use Getopt::Long; use Pod::Usage; use Data::Dumper qw(Dumper); # For debug use DBI; use FindBin qw( $Bin ); use File::Basename qw( dirname ); use vars qw( $BASEDIR ); BEGIN{ # Set the perl libraries. Need a symlink from the gramene-ensembl # directory to an ensembl API distribution $BASEDIR = dirname($Bin); unshift @INC, $BASEDIR.'/ensembl-live/ensembl/modules'; unshift @INC, $BASEDIR.'/ensembl-live/ensembl-compara/modules'; unshift @INC, $BASEDIR.'/bioperl-HEAD'; # ncomment if BioPerl not in path } use Bio::EnsEMBL::Registry; use Bio::EnsEMBL::CoordSystem; use Bio::EnsEMBL::Slice; use Bio::SeqIO::MultiFile; use Bio::DB::Taxonomy; use Bio::Species; use vars qw( $ENS_DBA $SEQ_IO $CS_NAME $CHUNK_SIZE $I $TAXON $VERSION $NOT_SEQ_LEVEL); BEGIN{ #Argument Processing my( $help, $man, $no_insert ); my( $species, $file ); GetOptions ( "help|?" => \$help, "man" => \$man, "no_insert" => \$no_insert, "species=s" => \$species, "assembly_version=s" => \$VERSION, "ensembl_registry=s" => \$file, "coord_system=s" => \$CS_NAME, "chunk_size=s" => \$CHUNK_SIZE, "not_seq_level" => \$NOT_SEQ_LEVEL, ) or pod2usage(2); pod2usage(-verbose => 2) if $man; pod2usage(1) if $help; $file ||= $BASEDIR.'/conf/ensembl.registry'; $VERSION ||= 'unspecified'; $CS_NAME || pod2usage( "\nNeed a coord_system name\n" ); $species || pod2usage( "\nNeed a --species\n" ); @ARGV || pod2usage( "\nNeed the path to FASTA file(s)\n" ); map{ -e $_ || pod2usage( "\nFile $_ does not exist\n" ); -r $_ || pod2usage( "\nCannot read $_\n" ); -f $_ || pod2usage( "\nFile $_ is not plain-text\n" ); -s $_ || pod2usage( "\nFile $_ is empty\n" ); } $file, @ARGV; $I = $no_insert ? 0 : 1; unless( $I ){ warn( "[INFO] Evaluation run - no db changes will be made\n")} # Load the ensembl file Bio::EnsEMBL::Registry->load_all( $file ); $ENS_DBA = Bio::EnsEMBL::Registry->get_DBAdaptor( $species, 'core' ); $ENS_DBA || pod2usage( "\nNo core DB for $species set in $file\n" ); # Load the Fasta file warn( "[INFO] FASTA files: " . join( "\n".(' 'x18), @ARGV ) . "\n" ); $SEQ_IO = new Bio::SeqIO::MultiFile( -format => "fasta", -files => [@ARGV]); # Get taxonomy info for the species my $species_binomial = Bio::EnsEMBL::Registry->get_alias($species); $species_binomial =~ s/_/ /g; # $species_binomial =~ s/scaffold//g; my $db = Bio::DB::Taxonomy->new(-source => 'entrez' ); my $taxonid = $db->get_taxonid( $species_binomial ) || pod2usage( "\nNo NCBI taxon id for $species_binomial". "\nTry using a more recent bioperl version\n" ); $TAXON = $db->get_Taxonomy_Node( -name => $species_binomial ) || pod2usage( "\nNo NCBI taxonomy for $species_binomial\n" ); } #==================== MAIN ==================== # Deal with the taxon and assembly version # &store_taxon_meta( $TAXON ); my $mc = $ENS_DBA->get_MetaContainer; warn( "[INFO] adding assembly.default $VERSION to meta table\n" ); if( $I ){ $mc->store_key_value('assembly.default', $VERSION) } # Get the coord_systems my( $seq_cs, $chunk_cs ) = &get_coord_systems(); my $slice_adaptor = $ENS_DBA->get_adaptor('Slice'); while( my $seq = $SEQ_IO->next_seq ){ my $seq_id = $seq->id; # TODO - use filename if ID is missing if($CS_NAME =~ /chromosome/i){ next unless ($seq_id =~ s/chr(omosome)?_?0*//i);# Strip 'chromsome' prefix from ID }else{ next if ($seq_id =~ s/chr(omosome)?_?0*//i); } #$seq_id =~ s/chr(omosome)?_?0*//i; # Strip 'chromsome' prefix from ID $seq->id( $seq_id ); my $seq_length = $seq->length; warn( "[INFO] Processing $CS_NAME $seq_id ($seq_length bp)\n" ); my $seq_slice = &new_slice( $seq_cs, $seq ); if( $CHUNK_SIZE ){ for( my $start=1; $start<=$seq_length; $start+=$CHUNK_SIZE ){ my $end = $start + $CHUNK_SIZE - 1; if( $end > $seq_length ){ $end = $seq_length } my $chunk_id = "${seq_id}_${start}..${end}"; warn( "[INFO] Processing chunk $chunk_id\n" ); my $chunk_seq = Bio::PrimarySeq->new ( -id => $chunk_id, -seq => $seq->subseq( $start, $end ), ); my $chunk_slice = &new_slice( $chunk_cs, $chunk_seq ); my $asm_slice = $seq_slice->sub_Slice( $start, $end ); if( $I ){ $slice_adaptor->store_assembly( $asm_slice, $chunk_slice ); } } } } #====================================================================== # Takes a Bio::Taxonomy::Node and populates the species # entries in the meta table sub store_taxon_meta{ my $taxon = shift || die( "Need a Bio::Taxonomy::Node" ); my $mc = $ENS_DBA->get_MetaContainer; my $taxid = $taxon->object_id; warn( "[INFO] adding species.taxonomy_id $taxid to meta\n" ); if( $I ){ $mc->store_key_value('species.taxonomy_id', $taxid) } if( my $name = $taxon->common_name ){ warn( "[INFO] adding species.common_name $name to meta\n" ); if( $I ){ $mc->store_key_value('species.common_name', $name) } } foreach my $name( $taxon->classification ){ my $key = 'species.classification'; warn( "[INFO] adding $key $name to meta\n" ); if( $I ){ $mc->store_key_value($key, $name) } } return; } #---------------------------------------------------------------------- # Creates the appropriate coord systems in the DB sub get_coord_systems{ my $csa = $ENS_DBA->get_adaptor('CoordSystem'); my $seq_cs ; my $seq_cs_exist; $seq_cs = $csa->fetch_by_name($CS_NAME); if($seq_cs){ $seq_cs_exist = 1; }else{ $seq_cs = Bio::EnsEMBL::CoordSystem->new ( -name => $CS_NAME, -rank => $CS_NAME =~ /chromosome/i ? 1 : 2, -default => 1, -version => $VERSION, $CHUNK_SIZE ? () : ( $NOT_SEQ_LEVEL ? () : -sequence_level=>1 ), ); } my $chunk_cs; my $chunk_cs_exist; if( $CHUNK_SIZE ){ $chunk_cs = $csa->fetch_by_name('chunk'); if($chunk_cs){ $chunk_cs_exist = 1; }else{ $chunk_cs = Bio::EnsEMBL::CoordSystem->new ( -name => 'chunk', -rank => 3, -default => 1, -version => $VERSION, -sequence_level => 1, ); } } warn( "[INFO] Storing coord_system: $CS_NAME\n" ); if( $I ){ $csa->store($seq_cs) unless $seq_cs_exist; } if( $chunk_cs ){ print( "[INFO] Storing coord_system: chunk ($CHUNK_SIZE bp)\n" ); if( $I ){ $csa->store($chunk_cs) unless $chunk_cs_exist; $csa->store_mapping_path($seq_cs, $chunk_cs ); } } return( $seq_cs, $chunk_cs ); } #---------------------------------------------------------------------- # Creates a new slice based on the given cs_name, name, start and end our $SLA; sub new_slice{ my $cs = shift || die( "Need a coord system" ); my $bioseq = shift || die( "Need a Bio::Seq" ); #printf "seq_region_name=%s, len=%d\n", $bioseq->id, $bioseq->length; my $slice = Bio::EnsEMBL::Slice->new ( -coord_system => $cs, -seq_region_name => $bioseq->id, -start => 1, -end => $bioseq->length, -strand => 1, -version => 1, ); my $seqref; if( $cs->is_sequence_level ){ $seqref = \($bioseq->seq) } if( $I ){ $SLA ||= $ENS_DBA->get_adaptor('Slice'); $SLA->store( $slice, ( $seqref ? $seqref : () ) ) } return $slice; } #====================================================================== 1; __END__
warelab/gramene-ensembl
maize/load-scripts/load-assembly-from-fasta.pl
Perl
mit
10,112
%HAMBRE sugerencias_hambre(P,ComidaSugerida,Lugar) :- % Si no hay comida en el predicado sugerir comida por probabilidad P == [],sugerir(comida(_,_),ComidaSugerida), % Y sugerir lugar por probabilidad segun la comida sugerir(hambre_lugar(ComidaSugerida,_,_),LugarSugerido), % Si no existe el lugar agregar uno, preguntando si quiere o no %((LugarSugerido == [],agregar_lugar_general(ComidaSugerida,comer)); ((LugarSugerido == [],Lugar='false'); % Si Existe el lugar mostrarlo (Lugar = LugarSugerido)); % Si hay comida en el predicado procesar_predicado(P,P2),list_string(P2,ComidaSugerida),agregar_hecho(comida(ComidaSugerida,_)),hora(H,_,_),horario(H,StringHora),agregar_hecho(tiempo(ComidaSugerida,comida,StringHora,_)),sugerir(hambre_lugar(ComidaSugerida,_,_),LugarSugerido), ((LugarSugerido == [],Lugar = 'false'); % Si Existe el lugar mostrarlo (Lugar = LugarSugerido)). consultar_hambre(ComidaFavorita,'') :- hecho_favorito(comida(_,_),ComidaFavorita).
spantons/Goo-agente-inteligente-inferencia-y-conocimiento-prolog
dependencias/hambre.pl
Perl
mit
996
# $Id: ReadLine.pm 2357 2008-06-20 17:41:54Z rcaputo $ package POE::Wheel::ReadLine; use strict; BEGIN { eval { require bytes } and bytes->import; } use vars qw($VERSION); $VERSION = do {my($r)=(q$Revision: 2357 $=~/(\d+)/);sprintf"1.%04d",$r}; use Carp qw( croak carp ); use Symbol qw(gensym); use POE qw( Wheel ); use POSIX (); if ($^O eq "MSWin32") { die "$^O cannot run " . __PACKAGE__; } # Things we'll need to interact with the terminal. use Term::Cap (); use Term::ReadKey qw( ReadKey ReadMode GetTerminalSize ); my $initialised = 0; my $termcap; # Termcap entry. my $tc_bell; # How to ring the terminal. my $tc_visual_bell; # How to ring the terminal. my $tc_has_ce; # Termcap can clear to end of line. # Screen extent. my ($trk_rows, $trk_cols); # Private STDIN and STDOUT. my $stdin = gensym(); open($stdin, "<&STDIN") or die "Can't open private STDIN: $!"; my $stdout = gensym; open($stdout, ">&STDOUT") or die "Can't open private STDOUT: $!"; # Offsets into $self. sub SELF_INPUT () { 0 } sub SELF_CURSOR_INPUT () { 1 } sub SELF_EVENT_INPUT () { 2 } sub SELF_READING_LINE () { 3 } sub SELF_STATE_READ () { 4 } sub SELF_PROMPT () { 5 } sub SELF_HIST_LIST () { 6 } sub SELF_HIST_INDEX () { 7 } sub SELF_INPUT_HOLD () { 8 } sub SELF_KEY_BUILD () { 9 } sub SELF_INSERT_MODE () { 10 } sub SELF_PUT_MODE () { 11 } sub SELF_PUT_BUFFER () { 12 } sub SELF_IDLE_TIME () { 13 } sub SELF_STATE_IDLE () { 14 } sub SELF_HAS_TIMER () { 15 } sub SELF_CURSOR_DISPLAY () { 16 } sub SELF_UNIQUE_ID () { 17 } sub SELF_KEYMAP () { 18 } sub SELF_OPTIONS () { 19 } sub SELF_APP () { 20 } sub SELF_ALL_KEYMAPS () { 21 } sub SELF_PENDING () { 22 } sub SELF_COUNT () { 23 } sub SELF_MARK () { 24 } sub SELF_MARKLIST () { 25 } sub SELF_KILL_RING () { 26 } sub SELF_LAST () { 27 } sub SELF_PENDING_FN () { 28 } sub SELF_SOURCE () { 29 } sub SELF_SEARCH () { 30 } sub SELF_SEARCH_PROMPT () { 31 } sub SELF_SEARCH_MAP () { 32 } sub SELF_PREV_PROMPT () { 33 } sub SELF_SEARCH_DIR () { 34 } sub SELF_SEARCH_KEY () { 35 } sub SELF_UNDO () { 36 } sub CRIMSON_SCOPE_HACK ($) { 0 } #------------------------------------------------------------------------------ # Build a hash of input characters and their "normalized" display # versions. ISO Latin-1 characters (8th bit set "ASCII") are # mishandled. European users, please forgive me. If there's a good # way to handle this-- perhaps this is an interesting use for # Unicode-- please let me know. my (%normalized_character, @normalized_extra_width); #------------------------------------------------------------------------------ # Gather information about the user's terminal. This just keeps # getting uglier. my $ospeed = undef; my $termios = undef; my $term = undef; my $termios = undef; my $tc_left = undef; my $trk_cols = undef; my $trk_rows = undef; sub _curs_left { my $amount = shift; if ($tc_left eq "LE") { $termcap->Tgoto($tc_left, 1, $amount, $stdout); return; } for (1..$amount) { $termcap->Tgoto($tc_left, 1, 1, $stdout); } } our $defuns = { "abort" => \&rl_abort, "accept-line" => \&rl_accept_line, "backward-char" => \&rl_backward_char, "backward-delete-char" => \&rl_backward_delete_char, "backward-kill-line" => \&rl_unix_line_discard, # reuse emacs "backward-kill-word" => \&rl_backward_kill_word, "backward-word" => \&rl_backward_word, "beginning-of-history" => \&rl_beginning_of_history, "beginning-of-line" => \&rl_beginning_of_line, "capitalize-word" => \&rl_capitalize_word, "character-search" => \&rl_character_search, "character-search-backward" => \&rl_character_search_backward, "clear-screen" => \&rl_clear_screen, "complete" => \&rl_complete, "copy-region-as-kill" => \&rl_copy_region_as_kill, "delete-char" => \&rl_delete_char, "delete-horizontal-space" => \&rl_delete_horizontal_space, "digit-argument" => \&rl_digit_argument, "ding" => \&rl_ding, "downcase-word" => \&rl_downcase_word, "dump-key" => \&rl_dump_key, "dump-macros" => \&rl_dump_macros, "dump-variables" => \&rl_dump_variables, "emacs-editing-mode" => \&rl_emacs_editing_mode, "end-of-history" => \&rl_end_of_history, "end-of-line" => \&rl_end_of_line, "forward-char" => \&rl_forward_char, "forward-search-history" => \&rl_forward_search_history, "forward-word" => \&rl_forward_word, "insert-comment" => \&rl_insert_comment, "insert-completions" => \&rl_insert_completions, "insert-macro" => \&rl_insert_macro, "interrupt" => \&rl_interrupt, "isearch-again" => \&rl_isearch_again, "kill-line" => \&rl_kill_line, "kill-region" => \&rl_kill_region, "kill-whole-line" => \&rl_kill_whole_line, "kill-word" => \&rl_kill_word, "next-history" => \&rl_next_history, "non-incremental-forward-search-history" => \&rl_non_incremental_forward_search_history, "non-incremental-reverse-search-history" => \&rl_non_incremental_reverse_search_history, "overwrite-mode" => \&rl_overwrite_mode, "poe-wheel-debug" => \&rl_poe_wheel_debug, "possible-completions" => \&rl_possible_completions, "previous-history" => \&rl_previous_history, "quoted-insert" => \&rl_quoted_insert, "re-read-init-file" => \&rl_re_read_init_file, "redraw-current-line" => \&rl_redraw_current_line, "reverse-search-history" => \&rl_reverse_search_history, "revert-line" => \&rl_revert_line, "search-abort" => \&rl_search_abort, "search-finish" => \&rl_search_finish, "search-key" => \&rl_search_key, "self-insert" => \&rl_self_insert, "set-keymap" => \&rl_set_keymap, "set-mark" => \&rl_set_mark, "tab-insert" => \&rl_ding, # UNIMPLEMENTED "tilde-expand" => \&rl_tilde_expand, "transpose-chars" => \&rl_transpose_chars, "transpose-words" => \&rl_transpose_words, "undo" => \&rl_undo, "unix-line-discard" => \&rl_unix_line_discard, "unix-word-rubout" => \&rl_unix_word_rubout, "upcase-word" => \&rl_upcase_word, "vi-append-eol" => \&rl_vi_append_eol, "vi-append-mode" => \&rl_vi_append_mode, "vi-arg-digit" => \&rl_vi_arg_digit, "vi-change-case" => \&rl_vi_change_case, "vi-change-char" => \&rl_vi_change_char, "vi-change-to" => \&rl_vi_change_to, "vi-char-search" => \&rl_vi_char_search, "vi-column" => \&rl_vi_column, "vi-complete" => \&rl_vi_cmplete, "vi-delete" => \&rl_vi_delete, "vi-delete-to" => \&rl_vi_delete_to, "vi-editing-mode" => \&rl_vi_editing_mode, "vi-end-spec" => \&rl_vi_end_spec, "vi-end-word" => \&rl_vi_end_word, "vi-eof-maybe" => \&rl_vi_eof_maybe, "vi-fetch-history" => \&rl_beginning_of_history, # re-use emacs version "vi-first-print" => \&rl_vi_first_print, "vi-goto-mark" => \&rl_vi_goto_mark, "vi-insert-beg" => \&rl_vi_insert_beg, "vi-insertion-mode" => \&rl_vi_insertion_mode, "vi-match" => \&rl_vi_match, "vi-movement-mode" => \&rl_vi_movement_mode, "vi-next-word" => \&rl_vi_next_word, "vi-prev-word" => \&rl_vi_prev_word, "vi-put" => \&rl_vi_put, "vi-redo" => \&rl_vi_redo, "vi-replace" => \&rl_vi_replace, "vi-search" => \&rl_vi_search, "vi-search-accept" => \&rl_vi_search_accept, "vi-search-again" => \&rl_vi_search_again, "vi-search-key" => \&rl_vi_search_key, "vi-set-mark" => \&rl_vi_set_mark, "vi-spec-beginning-of-line" => \&rl_vi_spec_beginning_of_line, "vi-spec-end-of-line" => \&rl_vi_spec_end_of_line, "vi-spec-first-print" => \&rl_vi_spec_first_print, "vi-spec-forward-char" => \&rl_vi_spec_forward_char, "vi-spec-mark" => \&rl_vi_spec_mark, "vi-spec-word" => \&rl_vi_spec_word, "vi-subst" => \&rl_vi_subst, "vi-tilde-expand" => \&rl_vi_tilde_expand, "vi-undo" => \&rl_undo, # re-use emacs version "vi-yank-arg" => \&rl_vi_yank_arg, "vi-yank-to" => \&rl_vi_yank_to, "yank" => \&rl_yank, "yank-last-arg" => \&rl_yank_last_arg, "yank-nth-arg" => \&rl_yank_nth_arg, "yank-pop" => \&rl_yank_pop, }; # what functions are for counting my @fns_counting = ( 'rl_vi_arg_digit', 'rl_digit_argument', 'rl_universal-argument', ); # what functions are purely for movement... my @fns_movement = ( 'rl_beginning_of_line', 'rl_backward_char', 'rl_forward_char', 'rl_backward_word', 'rl_forward_word', 'rl_end_of_line', 'rl_character_search', 'rl_character_search_backward', 'rl_vi_prev_word', 'rl_vi_next_word', 'rl_vi_goto_mark', 'rl_vi_end_word', 'rl_vi_column', 'rl_vi_first_print', 'rl_vi_char_search', 'rl_vi_spec_char_search', 'rl_vi_spec_end_of_line', 'rl_vi_spec_beginning_of_line', 'rl_vi_spec_first_print', 'rl_vi_spec_word', 'rl_vi_spec_mark', ); # the list of functions that we don't want to record for # later redo usage in vi mode. my @fns_anon = ( 'rl_vi_redo', @fns_counting, @fns_movement, ); my $defaults_inputrc = <<'INPUTRC'; set comment-begin # INPUTRC my $emacs_inputrc = <<'INPUTRC'; C-a: beginning-of-line C-b: backward-char C-c: interrupt C-d: delete-char C-e: end-of-line C-f: forward-char C-g: abort C-h: backward-delete-char C-i: complete C-j: accept-line C-k: kill-line C-l: clear-screen C-m: accept-line C-n: next-history C-p: previous-history C-q: poe-wheel-debug C-r: reverse-search-history C-s: forward-search-history C-t: transpose-chars C-u: unix-line-discard C-v: quoted-insert C-w: unix-word-rubout C-y: yank C-]: character-search C-_: undo del: backward-delete-char rubout: backward-delete-char M-C-g: abort M-C-h: backward-kill-word M-C-i: tab-insert M-C-j: vi-editing-mode M-C-r: revert-line M-C-y: yank-nth-arg M-C-[: complete M-C-]: character-search-backward M-space: set-mark M-#: insert-comment M-&: tilde-expand M-*: insert-completions M--: digit-argument M-.: yank-last-arg M-0: digit-argument M-1: digit-argument M-2: digit-argument M-3: digit-argument M-4: digit-argument M-5: digit-argument M-6: digit-argument M-7: digit-argument M-8: digit-argument M-9: digit-argument M-<: beginning-of-history M->: end-of-history M-?: possible-completions M-b: backward-word M-c: capitalize-word M-d: kill-word M-f: forward-word M-l: downcase-word M-n: non-incremental-forward-search-history M-p: non-incremental-reverse-search-history M-r: revert-line M-t: transpose-words M-u: upcase-word M-y: yank-pop M-\: delete-horizontal-space M-~: tilde-expand M-del: backward-kill-word M-_: yank-last-arg C-xC-r: re-read-init-file C-xC-g: abort C-xDel: backward-kill-line C-xm: dump-macros C-xv: dump-variables C-xk: dump-key home: beginning-of-line end: end-of-line ins: overwrite-mode del: delete-char left: backward-char right: forward-char up: previous-history down: next-history bs: backward-delete-char INPUTRC my $vi_inputrc = <<'INPUTRC'; # VI uses two keymaps, depending on which mode we're in. set keymap vi-insert C-d: vi-eof-maybe C-h: backward-delete-char C-i: complete C-j: accept-line C-m: accept-line C-r: reverse-search-history C-s: forward-search-history C-t: transpose-chars C-u: unix-line-discard C-v: quoted-insert C-w: unix-word-rubout C-y: yank C-[: vi-movement-mode C-_: undo C-?: backward-delete-char set keymap vi-command C-d: vi-eof-maybe C-e: emacs-editing-mode C-g: abort C-h: backward-char C-j: accept-line C-k: kill-line C-l: clear-screen C-m: accept-line C-n: next-history C-p: previous-history C-q: quoted-insert C-r: reverse-search-history C-s: forward-search-history C-t: transpose-chars C-u: unix-line-discard C-v: quoted-insert C-w: unix-word-rubout C-y: yank C-_: vi-undo " ": forward-char "#": insert-comment "$": end-of-line "%": vi-match "&": vi-tilde-expand "*": vi-complete "+": next-history ",": vi-char-search "-": previous-history ".": vi-redo "/": vi-search "0": vi-arg-digit "1": vi-arg-digit "2": vi-arg-digit "3": vi-arg-digit "4": vi-arg-digit "5": vi-arg-digit "6": vi-arg-digit "7": vi-arg-digit "8": vi-arg-digit "9": vi-arg-digit ";": vi-char-search "=": vi-complete "?": vi-search A: vi-append-eol B: vi-prev-word C: vi-change-to D: vi-delete-to E: vi-end-word F: vi-char-search G: vi-fetch-history I: vi-insert-beg N: vi-search-again P: vi-put R: vi-replace S: vi-subst T: vi-char-search U: revert-line W: vi-next-word X: backward-delete-char Y: vi-yank-to "\": vi-complete "^": vi-first-print "_": vi-yank-arg "`": vi-goto-mark a: vi-append-mode b: backward-word c: vi-change-to d: vi-delete-to e: vi-end-word h: backward-char i: vi-insertion-mode j: next-history k: previous-history l: forward-char m: vi-set-mark n: vi-search-again p: vi-put r: vi-change-char s: vi-subst t: vi-char-search w: vi-next-word x: vi-delete y: vi-yank-to "|": vi-column "~": vi-change-case set keymap vi-specification "^": vi-spec-first-print "`": vi-spec-mark "$": vi-spec-end-of-line "0": vi-spec-beginning-of-line "1": vi-arg-digit "2": vi-arg-digit "3": vi-arg-digit "4": vi-arg-digit "5": vi-arg-digit "6": vi-arg-digit "7": vi-arg-digit "8": vi-arg-digit "9": vi-arg-digit w: vi-spec-word t: vi-spec-forward-char INPUTRC my $search_inputrc = <<'INPUTRC'; set keymap isearch C-r: isearch-again C-s: isearch-again set keymap vi-search C-j: vi-search-accept C-m: vi-search-accept INPUTRC #------------------------------------------------------------------------------ # Helper functions. sub _vislength { return 0 unless $_[0]; my $len = length($_[0]); while ($_[0] =~ m{(\\\[.*?\\\])}g) { $len -= length($1); } return $len; } # Wipe the current input line. sub _wipe_input_line { my ($self) = shift; # Clear the current prompt and input, and home the cursor. _curs_left( $self->[SELF_CURSOR_DISPLAY] + _vislength($self->[SELF_PROMPT])); if ( $tc_has_ce ) { print $stdout $termcap->Tputs( 'ce', 1 ); } else { my $wlen = _vislength($self->[SELF_PROMPT]) + _display_width($self->[SELF_INPUT]); print $stdout ( ' ' x $wlen); _curs_left($wlen); } } # Helper to flush any buffered output. sub _flush_output_buffer { my ($self) = shift; # Flush anything buffered. if ( @{ $self->[SELF_PUT_BUFFER] } ) { print $stdout @{ $self->[SELF_PUT_BUFFER] }; # Do not change the interior arrayref, or the event handlers will # become confused. @{ $self->[SELF_PUT_BUFFER] } = (); } } # Set up the prompt and input line like nothing happened. sub _repaint_input_line { my ($self) = shift; my $sp = $self->[SELF_PROMPT]; $sp =~ s{\\[\[\]]}{}g; print $stdout $sp, _normalize($self->[SELF_INPUT]); if ( $self->[SELF_CURSOR_INPUT] != length( $self->[SELF_INPUT]) ) { _curs_left( _display_width($self->[SELF_INPUT]) - $self->[SELF_CURSOR_DISPLAY] ); } } sub _clear_to_end { my ($self) = @_; if (length $self->[SELF_INPUT]) { if ($tc_has_ce) { print $stdout $termcap->Tputs( 'ce', 1 ); } else { my $display_width = _display_width($self->[SELF_INPUT]); print $stdout ' ' x $display_width; _curs_left($display_width); } } } sub _delete_chars { my ($self, $from, $howmany) = @_; # sanitize input if ($howmany < 0) { $from -= $howmany; $howmany = -$howmany; if ($from < 0) { $howmany -= $from; $from = 0; } } my $old = substr($self->[SELF_INPUT], $from, $howmany); my $killed_width = _display_width($old); substr($self->[SELF_INPUT], $from, $howmany) = ''; if ($self->[SELF_CURSOR_INPUT] > $from) { my $newdisp = length(_normalize(substr($self->[SELF_INPUT], 0, $from))); _curs_left($self->[SELF_CURSOR_DISPLAY] - $newdisp); $self->[SELF_CURSOR_INPUT] = $from; $self->[SELF_CURSOR_DISPLAY] = $newdisp; } my $normal_remaining = _normalize(substr($self->[SELF_INPUT], $from)); print $stdout $normal_remaining; my $normal_remaining_length = length($normal_remaining); if ($tc_has_ce) { print $stdout $termcap->Tputs( 'ce', 1 ); } else { print $stdout ' ' x $killed_width; $normal_remaining_length += $killed_width; } _curs_left($normal_remaining_length) if $normal_remaining_length; return $old; } sub _search { my ($self, $rebuild) = @_; if ($rebuild) { $self->_wipe_input_line; $self->_build_search_prompt; } # find in history.... my $found = 0; for ( my $i = $self->[SELF_HIST_INDEX]; $i < scalar @{$self->[SELF_HIST_LIST]} && $i >= 0; $i += $self->[SELF_SEARCH_DIR] ) { next unless $self->[SELF_HIST_LIST]->[$i] =~ /$self->[SELF_SEARCH]/; $self->[SELF_HIST_INDEX] = $i; $self->[SELF_INPUT] = $self->[SELF_HIST_LIST]->[$i]; $self->[SELF_CURSOR_INPUT] = 0; $self->[SELF_CURSOR_DISPLAY] = 0; $self->[SELF_UNDO] = [ $self->[SELF_INPUT], 0, 0 ]; # reset undo info $found++; last; } $self->rl_ding unless $found; $self->_repaint_input_line; } # Return a normalized version of a string. This includes destroying # 8th-bit-set characters, turning them into strange multi-byte # sequences. Apologies to everyone; please let me know of a portable # way to deal with this. sub _normalize { local $_ = shift; s/([^ -~])/$normalized_character{$1}/g; return $_; } sub _readable_key { my ($raw_key) = @_; my @text = (); foreach my $l (split(//, $raw_key)) { if (ord($l) == 0x1B) { push(@text, 'Meta-'); next; } if (ord($l) < 32) { push(@text, 'Control-' . chr(ord($l)+64)); next; } if (ord($l) > 127) { my $l = ord($l)-128; if ($l < 32) { $l = "Control-" . chr($l+64); } push(@text, 'Meta-' . chr($l)); next; } if (ord($l) == 127) { push @text, "^?"; next; } push(@text, $l); } return join("", @text); } # Calculate the display width of a string. The display width is # sometimes wider than the actual string because some characters are # represented on the terminal as multiple characters. sub _display_width { local $_ = shift; my $width = length; $width += $normalized_extra_width[ord] foreach (m/([\x00-\x1F\x7F-\xFF])/g); return $width; } sub _build_search_prompt { my ($self) = @_; $self->[SELF_PROMPT] = $self->[SELF_SEARCH_PROMPT]; $self->[SELF_PROMPT] =~ s{%s}{$self->[SELF_SEARCH]}; } sub _global_init { return if $initialised; # Get the terminal speed for Term::Cap. $termios = POSIX::Termios->new(); $termios->getattr(); $ospeed = $termios->getospeed() || eval { POSIX::B38400() } || 0; # Get the current terminal's capabilities. $term = $ENV{TERM} || 'vt100'; $termcap = Term::Cap->Tgetent( { TERM => $term, OSPEED => $ospeed } ); die "could not find termcap entry for ``$term'': $!" unless defined $termcap; # Require certain capabilities. $termcap->Trequire( qw( cl ku kd kl kr) ); # Cursor movement. $tc_left = "LE"; eval { $termcap->Trequire($tc_left) }; if ($@) { $tc_left = "le"; eval { $termcap->Trequire($tc_left) }; if ($@) { # try out to see if we have a better terminfo defun. # it may well not work (hence eval the lot), but it's worth a shot eval { my @tc = `infocmp -C $term`; chomp(@tc); splice(@tc, 0, 1); # remove header line $ENV{TERMCAP} = join("", @tc); $termcap = Term::Cap->Tgetent( { TERM => $term, OSPEED => $ospeed } ); $termcap->Trequire($tc_left); }; } die "POE::Wheel::ReadLine requires a termcap that supports LE or le" if $@; } # Terminal size. # We initialize the values once on startup, # and then from then on, we check them on every entry into # the input state engine (so that we have valid values) and # before handing control back to the user (so that they get # an up-to-date value). eval { ($trk_cols, $trk_rows) = GetTerminalSize($stdout) }; ($trk_cols, $trk_rows) = (80, 25) if $@; # Configuration... # Some things are optional. eval { $termcap->Trequire( 'ce' ) }; $tc_has_ce = 1 unless $@; # o/` You can ring my bell, ring my bell. o/` my $bell = $termcap->Tputs( bl => 1 ); $bell = $termcap->Tputs( vb => 1 ) unless defined $bell; $tc_bell = (defined $bell) ? $bell : ''; $bell = $termcap->Tputs( vb => 1 ) || ''; $tc_visual_bell = $bell; my $convert_meta = 1; for (my $ord = 0; $ord < 256; $ord++) { my $str = chr($ord); if ($ord > 127) { if ($convert_meta) { $str = "^["; if (($ord - 128) < 32) { $str .= "^" . lc(chr($ord-128+64)); } else { $str .= lc(chr($ord-128)); } } else { $str = sprintf "<%2x>", $ord; } } elsif ($ord < 32) { $str = '^' . lc(chr($ord+64)); } elsif ($ord == 127) { $str = "^?"; } $normalized_character{chr($ord)} = $str; $normalized_extra_width[$ord] = length ( $str ) - 1; } $initialised++; } #------------------------------------------------------------------------------ # The methods themselves. # Create a new ReadLine wheel. sub new { my $proto = shift; my $class = ref($proto) || $proto; my %params = @_; croak "$class requires a working Kernel" unless defined $poe_kernel; my $input_event = delete $params{InputEvent}; croak "$class requires an InputEvent parameter" unless defined $input_event; my $put_mode = delete $params{PutMode}; $put_mode = 'idle' unless defined $put_mode; croak "$class PutMode must be either 'immediate', 'idle', or 'after'" unless $put_mode =~ /^(immediate|idle|after)$/; my $idle_time = delete $params{IdleTime}; $idle_time = 2 unless defined $idle_time; my $app = delete($params{AppName}) || delete($params{appname}); delete $params{appname}; # in case AppName was present $app ||= 'poe-readline'; if (scalar keys %params) { carp( "unknown parameters in $class constructor call: ", join(', ', keys %params) ); } my $self = undef; if (ref $proto) { $self = bless [], $class; @$self = @$proto; $self->[SELF_SOURCE] = $proto; # ensure we're not bound to the old handler $poe_kernel->select_read($stdin); } else { $self = bless [ '', # SELF_INPUT 0, # SELF_CURSOR_INPUT $input_event, # SELF_EVENT_INPUT 0, # SELF_READING_LINE undef, # SELF_STATE_READ '>', # SELF_PROMPT [ ], # SELF_HIST_LIST 0, # SELF_HIST_INDEX '', # SELF_INPUT_HOLD '', # SELF_KEY_BUILD 1, # SELF_INSERT_MODE $put_mode, # SELF_PUT_MODE [ ], # SELF_PUT_BUFFER $idle_time, # SELF_IDLE_TIME undef, # SELF_STATE_IDLE 0, # SELF_HAS_TIMER 0, # SELF_CURSOR_DISPLAY &POE::Wheel::allocate_wheel_id(), # SELF_UNIQUE_ID undef, # SELF_KEYMAP { }, # SELF_OPTIONS $app, # SELF_APP {}, # SELF_ALL_KEYMAPS undef, # SELF_PENDING 0, # SELF_COUNT 0, # SELF_MARK {}, # SELF_MARKLIST [], # SELF_KILL_RING '', # SELF_LAST undef, # SELF_PENDING_FN undef, # SELF_SOURCE '', # SELF_SEARCH undef, # SELF_SEARCH_PROMPT undef, # SELF_SEARCH_MAP '', # SELF_PREV_PROMPT 0, # SELF_SEARCH_DIR '', # SELF_SEARCH_KEY [], # SELF_UNDO ], $class; _global_init(); $self->rl_re_read_init_file(); } # Turn off $stdout buffering. select((select($stdout), $| = 1)[0]); # Set up the event handlers. Idle goes first. $self->[SELF_STATE_IDLE] = ( ref($self) . "(" . $self->[SELF_UNIQUE_ID] . ") -> input timeout" ); $poe_kernel->state($self->[SELF_STATE_IDLE], $self, '_idle_state'); $self->[SELF_STATE_READ] = ( ref($self) . "(" . $self->[SELF_UNIQUE_ID] . ") -> select read" ); $poe_kernel->state($self->[SELF_STATE_READ], $self, '_read_state'); return $self; } #------------------------------------------------------------------------------ # Destroy the ReadLine wheel. Clean up the terminal. sub DESTROY { my $self = shift; # Stop selecting on the handle. $poe_kernel->select($stdin); # Detach our tentacles from the parent session. if ($self->[SELF_STATE_READ]) { $poe_kernel->state($self->[SELF_STATE_READ]); $self->[SELF_STATE_READ] = undef; } if ($self->[SELF_STATE_IDLE]) { $poe_kernel->alarm($self->[SELF_STATE_IDLE]); $poe_kernel->state($self->[SELF_STATE_IDLE]); $self->[SELF_STATE_IDLE] = undef; } # tell the terminal that we want to leave 'application' mode print $termcap->Tputs('ke' => 1) if $termcap->Tputs('ke'); # Restore the console. ReadMode('restore'); &POE::Wheel::free_wheel_id($self->[SELF_UNIQUE_ID]); } #------------------------------------------------------------------------------ # Redefine the idle handler. This also uses stupid closure tricks. # See the comments for &_define_read_state for more information about # these closure tricks. sub _idle_state { my ($self) = $_[OBJECT]; if (@{$self->[SELF_PUT_BUFFER]}) { $self->_wipe_input_line; $self->_flush_output_buffer; $self->_repaint_input_line; } # No more timer. $self->[SELF_HAS_TIMER] = 0; } sub _read_state { my ($self, $k) = @_[OBJECT, KERNEL]; # Read keys, non-blocking, as long as there are some. while (defined(my $raw_key = ReadKey(-1))) { # Not reading a line; discard the input. next unless $self->[SELF_READING_LINE]; # Update the timer on significant input. if ( $self->[SELF_PUT_MODE] eq 'idle' ) { $k->delay( $self->[SELF_STATE_IDLE], $self->[SELF_IDLE_TIME] ); $self->[SELF_HAS_TIMER] = 1; } push( @{$self->[SELF_UNDO]}, [ $self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT], $self->[SELF_CURSOR_DISPLAY] ] ); # Build-multi character codes and make the keystroke printable. $self->[SELF_KEY_BUILD] .= $raw_key; $raw_key = $self->[SELF_KEY_BUILD]; my $key = _normalize($raw_key); if ($self->[SELF_PENDING_FN]) { my $old = $self->[SELF_INPUT]; my $oldref = $self->[SELF_PENDING_FN]; push( @{$self->[SELF_UNDO]}, [ $old, $self->[SELF_CURSOR_INPUT], $self->[SELF_CURSOR_DISPLAY] ] ); &{$self->[SELF_PENDING_FN]}($key, $raw_key); pop(@{$self->[SELF_UNDO]}) if ($old eq $self->[SELF_INPUT]); $self->[SELF_KEY_BUILD] = ''; if ($self->[SELF_PENDING_FN] && "$self->[SELF_PENDING_FN]" eq $oldref) { $self->[SELF_PENDING_FN] = undef; } next; } # Keep glomming keystrokes until they stop existing in the # hash of meta prefixes. next if exists $self->[SELF_KEYMAP]->{prefix}->{$raw_key}; # PROCESS KEY my $old = $self->[SELF_INPUT]; push( @{$self->[SELF_UNDO]}, [ $old, $self->[SELF_CURSOR_INPUT], $self->[SELF_CURSOR_DISPLAY] ] ); $self->[SELF_KEY_BUILD] = ''; $self->_apply_key($key, $raw_key); pop(@{$self->[SELF_UNDO]}) if ($old eq $self->[SELF_INPUT]); } } sub _apply_key { my ($self, $key, $raw_key) = @_; my $mapping = $self->[SELF_KEYMAP]; my $fn = $mapping->{default}; if (exists $mapping->{binding}->{$raw_key}) { $fn = $mapping->{binding}->{$raw_key}; } # print "\r\ninvoking $fn for $key\r\n";$self->_repaint_input_line; if ($self->[SELF_COUNT] && !grep { $_ eq $fn } @fns_counting) { $self->[SELF_COUNT] = int($self->[SELF_COUNT]); $self->[SELF_COUNT] ||= 1; while ($self->[SELF_COUNT] > 0) { if (ref $fn) { $self->$fn($key, $raw_key); } else { &{$defuns->{$fn}}($self, $key, $raw_key); } $self->[SELF_COUNT]--; } $self->[SELF_COUNT] = ""; } else { if (ref $fn) { $self->$fn($key, $raw_key); } else { &{$defuns->{$fn}}($self, $key, $raw_key); } } $self->[SELF_LAST] = $fn unless grep { $_ eq $fn } @fns_anon; } # Send a prompt; get a line. sub get { my ($self, $prompt) = @_; # Already reading a line here, people. Sheesh! return if $self->[SELF_READING_LINE]; # recheck the terminal size every prompt, in case the size # has changed eval { ($trk_cols, $trk_rows) = GetTerminalSize($stdout) }; ($trk_cols, $trk_rows) = (80, 25) if $@; ReadMode('ultra-raw'); # Tell the terminal that we want to be in 'application' mode. print $termcap->Tputs('ks' => 1) if $termcap->Tputs('ks'); # Set up for the read. $self->[SELF_READING_LINE] = 1; $self->[SELF_PROMPT] = $prompt; $self->[SELF_INPUT] = ''; $self->[SELF_CURSOR_INPUT] = 0; $self->[SELF_CURSOR_DISPLAY] = 0; $self->[SELF_HIST_INDEX] = @{$self->[SELF_HIST_LIST]}; $self->[SELF_INSERT_MODE] = 1; $self->[SELF_UNDO] = []; $self->[SELF_LAST] = ''; # Watch the filehandle. $poe_kernel->select($stdin, $self->[SELF_STATE_READ]); my $sp = $prompt; $sp =~ s{\\[\[\]]}{}g; print $stdout $sp; } # Write a line on the terminal. sub put { my $self = shift; my @lines = map { $_ . "\x0D\x0A" } @_; # Write stuff immediately under certain conditions: (1) The wheel is # in immediate mode. (2) The wheel currently isn't reading a line. # (3) The wheel is in idle mode, and there. if ( $self->[SELF_PUT_MODE] eq 'immediate' or !$self->[SELF_READING_LINE] or ( $self->[SELF_PUT_MODE] eq 'idle' and !$self->[SELF_HAS_TIMER] ) ) { # Only clear the input line if we're reading input already $self->_wipe_input_line if ($self->[SELF_READING_LINE]); # Print the new stuff. $self->_flush_output_buffer; print $stdout @lines; # Only repaint the input if we're reading a line. $self->_repaint_input_line if ($self->[SELF_READING_LINE]); return; } # Otherwise buffer stuff. push @{$self->[SELF_PUT_BUFFER]}, @lines; # Set a timer, if timed. if ( $self->[SELF_PUT_MODE] eq 'idle' and !$self->[SELF_HAS_TIMER] ) { $poe_kernel->delay( $self->[SELF_STATE_IDLE], $self->[SELF_IDLE_TIME] ); $self->[SELF_HAS_TIMER] = 1; } } # Clear the screen. sub clear { my $self = shift; $termcap->Tputs( cl => 1, $stdout ); } sub terminal_size { return ($trk_cols, $trk_rows); } # Add things to the edit history. sub add_history { my $self = shift; push @{$self->[SELF_HIST_LIST]}, @_; } # RCC 2008-06-15. Backwards compatibility. *addhistory = *add_history; sub get_history { my $self = shift; return @{$self->[SELF_HIST_LIST]}; } # RCC 2008-06-15. Backwards compatibility. *GetHistory = *get_history; sub write_history { my ($self, $file) = @_; $file ||= "$ENV{HOME}/.history"; open(HIST, ">$file") || return undef; print HIST join("\n", @{$self->[SELF_HIST_LIST]}) . "\n"; close(HIST); return 1; } # RCC 2008-06-15. Backwards compatibility. *WriteHistory = *write_history; sub read_history { my ($self, $file, $from, $to) = @_; $from ||= 0; $to = -1 unless defined $to; $file ||= "$ENV{HOME}/.history"; open(HIST, $file) or return undef; my @hist = <HIST>; close(HIST); my $line = 0; foreach my $h (@hist) { chomp($h); $self->add_history($h) if ($line >= $from && ($to < $from || $line <= $to)); $line++; } return 1; } # RCC 2008-06-15. Backwards compatibility. *ReadHistory = *read_history; sub history_truncate_file { my ($self, $file, $lines) = @_; $lines ||= 0; $file ||= "$ENV{HOME}/.history"; open(HIST, $file) or return undef; my @hist = <HIST>; close(HIST); chomp(@hist); if ((scalar @hist) > $lines) { open(HIST, ">$file") or return undef; if ($lines) { splice(@hist, 0, (scalar @hist)-$lines); @{$self->[SELF_HIST_LIST]} = @hist; print HIST "$_\n" foreach @hist; } else { @{$self->[SELF_HIST_LIST]} = (); } close(HIST); } return 1; } # Get the wheel's ID. sub ID { return $_[0]->[SELF_UNIQUE_ID]; } sub attribs { my ($self) = @_; return $self->[SELF_OPTIONS]; } # RCC 2008-06-15. Backwards compatibility. *Attribs = *attribs; sub option { my ($self, $arg) = @_; $arg = lc($arg); return "" unless exists $self->[SELF_OPTIONS]->{$arg}; return $self->[SELF_OPTIONS]->{$arg}; } sub _init_keymap { my ($self, $default, @names) = @_; my $name = $names[0]; if (!exists $defuns->{$default}) { die("cannot initialise keymap $name, since default function $default is unknown") } my $map = POE::Wheel::ReadLine::Keymap->init( default => $default, name => $name, termcap => $termcap ); foreach my $n (@names) { $self->[SELF_ALL_KEYMAPS]->{$n} = $map; } return $map; } sub rl_re_read_init_file { my ($self) = @_; $self->_init_keymap('self-insert', 'emacs'); $self->_init_keymap('ding', 'vi-command', 'vi'); $self->_init_keymap('self-insert', 'vi-insert'); # searching my $isearch = $self->_init_keymap('search-finish', 'isearch'); my $vi_search = $self->_init_keymap('search-finish', 'vi-search'); $self->_parse_inputrc($search_inputrc); # A keymap to take the VI range specification commands # used by the -to commands (e.g. change-to, etc) $self->_init_keymap('vi-end-spec', 'vi-specification'); $self->_parse_inputrc($defaults_inputrc); $self->rl_set_keymap('vi'); $self->_parse_inputrc($vi_inputrc); $self->rl_set_keymap('emacs'); $self->_parse_inputrc($emacs_inputrc); my $personal = exists $ENV{INPUTRC} ? $ENV{INPUTRC} : "$ENV{HOME}/.inputrc"; foreach my $file ($personal) { my $input = ""; if (open(IN, $file)) { local $/ = undef; $input = <IN>; close(IN); $self->_parse_inputrc($input); } } if (!$self->option('editing-mode')) { $self->[SELF_OPTIONS]->{'editing-mode'} = 'emacs'; } if ($self->option('editing-mode') eq 'vi') { # by default, start in insert mode already $self->rl_set_keymap('vi-insert'); } my $isearch_term = $self->option('isearch-terminators') || 'C-[ C-J'; foreach my $key (split(/\s+/, $isearch_term)) { $isearch->bind_key($key, 'search-abort'); } foreach my $key (ord(' ') .. ord('~')) { $isearch->bind_key('"' . chr($key) . '"', 'search-key'); $vi_search->bind_key('"' . chr($key) . '"', 'vi-search-key'); } } sub _parse_inputrc { my ($self, $input, $depth) = @_; $depth ||= 0; my @cond = (); # allows us to nest conditionals. foreach my $line (split(/\n+/, $input)) { next if $line =~ /^#/; if ($line =~ /^\$(.*)/) { my (@parms) = split(/[ \t+=]/,$1); if ($parms[0] eq 'if') { my $bool = 0; if ($parms[1] eq 'mode') { if ($self->option('editing-mode') eq $parms[2]) { $bool = 1; } } elsif ($parms[1] eq 'term') { my ($half, $full) = ($ENV{TERM} =~ /^([^-]*)(-.*)?$/); if ($half eq $parms[2] || ($full && $full eq $parms[2])) { $bool = 1; } } elsif ($parms[1] eq $self->[SELF_APP]) { $bool = 1; } push(@cond, $bool); } elsif ($parms[0] eq 'else') { $cond[$#cond] = not $cond[$#cond]; } elsif ($parms[0] eq 'endif') { pop(@cond); } elsif ($parms[0] eq 'include') { if ($depth > 10) { print STDERR "WARNING: ignoring ``include $parms[1] directive, since we're too deep''"; } else { my $fh = gensym; if (open $fh, "< $parms[1]\0") { my $contents = do { local $/; <$fh> }; close $fh; $self->_parse_inputrc($contents, $depth+1); } } } } else { next if (scalar @cond and not $cond[$#cond]); if ($line =~ /^set\s+([\S]+)\s+([\S]+)/) { my ($var,$val) = ($1, $2); $self->[SELF_OPTIONS]->{lc($var)} = $val; my $fn = "rl_set_" . lc($var); $fn =~ s{-}{_}g; if ($self->can($fn)) { $self->$fn($self->[SELF_OPTIONS]->{$var}); } } elsif ($line =~ /^([^:]+):\s*(.*)/) { my ($seq, $fn) = ($1, lc($2)); chomp($fn); $self->[SELF_KEYMAP]->bind_key($seq, $fn); } } } } # take a key and output it in a form nice to read... sub _dump_key_line { my ($self, $key, $raw_key) = @_; if (exists $self->[SELF_KEYMAP]->{prefix}->{$raw_key}) { $self->[SELF_PENDING_FN] = sub { my ($k, $rk) = @_; $self->_dump_key_line($key.$k, $raw_key.$rk); }; return; } my $fn = $self->[SELF_KEYMAP]->{default}; if (exists $self->[SELF_KEYMAP]->{binding}->{$raw_key}) { $fn = $self->[SELF_KEYMAP]->{binding}->{$raw_key}; } if (ref $fn) { $fn = "[coderef]"; } print "\x0D\x0A" . _readable_key($raw_key) . ": " . $fn . "\x0D\x0A"; $self->_repaint_input_line; } sub bind_key { my ($self, $seq, $fn, $map) = @_; $map ||= $self->[SELF_KEYMAP]; $map->bind_key($seq, $fn); } sub add_defun { my ($self, $name, $fn) = @_; $defuns->{$name} = $fn; } # ----------------------------------------------------- # Any variable assignments that we care about # ----------------------------------------------------- sub rl_set_keymap { my ($self, $arg) = @_; $arg = lc($arg); if (exists $self->[SELF_ALL_KEYMAPS]->{$arg}) { $self->[SELF_KEYMAP] = $self->[SELF_ALL_KEYMAPS]->{$arg}; $self->[SELF_OPTIONS]->{keymap} = $self->[SELF_KEYMAP]->{name}; } # always reset overstrike mode on keymap change $self->[SELF_INSERT_MODE] = 1; } # ---------------------------------------------------- # From here on, we have the helper functions which can # be bound to keys. The functions are named after the # readline counterparts. # ---------------------------------------------------- sub rl_self_insert { my ($self, $key, $raw_key) = @_; if ($self->[SELF_CURSOR_INPUT] < length($self->[SELF_INPUT])) { if ($self->[SELF_INSERT_MODE]) { # Insert. my $normal = _normalize(substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT])); substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT], 0) = $raw_key; print $stdout $key, $normal; $self->[SELF_CURSOR_INPUT] += length($raw_key); $self->[SELF_CURSOR_DISPLAY] += length($key); _curs_left(length($normal)); } else { # Overstrike. my $replaced_width = _display_width( substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT], length($raw_key)) ); substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT], length($raw_key)) = $raw_key; print $stdout $key; $self->[SELF_CURSOR_INPUT] += length($raw_key); $self->[SELF_CURSOR_DISPLAY] += length($key); # Expand or shrink the display if unequal replacement. if (length($key) != $replaced_width) { my $rest = _normalize(substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT])); # Erase trailing screen cruft if it's shorter. if (length($key) < $replaced_width) { $rest .= ' ' x ($replaced_width - length($key)); } print $stdout $rest; _curs_left(length($rest)); } } } else { # Append. print $stdout $key; $self->[SELF_INPUT] .= $raw_key; $self->[SELF_CURSOR_INPUT] += length($raw_key); $self->[SELF_CURSOR_DISPLAY] += length($key); } } sub rl_insert_macro { my ($self, $key) = @_; my $macro = $self->[SELF_KEYMAP]->{macros}->{$key}; $macro =~ s{\\a}{$tc_bell}g; $macro =~ s{\\r}{\r}g; $macro =~ s{\\n}{\n}g; $macro =~ s{\\t}{\t}g; $self->rl_self_insert($macro, $macro); } sub rl_insert_comment { my ($self) = @_; my $comment = $self->option('comment-begin'); $self->_wipe_input_line; if ($self->[SELF_COUNT]) { if (substr($self->[SELF_INPUT], 0, length($comment)) eq $comment) { substr($self->[SELF_INPUT], 0, length($comment)) = ""; } else { $self->[SELF_INPUT] = $comment . $self->[SELF_INPUT]; } $self->[SELF_COUNT] = 0; } else { $self->[SELF_INPUT] = $comment . $self->[SELF_INPUT]; } $self->_repaint_input_line; $self->rl_accept_line; } sub rl_revert_line { my ($self) = @_; return $self->rl_ding unless scalar @{$self->[SELF_UNDO]}; $self->_wipe_input_line; ( $self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT], $self->[SELF_CURSOR_DISPLAY] ) = @{$self->[SELF_UNDO]->[0]}; $self->[SELF_UNDO] = []; $self->_repaint_input_line; } sub rl_yank_last_arg { my ($self) = @_; if ($self->[SELF_HIST_INDEX] == 0) { return $self->rl_ding; } if ($self->[SELF_COUNT]) { return &rl_yank_nth_arg; } my $prev = $self->[SELF_HIST_LIST]->[$self->[SELF_HIST_INDEX]-1]; my ($arg) = ($prev =~ m{(\S+)$}); $self->rl_self_insert($arg, $arg); 1; } sub rl_yank_nth_arg { my ($self) = @_; if ($self->[SELF_HIST_INDEX] == 0) { return $self->rl_ding; } my $prev = $self->[SELF_HIST_LIST]->[$self->[SELF_HIST_INDEX]-1]; my @args = split(/\s+/, $prev); my $pos = $self->[SELF_COUNT] || 1; $self->[SELF_COUNT] = 0; if ($pos < 0) { $pos = (scalar @args) + $pos; } if ($pos > scalar @args || $pos < 0) { return $self->rl_ding; } $self->rl_self_insert($args[$pos], $args[$pos]); } sub rl_dump_key { my ($self) = @_; $self->[SELF_PENDING_FN] = sub { my ($k,$rk) = @_; $self->_dump_key_line($k, $rk) }; } sub rl_dump_macros { my ($self) = @_; print $stdout "\x0D\x0A"; my $c = 0; foreach my $macro (keys %{$self->[SELF_KEYMAP]->{macros}}) { print $stdout '"' . _normalize($macro) . "\": \"$self->[SELF_KEYMAP]->{macros}->{$macro}\"\x0D\x0A"; $c++; } if (!$c) { print "# no macros defined\x0D\x0A"; } $self->_repaint_input_line; } sub rl_dump_variables { my ($self) = @_; print $stdout "\x0D\x0A"; my $c = 0; foreach my $var (keys %{$self->[SELF_OPTIONS]}) { print $stdout "set $var $self->[SELF_OPTIONS]->{$var}\x0D\x0A"; $c++; } if (!$c) { print "# no variables defined\x0D\x0A"; } $self->_repaint_input_line; } sub rl_set_mark { my ($self) = @_; if ($self->[SELF_COUNT]) { $self->[SELF_MARK] = $self->[SELF_COUNT]; } else { $self->[SELF_MARK] = $self->[SELF_CURSOR_INPUT]; } $self->[SELF_COUNT] = 0; } sub rl_digit_argument { my ($self, $key) = @_; $self->[SELF_COUNT] .= $key; } sub rl_beginning_of_line { my ($self, $key) = @_; if ($self->[SELF_CURSOR_INPUT]) { _curs_left($self->[SELF_CURSOR_DISPLAY]); $self->[SELF_CURSOR_DISPLAY] = $self->[SELF_CURSOR_INPUT] = 0; } } sub rl_end_of_line { my ($self, $key) = @_; my $max = length($self->[SELF_INPUT]); $max-- if ($self->[SELF_KEYMAP]->{name} =~ /vi/); if ($self->[SELF_CURSOR_INPUT] < $max) { my $right_string = substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]); print _normalize($right_string); my $right = _display_width($right_string); if ($self->[SELF_KEYMAP]->{name} =~ /vi/) { $self->[SELF_CURSOR_DISPLAY] += $right - 1; $self->[SELF_CURSOR_INPUT] = length($self->[SELF_INPUT]) - 1; _curs_left(1); } else { $self->[SELF_CURSOR_DISPLAY] += $right; $self->[SELF_CURSOR_INPUT] = length($self->[SELF_INPUT]); } } } sub rl_backward_char { my ($self, $key) = @_; if ($self->[SELF_CURSOR_INPUT]) { $self->[SELF_CURSOR_INPUT]--; my $left = _display_width(substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT], 1)); _curs_left($left); $self->[SELF_CURSOR_DISPLAY] -= $left; } else { $self->rl_ding; } } sub rl_forward_char { my ($self, $key) = @_; my $max = length($self->[SELF_INPUT]); $max-- if ($self->[SELF_KEYMAP]->{name} =~ /vi/); if ($self->[SELF_CURSOR_INPUT] < $max) { my $normal = _normalize(substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT], 1)); print $stdout $normal; $self->[SELF_CURSOR_INPUT]++; $self->[SELF_CURSOR_DISPLAY] += length($normal); } else { $self->rl_ding; } } sub rl_forward_word { my ($self, $key) = @_; if (substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]) =~ /^(\W*\w+)/) { $self->[SELF_CURSOR_INPUT] += length($1); my $right = _display_width($1); print _normalize($1); $self->[SELF_CURSOR_DISPLAY] += $right; } else { $self->rl_ding; } } sub rl_backward_word { my ($self, $key) = @_; if (substr($self->[SELF_INPUT], 0, $self->[SELF_CURSOR_INPUT]) =~ /(\w+\W*)$/) { $self->[SELF_CURSOR_INPUT] -= length($1); my $left = _display_width($1); _curs_left($left); $self->[SELF_CURSOR_DISPLAY] -= $left; } else { $self->rl_ding; } } sub rl_backward_kill_word { my ($self) = @_; if ($self->[SELF_CURSOR_INPUT]) { substr($self->[SELF_INPUT], 0, $self->[SELF_CURSOR_INPUT]) =~ /(\w*\W*)$/; my $kill = $self->_delete_chars($self->[SELF_CURSOR_INPUT] - length($1), length($1)); push(@{$self->[SELF_KILL_RING]}, $kill); } else { $self->rl_ding; } } sub rl_kill_region { my ($self) = @_; my $kill = $self->_delete_chars($self->[SELF_CURSOR_INPUT], $self->[SELF_CURSOR_INPUT] - $self->[SELF_MARK]); push(@{$self->[SELF_KILL_RING]}, $kill); } sub rl_kill_word { my ($self, $key) = @_; if ($self->[SELF_CURSOR_INPUT] < length($self->[SELF_INPUT])) { substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]) =~ /^(\W*\w*\W*)/; my $kill = $self->_delete_chars($self->[SELF_CURSOR_INPUT], length($1)); push(@{$self->[SELF_KILL_RING]}, $kill); } else { $self->rl_ding; } } sub rl_kill_line { my ($self, $key) = @_; if ($self->[SELF_CURSOR_INPUT] < length($self->[SELF_INPUT])) { my $kill = $self->_delete_chars($self->[SELF_CURSOR_INPUT], length($self->[SELF_INPUT]) - $self->[SELF_CURSOR_INPUT]); push(@{$self->[SELF_KILL_RING]}, $kill); } else { $self->rl_ding; } } sub rl_unix_word_rubout { my ($self, $key) = @_; if ($self->[SELF_CURSOR_INPUT]) { substr($self->[SELF_INPUT], 0, $self->[SELF_CURSOR_INPUT]) =~ /(\S*\s*)$/; my $kill = $self->_delete_chars($self->[SELF_CURSOR_INPUT] - length($1), length($1)); push(@{$self->[SELF_KILL_RING]}, $kill); } else { $self->rl_ding; } } sub rl_delete_horizontal_space { my ($self) = @_; substr($self->[SELF_INPUT], 0, $self->[SELF_CURSOR_INPUT]) =~ /(\s*)$/; my $left = length($1); substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]) =~ /^(\s*)/; my $right = length($1); if ($left + $right) { $self->_delete_chars($self->[SELF_CURSOR_INPUT] - $left, $left + $right); } else { $self->rl_ding; } } sub rl_copy_region_as_kill { my ($self) = @_; my $from = $self->[SELF_CURSOR_INPUT]; my $howmany = $self->[SELF_CURSOR_INPUT] - $self->[SELF_MARK]; if ($howmany < 0) { $from -= $howmany; $howmany = -$howmany; if ($from < 0) { $howmany -= $from; $from = 0; } } my $old = substr($self->[SELF_INPUT], $from, $howmany); push(@{$self->[SELF_KILL_RING]}, $old); } sub rl_abort { my ($self, $key) = @_; print $stdout uc($key), "\x0D\x0A"; $poe_kernel->select_read($stdin); if ($self->[SELF_HAS_TIMER]) { $poe_kernel->delay( $self->[SELF_STATE_IDLE] ); $self->[SELF_HAS_TIMER] = 0; } $poe_kernel->yield( $self->[SELF_EVENT_INPUT], undef, 'cancel', $self->[SELF_UNIQUE_ID] ); $self->[SELF_READING_LINE] = 0; $self->[SELF_HIST_INDEX] = @{$self->[SELF_HIST_LIST]}; $self->_flush_output_buffer; } sub rl_interrupt { my ($self, $key) = @_; print $stdout uc($key), "\x0D\x0A"; $poe_kernel->select_read($stdin); if ($self->[SELF_HAS_TIMER]) { $poe_kernel->delay( $self->[SELF_STATE_IDLE] ); $self->[SELF_HAS_TIMER] = 0; } $poe_kernel->yield( $self->[SELF_EVENT_INPUT], undef, 'interrupt', $self->[SELF_UNIQUE_ID] ); $self->[SELF_READING_LINE] = 0; $self->[SELF_HIST_INDEX] = @{$self->[SELF_HIST_LIST]}; $self->_flush_output_buffer; } # Delete a character. On an empty line, it throws an # "eot" exception, just like Term::ReadLine does. sub rl_delete_char { my ($self, $key) = @_; if (length $self->[SELF_INPUT] == 0) { print $stdout uc($key), "\x0D\x0A"; $poe_kernel->select_read($stdin); if ($self->[SELF_HAS_TIMER]) { $poe_kernel->delay( $self->[SELF_STATE_IDLE] ); $self->[SELF_HAS_TIMER] = 0; } $poe_kernel->yield( $self->[SELF_EVENT_INPUT], undef, "eot", $self->[SELF_UNIQUE_ID] ); $self->[SELF_READING_LINE] = 0; $self->[SELF_HIST_INDEX] = @{$self->[SELF_HIST_LIST]}; $self->_flush_output_buffer; return; } if ($self->[SELF_CURSOR_INPUT] < length($self->[SELF_INPUT])) { $self->_delete_chars($self->[SELF_CURSOR_INPUT], 1); } else { $self->rl_ding; } } sub rl_backward_delete_char { my ($self, $key) = @_; if ($self->[SELF_CURSOR_INPUT]) { $self->_delete_chars($self->[SELF_CURSOR_INPUT]-1, 1); } else { $self->rl_ding; } } sub rl_accept_line { my ($self, $key) = @_; if ($self->[SELF_CURSOR_INPUT] < length($self->[SELF_INPUT])) { my $right_string = substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]); print _normalize($right_string); my $right = _display_width($right_string); $self->[SELF_CURSOR_DISPLAY] += $right; $self->[SELF_CURSOR_INPUT] = length($self->[SELF_INPUT]); } # home the cursor. $self->[SELF_CURSOR_DISPLAY] = 0; $self->[SELF_CURSOR_INPUT] = 0; print $stdout "\x0D\x0A"; $poe_kernel->select_read($stdin); if ($self->[SELF_HAS_TIMER]) { $poe_kernel->delay( $self->[SELF_STATE_IDLE] ); $self->[SELF_HAS_TIMER] = 0; } $poe_kernel->yield( $self->[SELF_EVENT_INPUT], $self->[SELF_INPUT], $self->[SELF_UNIQUE_ID] ); $self->[SELF_READING_LINE] = 0; $self->[SELF_HIST_INDEX] = @{$self->[SELF_HIST_LIST]}; $self->_flush_output_buffer; ReadMode('restore'); eval { ($trk_cols, $trk_rows) = GetTerminalSize($stdout) }; ($trk_cols, $trk_rows) = (80, 25) if $@; if ($self->[SELF_KEYMAP]->{name} =~ /vi/) { $self->rl_set_keymap('vi-insert'); } } sub rl_clear_screen { my ($self, $key) = @_; my $left = _display_width(substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT])); $termcap->Tputs( 'cl', 1, $stdout ); my $sp = $self->[SELF_PROMPT]; $sp =~ s{\\[\[\]]}{}g; print $stdout $sp, _normalize($self->[SELF_INPUT]); _curs_left($left) if $left; } sub rl_transpose_chars { my ($self, $key) = @_; if ($self->[SELF_CURSOR_INPUT] > 0 and $self->[SELF_CURSOR_INPUT] < length($self->[SELF_INPUT])) { my $width_left = _display_width(substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT] - 1, 1)); my $transposition = reverse substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT] - 1, 2); substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT] - 1, 2) = $transposition; _curs_left($width_left); print $stdout _normalize($transposition); _curs_left($width_left); } else { $self->rl_ding; } } sub rl_transpose_words { my ($self, $key) = @_; my ($previous, $left, $space, $right, $rest); # This bolus of code was written to replace a single # regexp after finding out that the regexp's negative # zero-width look-behind assertion doesn't work in # perl 5.004_05. For the record, this is that regexp: # s/^(.{0,$cursor_sub_one})(?<!\S)(\S+)(\s+)(\S+)/$1$4$3$2/ if (substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT], 1) =~ /\s/) { my ($left_space, $right_space); ($previous, $left, $left_space) = ( substr($self->[SELF_INPUT], 0, $self->[SELF_CURSOR_INPUT]) =~ /^(.*?)(\S+)(\s*)$/ ); ($right_space, $right, $rest) = ( substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]) =~ /^(\s+)(\S+)(.*)$/ ); $space = $left_space . $right_space; } elsif ( substr($self->[SELF_INPUT], 0, $self->[SELF_CURSOR_INPUT]) =~ /^(.*?)(\S+)(\s+)(\S*)$/ ) { ($previous, $left, $space, $right) = ($1, $2, $3, $4); if (substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]) =~ /^(\S*)(.*)$/) { $right .= $1 if defined $1; $rest = $2; } } elsif ( substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]) =~ /^(\S+)(\s+)(\S+)(.*)$/ ) { ($left, $space, $right, $rest) = ($1, $2, $3, $4); if ( substr($self->[SELF_INPUT], 0, $self->[SELF_CURSOR_INPUT]) =~ /^(.*?)(\S+)$/ ) { $previous = $1; $left = $2 . $left; } } else { $self->rl_ding; next; } $previous = '' unless defined $previous; $rest = '' unless defined $rest; $self->[SELF_INPUT] = $previous . $right . $space . $left . $rest; if ($self->[SELF_CURSOR_DISPLAY] - _display_width($previous)) { _curs_left($self->[SELF_CURSOR_DISPLAY] - _display_width($previous)); } print $stdout _normalize($right . $space . $left); $self->[SELF_CURSOR_INPUT] = length($previous. $left . $space . $right); $self->[SELF_CURSOR_DISPLAY] = _display_width($previous . $left . $space . $right); } sub rl_unix_line_discard { my ($self, $key) = @_; if (length $self->[SELF_INPUT]) { my $kill = $self->_delete_chars(0, $self->[SELF_CURSOR_INPUT]); push(@{$self->[SELF_KILL_RING]}, $kill); } else { $self->rl_ding; } } sub rl_kill_whole_line { my ($self, $key) = @_; if (length $self->[SELF_INPUT]) { # Back up to the beginning of the line. if ($self->[SELF_CURSOR_INPUT]) { _curs_left($self->[SELF_CURSOR_DISPLAY]); $self->[SELF_CURSOR_DISPLAY] = $self->[SELF_CURSOR_INPUT] = 0; } $self->_clear_to_end; # Clear the input buffer. push(@{$self->[SELF_KILL_RING]}, $self->[SELF_INPUT]); $self->[SELF_INPUT] = ''; } else { $self->rl_ding; } } sub rl_yank { my ($self) = @_; my $pos = scalar @{$self->[SELF_KILL_RING]}; return $self->rl_ding unless ($pos); $pos--; $self->rl_self_insert($self->[SELF_KILL_RING]->[$pos], $self->[SELF_KILL_RING]->[$pos]); } sub rl_yank_pop { my ($self) = @_; return $self->rl_ding unless ($self->[SELF_LAST] =~ /yank/); my $pos = scalar @{$self->[SELF_KILL_RING]}; return $self->rl_ding unless ($pos); my $top = pop @{$self->[SELF_KILL_RING]}; unshift(@{$self->[SELF_KILL_RING]}, $top); $self->rl_yank; } sub rl_previous_history { my ($self, $key) = @_; if ($self->[SELF_HIST_INDEX]) { # Moving away from a new input line; save it in case # we return. if ($self->[SELF_HIST_INDEX] == @{$self->[SELF_HIST_LIST]}) { $self->[SELF_INPUT_HOLD] = $self->[SELF_INPUT]; } # Move cursor to start of input. if ($self->[SELF_CURSOR_INPUT]) { _curs_left($self->[SELF_CURSOR_DISPLAY]); } $self->_clear_to_end; # Move the history cursor back, set the new input # buffer, and show what the user's editing. Set the # cursor to the end of the new line. my $normal; print $stdout $normal = _normalize($self->[SELF_INPUT] = $self->[SELF_HIST_LIST]->[--$self->[SELF_HIST_INDEX]]); $self->[SELF_UNDO] = [ [ $self->[SELF_INPUT], 0, 0 ] ]; # reset undo info $self->[SELF_CURSOR_INPUT] = length($self->[SELF_INPUT]); $self->[SELF_CURSOR_DISPLAY] = length($normal); $self->rl_backward_char if (length($self->[SELF_INPUT]) && $self->[SELF_KEYMAP]->{name} =~ /vi/); } else { # At top of history list. $self->rl_ding; } } sub rl_next_history { my ($self, $key) = @_; if ($self->[SELF_HIST_INDEX] < @{$self->[SELF_HIST_LIST]}) { # Move cursor to start of input. if ($self->[SELF_CURSOR_INPUT]) { _curs_left($self->[SELF_CURSOR_DISPLAY]); } $self->_clear_to_end; my $normal; if (++$self->[SELF_HIST_INDEX] == @{$self->[SELF_HIST_LIST]}) { # Just past the end of the history. Whatever was # there when we left it. print $stdout $normal = _normalize($self->[SELF_INPUT] = $self->[SELF_INPUT_HOLD]); } else { # There's something in the history list. Make that # the current line. print $stdout $normal = _normalize($self->[SELF_INPUT] = $self->[SELF_HIST_LIST]->[$self->[SELF_HIST_INDEX]]); } $self->[SELF_UNDO] = [ [ $self->[SELF_INPUT], 0, 0 ] ]; # reset undo info $self->[SELF_CURSOR_INPUT] = length($self->[SELF_INPUT]); $self->[SELF_CURSOR_DISPLAY] = length($normal); $self->rl_backward_char if (length($self->[SELF_INPUT]) && $self->[SELF_KEYMAP]->{name} =~ /vi/); } else { $self->rl_ding; } } sub rl_beginning_of_history { my ($self) = @_; # First in history. if ($self->[SELF_HIST_INDEX]) { # Moving away from a new input line; save it in case # we return. if ($self->[SELF_HIST_INDEX] == @{$self->[SELF_HIST_LIST]}) { $self->[SELF_INPUT_HOLD] = $self->[SELF_INPUT]; } # Move cursor to start of input. if ($self->[SELF_CURSOR_INPUT]) { _curs_left($self->[SELF_CURSOR_DISPLAY]); } $self->_clear_to_end; # Move the history cursor back, set the new input # buffer, and show what the user's editing. Set the # cursor to the end of the new line. print $stdout my $normal = _normalize($self->[SELF_INPUT] = $self->[SELF_HIST_LIST]->[$self->[SELF_HIST_INDEX] = 0]); $self->[SELF_CURSOR_INPUT] = length($self->[SELF_INPUT]); $self->[SELF_CURSOR_DISPLAY] = length($normal); $self->[SELF_UNDO] = [ [ $self->[SELF_INPUT], 0, 0 ] ]; # reset undo info } else { # At top of history list. $self->rl_ding; } } sub rl_end_of_history { my ($self) = @_; if ($self->[SELF_HIST_INDEX] != @{$self->[SELF_HIST_LIST]} - 1) { # Moving away from a new input line; save it in case # we return. if ($self->[SELF_HIST_INDEX] == @{$self->[SELF_HIST_LIST]}) { $self->[SELF_INPUT_HOLD] = $self->[SELF_INPUT]; } # Move cursor to start of input. if ($self->[SELF_CURSOR_INPUT]) { _curs_left($self->[SELF_CURSOR_DISPLAY]); } $self->_clear_to_end; # Move the edit line down to the last history line. $self->[SELF_HIST_INDEX] = @{$self->[SELF_HIST_LIST]} - 1; print $stdout my $normal = _normalize($self->[SELF_INPUT] = $self->[SELF_HIST_LIST]->[$self->[SELF_HIST_INDEX]]); $self->[SELF_CURSOR_INPUT] = length($self->[SELF_INPUT]); $self->[SELF_CURSOR_DISPLAY] = length($normal); $self->[SELF_UNDO] = [ [ $self->[SELF_INPUT], 0, 0 ] ]; # reset undo info } else { $self->rl_ding; } } sub rl_forward_search_history { my ($self, $key) = @_; $self->_wipe_input_line; $self->[SELF_PREV_PROMPT] = $self->[SELF_PROMPT]; $self->[SELF_SEARCH_PROMPT] = '(forward-i-search)`%s\': '; $self->[SELF_SEARCH_MAP] = $self->[SELF_KEYMAP]; $self->[SELF_SEARCH_DIR] = +1; $self->[SELF_SEARCH_KEY] = $key; $self->_build_search_prompt; $self->_repaint_input_line; $self->rl_set_keymap('isearch'); } sub rl_reverse_search_history { my ($self, $key) = @_; $self->_wipe_input_line; $self->[SELF_PREV_PROMPT] = $self->[SELF_PROMPT]; $self->[SELF_SEARCH_PROMPT] = '(reverse-i-search)`%s\': '; $self->[SELF_SEARCH_MAP] = $self->[SELF_KEYMAP]; $self->[SELF_SEARCH_DIR] = -1; $self->[SELF_SEARCH_KEY] = $key; # start at the previous line... $self->[SELF_HIST_INDEX]-- if $self->[SELF_HIST_INDEX]; $self->_build_search_prompt; $self->_repaint_input_line; $self->rl_set_keymap('isearch'); } sub rl_capitalize_word { my ($self, $key) = @_; # Capitalize from cursor on. if (substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]) =~ /^(\s*)(\S+)/) { # Track leading space, and uppercase word. my $space = $1; $space = '' unless defined $space; my $word = ucfirst(lc($2)); # Replace text with the uppercase version. substr( $self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT] + length($space), length($word) ) = $word; # Display the new text; move the cursor after it. print $stdout $space, _normalize($word); $self->[SELF_CURSOR_INPUT] += length($space . $word); $self->[SELF_CURSOR_DISPLAY] += length($space) + _display_width($word); } else { $self->rl_ding; } } sub rl_upcase_word { my ($self, $key) = @_; # Uppercase from cursor on. # Modeled after capitalize. if (substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]) =~ /^(\s*)(\S+)/) { my $space = $1; $space = '' unless defined $space; my $word = uc($2); substr( $self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT] + length($space), length($word) ) = $word; print $stdout $space, _normalize($word); $self->[SELF_CURSOR_INPUT] += length($space . $word); $self->[SELF_CURSOR_DISPLAY] += length($space) + _display_width($word); } else { $self->rl_ding; } } sub rl_downcase_word { my ($self, $key) = @_; # Lowercase from cursor on. # Modeled after capitalize. if (substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]) =~ /^(\s*)(\S+)/) { my $space = $1; $space = '' unless defined $space; my $word = lc($2); substr( $self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT] + length($space), length($word) ) = $word; print $stdout $space, _normalize($word); $self->[SELF_CURSOR_INPUT] += length($space . $word); $self->[SELF_CURSOR_DISPLAY] += length($space) + _display_width($word); } else { $self->rl_ding; } next; } sub rl_quoted_insert { my ($self, $key) = @_; $self->[SELF_PENDING_FN] = sub { my ($k,$rk) = @_; $self->rl_self_insert($k, $rk); } } sub rl_overwrite_mode { my ($self, $key) = @_; $self->[SELF_INSERT_MODE] = !$self->[SELF_INSERT_MODE]; if ($self->[SELF_COUNT]) { if ($self->[SELF_COUNT] > 0) { $self->[SELF_INSERT_MODE] = 0; } else { $self->[SELF_INSERT_MODE] = 1; } } } sub rl_vi_replace { my ($self) = @_; $self->rl_vi_insertion_mode; $self->rl_overwrite_mode; } sub rl_tilde_expand { my ($self) = @_; my $pre = substr($self->[SELF_INPUT], 0, $self->[SELF_CURSOR_INPUT]); my ($append) = (substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]) =~ /^(\w+)/); my ($left,$user) = ("$pre$append" =~ /^(.*)~(\S+)$/); if ($user) { my $dir = (getpwnam($user))[7]; if (!$dir) { print "\x0D\x0Ausername '$user' not found\x0D\x0A"; $self->_repaint_input_line; return $self->rl_ding; } $self->_wipe_input_line; substr($self->[SELF_INPUT], length($left), length($user) + 1) = $dir; # +1 for tilde $self->[SELF_CURSOR_INPUT] += length($dir) - length($user) - 1; $self->[SELF_CURSOR_DISPLAY] += length($dir) - length($user) - 1; $self->_repaint_input_line; return 1; } else { return $self->rl_ding; } } sub _complete_match { my ($self) = @_; my $lookfor = substr($self->[SELF_INPUT], 0, $self->[SELF_CURSOR_INPUT]); $lookfor =~ /(\S+)$/; $lookfor = $1; my $point = $self->[SELF_CURSOR_INPUT] - length($lookfor); my @clist = (); if ($self->option("completion_function")) { my $fn = $self->[SELF_OPTIONS]->{completion_function}; @clist = &$fn($lookfor, $self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]); } my @poss = @clist; if ($lookfor) { my $l = length $lookfor; @poss = grep { substr($_, 0, $l) eq $lookfor } @clist; } return @poss; } sub _complete_list { my ($self, @poss) = @_; my $width = 0; if ($self->option('print-completions-horizontally') eq 'on') { map { $width = (length($_) > $width) ? length($_) : $width } @poss; my $cols = int($trk_cols / $width); $cols = int($trk_cols / ($width+$cols)); # ensure enough room for spaces $width = int($trk_cols / $cols); print $stdout "\x0D\x0A"; my $c = 0; foreach my $word (@poss) { print $stdout $word . (" " x ($width - length($word))); if (++$c == $cols) { print $stdout "\x0D\x0A"; $c = 0; } } print "\x0D\x0A" if $c; } else { print "\x0D\x0A"; foreach my $word (@poss) { print $stdout $word . "\x0D\x0A"; } } $self->_repaint_input_line; } sub rl_possible_completions { my ($self, $key) = @_; my @poss = $self->_complete_match; if (scalar @poss == 0) { return $self->rl_ding; } $self->_complete_list(@poss); } sub rl_complete { my ($self, $key) = @_; my $lookfor = substr($self->[SELF_INPUT], 0, $self->[SELF_CURSOR_INPUT]); $lookfor =~ /(\S+)$/; $lookfor = $1; my $point = $self->[SELF_CURSOR_INPUT] - length($lookfor); my @poss = $self->_complete_match; if (scalar @poss == 0) { return $self->rl_ding; } if (scalar @poss == 1) { substr($self->[SELF_INPUT], $point, $self->[SELF_CURSOR_INPUT]) = $poss[0]; my $rest = substr($self->[SELF_INPUT], $point+length($lookfor)); print $stdout $rest; _curs_left(length($rest)-length($poss[0])); $self->[SELF_CURSOR_INPUT] += length($poss[0])-length($lookfor); $self->[SELF_CURSOR_DISPLAY] += length($poss[0])-length($lookfor); return 1; } # so at this point, we have multiple possibilities # find out how much more is in common with the possibilities. my $max = length($lookfor); while (1) { my $letter = undef; my $ok = 1; foreach my $p (@poss) { if ((length $p) < $max) { $ok = 0; last; } if (!$letter) { $letter = substr($p, $max, 1); next; } if (substr($p, $max, 1) ne $letter) { $ok = 0; last; } } if ($ok) { $max++; } else { last; } } if ($max > length($lookfor)) { my $partial = substr($poss[0], 0, $max); substr($self->[SELF_INPUT], $point, $self->[SELF_CURSOR_INPUT]) = $partial; my $rest = substr($self->[SELF_INPUT], $point+length($lookfor)); print $stdout $rest; _curs_left(length($rest)-length($partial)); $self->[SELF_CURSOR_INPUT] += length($partial)-length($lookfor); $self->[SELF_CURSOR_DISPLAY] += length($partial)-length($lookfor); return $self->rl_ding if @poss == 1; } if ($self->[SELF_LAST] !~ /complete/ && !$self->option('show-all-if-ambiguous')) { return $self->rl_ding; } $self->_complete_list(@poss); return 0; } sub rl_insert_completions { my ($self) = @_; my @poss = $self->_complete_match; if (scalar @poss == 0) { return $self->rl_ding; } # need to back up the current text my $lookfor = substr($self->[SELF_INPUT], 0, $self->[SELF_CURSOR_INPUT]); $lookfor =~ /(\S+)$/; $lookfor = $1; my $point = length($lookfor); while ($point--) { $self->rl_backward_delete_char; } my $text = join(" ", @poss); $self->rl_self_insert($text, $text); } sub rl_ding { my ($self) = @_; if (!$self->option('bell-style') || $self->option('bell-style') eq 'audible') { print $stdout $tc_bell; } elsif ($self->option('bell-style') eq 'visible') { print $stdout $tc_visual_bell; } return 0; } sub rl_redraw_current_line { my ($self) = @_; $self->_wipe_input_line; $self->_repaint_input_line; } sub rl_poe_wheel_debug { my ($self, $key) = @_; my $left = _display_width(substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT])); my $sp = $self->[SELF_PROMPT]; $sp =~ s{\\[\[\]]}{}g; print( $stdout "\x0D\x0A", "ID=$self->[SELF_UNIQUE_ID] ", "cursor_input($self->[SELF_CURSOR_INPUT]) ", "cursor_display($self->[SELF_CURSOR_DISPLAY]) ", "term_columns($trk_cols)\x0D\x0A", $sp, _normalize($self->[SELF_INPUT]) ); _curs_left($left) if $left; } sub rl_vi_movement_mode { my ($self) = @_; $self->rl_set_keymap('vi'); $self->rl_backward_char if ($self->[SELF_INPUT]); } sub rl_vi_append_mode { my ($self) = @_; if ($self->[SELF_CURSOR_INPUT] < length($self->[SELF_INPUT])) { # we can't just call forward-char, coz we don't want bell to ring. my $normal = _normalize(substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT], 1)); print $stdout $normal; $self->[SELF_CURSOR_INPUT]++; $self->[SELF_CURSOR_DISPLAY] += length($normal); } $self->rl_set_keymap('vi-insert'); } sub rl_vi_append_eol { my ($self) = @_; $self->rl_end_of_line; $self->rl_vi_append_mode; } sub rl_vi_insertion_mode { my ($self) = @_; $self->rl_set_keymap('vi-insert'); } sub rl_vi_insert_beg { my ($self) = @_; $self->rl_beginning_of_line; $self->rl_vi_insertion_mode; } sub rl_vi_editing_mode { my ($self) = @_; $self->rl_set_keymap('vi'); } sub rl_emacs_editing_mode { my ($self) = @_; $self->rl_set_keymap('emacs'); } sub rl_vi_eof_maybe { my ($self, $key) = @_; if (length $self->[SELF_INPUT] == 0) { print $stdout uc($key), "\x0D\x0A"; $poe_kernel->select_read($stdin); if ($self->[SELF_HAS_TIMER]) { $poe_kernel->delay( $self->[SELF_STATE_IDLE] ); $self->[SELF_HAS_TIMER] = 0; } $poe_kernel->yield( $self->[SELF_EVENT_INPUT], undef, "eot", $self->[SELF_UNIQUE_ID] ); $self->[SELF_READING_LINE] = 0; $self->[SELF_HIST_INDEX] = @{$self->[SELF_HIST_LIST]}; $self->_flush_output_buffer; return 0; } else { return $self->rl_ding; } } sub rl_vi_change_case { my ($self) = @_; my $char = substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT], 1); if ($char lt 'a') { substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT], 1) = lc($char); } else { substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT], 1) = uc($char); } $self->rl_forward_char; } sub rl_vi_prev_word { &rl_backward_word; } sub rl_vi_next_word { my ($self, $key) = @_; if (substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]) =~ /^(\s*\S+\s)/) { $self->[SELF_CURSOR_INPUT] += length($1); my $right = _display_width($1); print _normalize($1); $self->[SELF_CURSOR_DISPLAY] += $right; } else { return $self->rl_ding; } } sub rl_vi_end_word { my ($self, $key) = @_; if ($self->[SELF_CURSOR_INPUT] < length($self->[SELF_INPUT])) { $self->rl_forward_char; if (substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]) =~ /^(\s*\S+)/) { $self->[SELF_CURSOR_INPUT] += length($1)-1; my $right = _display_width($1); print _normalize($1); $self->[SELF_CURSOR_DISPLAY] += $right-1; _curs_left(1); } } else { return $self->rl_ding; } } sub rl_vi_column { my ($self) = @_; $self->[SELF_COUNT] ||= 0; $self->rl_beginning_of_line; while ($self->[SELF_COUNT]--) { $self->rl_forward_char; } $self->[SELF_COUNT] = 0; } sub rl_vi_match { my ($self) = @_; return $self->rl_ding unless $self->[SELF_INPUT]; # what paren are we after? look forwards down the line for the closest my $pos = $self->[SELF_CURSOR_INPUT]; my $where = substr($self->[SELF_INPUT], $pos); my ($adrift) = ($where =~ m/([^\(\)\{\}\[\]]*)/); my $paren = substr($where, length($adrift), 1); $pos += length($adrift); return $self->rl_ding unless $paren; my $what_to_do = { '(' => [ ')', 1 ], '{' => [ '}', 1 ], '[' => [ ']', 1 ], ')' => [ '(', -1 ], '}' => [ '{', -1 ], ']' => [ '[', -1 ], }->{$paren}; my($opp,$dir) = @{$what_to_do}; my $level = 1; while ($level) { if ($dir > 0) { return $self->rl_ding if ($pos == length($self->[SELF_INPUT])); $pos++; } else { return $self->rl_ding unless $pos; $pos--; } my $c = substr($self->[SELF_INPUT], $pos, 1); if ($c eq $opp) { $level--; } elsif ($c eq $paren) { $level++ } } $self->[SELF_COUNT] = $pos; $self->rl_vi_column; return 1; } sub rl_vi_first_print { my ($self) = @_; $self->rl_beginning_of_line; substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]) =~ /^(\s*)/; if (length($1)) { $self->[SELF_CURSOR_INPUT] += length($1); my $right = _display_width($1); print _normalize($1); $self->[SELF_CURSOR_DISPLAY] += $right; } } sub rl_vi_delete { my ($self) = @_; if ($self->[SELF_CURSOR_INPUT] < length($self->[SELF_INPUT])) { $self->_delete_chars($self->[SELF_CURSOR_INPUT], 1); if ($self->[SELF_INPUT] && $self->[SELF_CURSOR_INPUT] >= length($self->[SELF_INPUT])) { $self->[SELF_CURSOR_INPUT]--; $self->[SELF_CURSOR_DISPLAY]--; _curs_left(1); } } else { return $self->rl_ding; } } sub rl_vi_put { my ($self, $key) = @_; my $pos = scalar @{$self->[SELF_KILL_RING]}; return $self->rl_ding unless ($pos); $pos--; if ($self->[SELF_INPUT] && $key eq 'p') { my $normal = _normalize(substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT], 1)); print $stdout $normal; $self->[SELF_CURSOR_INPUT]++; $self->[SELF_CURSOR_DISPLAY] += length($normal); } $self->rl_self_insert($self->[SELF_KILL_RING]->[$pos], $self->[SELF_KILL_RING]->[$pos]); if ($self->[SELF_CURSOR_INPUT] >= length($self->[SELF_INPUT])) { $self->[SELF_CURSOR_INPUT]--; $self->[SELF_CURSOR_DISPLAY]--; _curs_left(1); } } sub rl_vi_yank_arg { my ($self) = @_; $self->rl_vi_append_mode; if ($self->rl_yank_last_arg) { $self->rl_set_keymap('vi-insert'); } else { $self->rl_set_keymap('vi-command'); } } sub rl_vi_end_spec { my ($self) = @_; $self->[SELF_PENDING] = undef; $self->rl_ding; $self->rl_set_keymap('vi'); } sub rl_vi_spec_end_of_line { my ($self) = @_; $self->rl_set_keymap('vi'); $self->_vi_apply_spec($self->[SELF_CURSOR_INPUT], length($self->[SELF_INPUT]) - $self->[SELF_CURSOR_INPUT]); } sub rl_vi_spec_beginning_of_line { my ($self) = @_; $self->rl_set_keymap('vi'); $self->_vi_apply_spec(0, $self->[SELF_CURSOR_INPUT]); } sub rl_vi_spec_first_print { my ($self) = @_; substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]) =~ /^(\s*)/; my $len = length($1) || 0; my $from = $self->[SELF_CURSOR_INPUT]; if ($from > $len) { my $tmp = $from; $from = $len; $len = $tmp - $from; } $self->_vi_apply_spec($from, $len); } sub rl_vi_spec_word { my ($self) = @_; my $from = $self->[SELF_CURSOR_INPUT]; my $len = length($self->[SELF_INPUT]) - $from + 1; if (substr($self->[SELF_INPUT], $from) =~ /^(\s*\S+\s)/) { my $word = $1; $len = length($word); } $self->rl_set_keymap('vi'); $self->_vi_apply_spec($from, $len); } sub rl_character_search { my ($self) = @_; $self->[SELF_PENDING_FN] = sub { my $key = shift; return $self->rl_ding unless substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]) =~ /(.*)$key/; $self->[SELF_COUNT] = $self->[SELF_INPUT] + length($1); $self->vi_column; } } sub rl_character_search_backward { my ($self) = @_; $self->[SELF_PENDING_FN] = sub { my $key = shift; return $self->rl_ding unless substr($self->[SELF_INPUT], 0, $self->[SELF_CURSOR_INPUT]) =~ /$key([^$key])*$/; $self->[SELF_COUNT] = $self->[SELF_INPUT] - length($1); $self->vi_column; } } sub rl_vi_spec_forward_char { my ($self) = @_; $self->[SELF_PENDING_FN] = sub { my $key = shift; return $self->rl_ding unless substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]) =~ /(.*)$key/; $self->_vi_apply_spec($self->[SELF_CURSOR_INPUT], length($1)); } } sub rl_vi_spec_mark { my ($self) = @_; $self->[SELF_PENDING_FN] = sub { my $key = shift; return $self->rl_ding unless exists $self->[SELF_MARKLIST]->{$key}; my $pos = $self->[SELF_CURSOR_INPUT]; my $len = $self->[SELF_MARKLIST]->{$key} - $self->[SELF_CURSOR_INPUT]; if ($len < 0) { $pos += $len; $len = -$len; } $self->_vi_apply_spec($pos, $len); } } sub _vi_apply_spec { my ($self, $from, $howmany) = @_; &{$self->[SELF_PENDING]}($from, $howmany); $self->[SELF_PENDING] = undef if ($self->[SELF_COUNT] <= 1); } sub rl_vi_yank_to { my ($self, $key) = @_; $self->[SELF_PENDING] = sub { my ($from, $howmany) = @_; push(@{$self->[SELF_KILL_RING]}, substr($self->[SELF_INPUT], $from, $howmany)); }; if ($key eq 'Y') { $self->rl_vi_spec_end_of_line; } else { $self->rl_set_keymap('vi-specification'); } } sub rl_vi_delete_to { my ($self, $key) = @_; $self->[SELF_PENDING] = sub { my ($from, $howmany) = @_; $self->_delete_chars($from, $howmany); if ($self->[SELF_INPUT] && $self->[SELF_CURSOR_INPUT] >= length($self->[SELF_INPUT])) { $self->[SELF_CURSOR_INPUT]--; $self->[SELF_CURSOR_DISPLAY]--; _curs_left(1); } $self->rl_set_keymap('vi'); }; if ($key eq 'D') { $self->rl_vi_spec_end_of_line; } else { $self->rl_set_keymap('vi-specification'); } } sub rl_vi_change_to { my ($self, $key) = @_; $self->[SELF_PENDING] = sub { my ($from, $howmany) = @_; $self->_delete_chars($from, $howmany); $self->rl_set_keymap('vi-insert'); }; if ($key eq 'C') { $self->rl_vi_spec_end_of_line; } else { $self->rl_set_keymap('vi-specification'); } } sub rl_vi_arg_digit { my ($self, $key) = @_; if ($key == '0' && !$self->[SELF_COUNT]) { $self->rl_beginning_of_line; } else { $self->[SELF_COUNT] .= $key; } } sub rl_vi_tilde_expand { my ($self) = @_; if ($self->rl_tilde_expand) { $self->rl_vi_append_mode; } } sub rl_vi_complete { my ($self) = @_; if ($self->rl_complete) { $self->rl_set_keymap('vi-insert'); } } sub rl_vi_goto_mark { my ($self) = @_; $self->[SELF_PENDING_FN] = sub { my $key = shift; return $self->rl_ding unless exists $self->[SELF_MARKLIST]->{$key}; $self->[SELF_COUNT] = $self->[SELF_MARKLIST]->{$key}; $self->rl_vi_column; } } sub rl_vi_set_mark { my ($self) = @_; $self->[SELF_PENDING_FN] = sub { my $key = shift; return $self->rl_ding unless ($key >= 'a' && $key <= 'z'); $self->[SELF_MARKLIST]->{$key} = $self->[SELF_CURSOR_INPUT]; } } sub rl_search_abort { my ($self) = @_; $self->_wipe_input_line; $self->[SELF_PROMPT] = $self->[SELF_PREV_PROMPT]; $self->_repaint_input_line; $self->[SELF_KEYMAP] = $self->[SELF_SEARCH_MAP]; $self->[SELF_SEARCH_MAP] = undef; $self->[SELF_SEARCH] = undef; } sub rl_search_finish { my ($self, $key, $raw) = @_; $self->_wipe_input_line; $self->[SELF_PROMPT] = $self->[SELF_PREV_PROMPT]; $self->_repaint_input_line; $self->[SELF_KEYMAP] = $self->[SELF_SEARCH_MAP]; $self->[SELF_SEARCH_MAP] = undef; $self->[SELF_SEARCH] = undef; $self->_apply_key($key, $raw); } sub rl_search_key { my ($self, $key) = @_; $self->[SELF_SEARCH] .= $key; $self->_search(1); } sub rl_vi_search_key { my ($self, $key) = @_; $self->rl_self_insert($key, $key); } sub rl_vi_search { my ($self, $key) = @_; $self->_wipe_input_line; $self->[SELF_SEARCH_MAP] = $self->[SELF_KEYMAP]; if ($key eq '/' && $self->[SELF_HIST_INDEX] < scalar @{$self->[SELF_HIST_LIST]}) { $self->[SELF_SEARCH_DIR] = -1; } else { $self->[SELF_SEARCH_DIR] = +1; } $self->[SELF_SEARCH_KEY] = $key; $self->[SELF_INPUT] = $key; $self->[SELF_CURSOR_INPUT] = 1; $self->[SELF_CURSOR_DISPLAY] = 1; $self->_repaint_input_line; $self->rl_set_keymap('vi-search'); } sub rl_vi_search_accept { my ($self) = @_; $self->_wipe_input_line; $self->[SELF_CURSOR_INPUT] = 0; $self->[SELF_CURSOR_DISPLAY] = 0; $self->[SELF_INPUT] =~ s{^[/?]}{}; $self->[SELF_SEARCH] = $self->[SELF_INPUT] if $self->[SELF_INPUT]; $self->_search(0); $self->[SELF_KEYMAP] = $self->[SELF_SEARCH_MAP]; $self->[SELF_SEARCH_MAP] = undef; } sub rl_vi_search_again { my ($self, $key) = @_; return $self->rl_ding unless $self->[SELF_SEARCH]; $self->[SELF_HIST_INDEX] += $self->[SELF_SEARCH_DIR]; if ($self->[SELF_HIST_INDEX] < 0) { $self->[SELF_HIST_INDEX] = 0; return $self->rl_ding; } elsif ($self->[SELF_HIST_INDEX] >= scalar @{$self->[SELF_HIST_LIST]}) { $self->[SELF_HIST_INDEX] = (scalar @{$self->[SELF_HIST_LIST]}) - 1; return $self->rl_ding; } $self->_wipe_input_line; $self->_search(0); } sub rl_isearch_again { my ($self, $key) = @_; if ($key ne $self->[SELF_SEARCH_KEY]) { $self->[SELF_SEARCH_KEY] = $key; $self->[SELF_SEARCH_DIR] = -$self->[SELF_SEARCH_DIR]; } $self->[SELF_HIST_INDEX] += $self->[SELF_SEARCH_DIR]; if ($self->[SELF_HIST_INDEX] < 0) { $self->[SELF_HIST_INDEX] = 0; return $self->rl_ding; } elsif ($self->[SELF_HIST_INDEX] >= scalar @{$self->[SELF_HIST_LIST]}) { $self->[SELF_HIST_INDEX] = (scalar @{$self->[SELF_HIST_LIST]}) - 1; return $self->rl_ding; } $self->_search(1); } sub rl_non_incremental_forward_search_history { my ($self) = @_; $self->_wipe_input_line; $self->[SELF_CURSOR_INPUT] = 0; $self->[SELF_CURSOR_DISPLAY] = 0; $self->[SELF_SEARCH_DIR] = +1; $self->[SELF_SEARCH] = substr($self->[SELF_INPUT], 0, $self->[SELF_CURSOR_INPUT]); $self->_search(0); } sub rl_non_incremental_reverse_search_history { my ($self) = @_; $self->[SELF_HIST_INDEX] --; if ($self->[SELF_HIST_INDEX] < 0) { $self->[SELF_HIST_INDEX] = 0; return $self->rl_ding; } $self->_wipe_input_line; $self->[SELF_CURSOR_INPUT] = 0; $self->[SELF_CURSOR_DISPLAY] = 0; $self->[SELF_SEARCH_DIR] = -1; $self->[SELF_SEARCH] = substr($self->[SELF_INPUT], 0, $self->[SELF_CURSOR_INPUT]); $self->_search(0); } sub rl_undo { my ($self) = @_; $self->rl_ding unless scalar @{$self->[SELF_UNDO]}; my $tuple = pop @{$self->[SELF_UNDO]}; ($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT], $self->[SELF_CURSOR_DISPLAY]) = @$tuple; } sub rl_vi_redo { my ($self, $key) = @_; return $self->rl_ding unless $self->[SELF_LAST]; my $fn = $self->[SELF_LAST]; $self->$fn(); } sub rl_vi_char_search { my ($self, $key) = @_; $self->[SELF_PENDING_FN] = sub { my ($k,$rk) = @_; $rk = "\\" . $rk if ($rk !~ /\w/); return $self->rl_ding unless substr($self->[SELF_INPUT], $self->[SELF_CURSOR_INPUT]) =~ /([^$rk]*)$rk/; $self->[SELF_COUNT] = $self->[SELF_CURSOR_INPUT] + length($1); $self->rl_vi_column; } } sub rl_vi_change_char { my ($self, $key) = @_; $self->[SELF_PENDING_FN] = sub { my ($k,$rk) = @_; $self->rl_delete_char; $self->rl_self_insert($k,$rk); $self->rl_backward_char; } } sub rl_vi_subst { my ($self, $key) = @_; if ($key eq 's') { $self->rl_vi_delete; } else { $self->rl_beginning_of_line; $self->rl_kill_line; } $self->rl_vi_insertion_mode; } # ============================================================ # THE KEYMAP CLASS ITSELF # ============================================================ package POE::Wheel::ReadLine::Keymap; my %english_to_termcap = ( 'up' => 'ku', 'down' => 'kd', 'left' => 'kl', 'right' => 'kr', 'insert' => 'kI', 'ins' => 'kI', 'delete' => 'kD', 'del' => 'kD', 'home' => 'kh', 'end' => 'kH', 'backspace' => 'kb', 'bs' => 'kb', ); my %english_to_key = ( 'space' => " ", 'esc' => "\e", 'escape' => "\e", 'tab' => "\cI", 'ret' => "\cJ", 'return' => "\cJ", 'newline' => "\cM", 'lfd' => "\cL", 'rubout' => chr(127), ); sub init { my ($proto, %opts) = @_; my $class = ref($proto) || $proto; my $default = delete $opts{default} or die("no default specified for keymap"); my $name = delete $opts{name} or die("no name specified for keymap"); my $termcap = delete $opts{termcap} or die("no termcap specified for keymap"); my $self = { name => $name, default => $default, binding => {}, prefix => {}, termcap => $termcap, }; return bless $self, $class; } sub decode { my ($self, $seq) = @_; if (exists $english_to_termcap{lc($seq)}) { my $key = $self->{termcap}->Tputs($english_to_termcap{lc($seq)}, 1); $seq = $key; } elsif (exists $english_to_key{lc($seq)}) { $seq = $english_to_key{lc($seq)}; } return $seq; } sub control { my $c = shift; return chr(0x7F) if $c eq "?"; return chr(ord(uc($c))-64); } sub meta { return "\x1B" . $_[0] }; sub bind_key { my ($self, $inseq, $fn) = @_; my $seq = $inseq; my $macro = undef; if (!ref $fn) { if ($fn =~ /^["'](.*)['"]$/) { # A macro $macro = $1; $fn = 'insert-macro'; } else { if (!exists $POE::Wheel::ReadLine::defuns->{$fn}) { print "ignoring $inseq, since function '$fn' is not known\r\n"; next; } } } # Need to parse key sequence into a trivial lookup form. if ($seq =~ s{^"(.*)"$}{$1}) { $seq =~ s{\\C-(.)}{control($1)}ge; $seq =~ s{\\M-(.)}{meta($1)}ge; $seq =~ s{\\e}{\x1B}g; $seq =~ s{\\\\}{\\}g; $seq =~ s{\\"}{"}g; $seq =~ s{\\'}{'}g; } else { my $orig = $seq; do { $orig = $seq; $seq =~ s{(\w*)$}{$self->decode($1)}ge; # horrible regex, coz we need to work backwards, to allow # for things like C-M-r, or C-xC-x $seq =~ s{C(ontrol)?-(.)([^-]*)$}{control($2).$3}ge; $seq =~ s{M(eta)?-(.)([^-]*)$}{meta($2).$3}ge; } while ($seq ne $orig); } $self->{binding}->{$seq} = $fn if length $seq; $self->{macros}->{$seq} = $macro if $macro; #print "bound $inseq (" . POE::Wheel::ReadLine::_normalize($seq) . ") to $fn in map $self->{name}\r\n"; if (length($seq) > 1) { # XXX: Should store rawkey prefixes, to avoid the ^ problem. # requires converting seq into raw, then applying normalize # later on for binding. May not need last step if we keep # everything as raw. # Some keystrokes generate multi-byte sequences. Record the prefixes # for multi-byte sequences so the keystroke builder knows it's in the # middle of something. while (length($seq) > 1) { chop $seq; $self->{prefix}->{$seq}++; } } } 1; __END__ =head1 NAME POE::Wheel::ReadLine - non-blocking Term::ReadLine for POE =head1 SYNOPSIS #!perl use warnings; use strict; use POE qw(Wheel::ReadLine); POE::Session->create( inline_states=> { _start => \&setup_console, got_user_input => \&handle_user_input, } ); POE::Kernel->run(); exit; sub handle_user_input { my ($input, $exception) = @_[ARG0, ARG1]; my $console = $_[HEAP]{console}; unless (defined $input) { $console->put("$exception caught. B'bye!"); $_[KERNEL]->signal($_[KERNEL], "UIDESTROY"); $console->write_history("./test_history"); return; } $console->put(" You entered: $input"); $console->addhistory($input); $console->get("Go: "); } sub setup_console { $_[HEAP]{console} = POE::Wheel::ReadLine->new( InputEvent => 'got_user_input' ); $_[HEAP]{console}->read_history("./test_history"); $_[HEAP]{console}->clear(); $_[HEAP]{console}->put( "Enter some text.", "Ctrl+C or Ctrl+D exits." ); $_[HEAP]{console}->get("Go: "); } =head1 DESCRIPTION POE::Wheel::ReadLine is a non-blocking form of Term::ReadLine that's compatible with POE. It uses Term::Cap to interact with the terminal display and Term::ReadKey to interact with the keyboard. POE::Wheel::ReadLine handles almost all common input editing keys. It provides an input history list. It has both vi and emacs modes. It supports incremental input search. It's fully customizable, and it's compatible with standard readline(3) implementions such as Term::ReadLine::Gnu. POE::Wheel::ReadLine is configured by placing commands in an "inputrc" initialization file. The file's name is taken from the C<INPUTRC> environment variable, or ~/.inputrc by default. POE::Wheel::ReadLine will read the inputrc file and configure itself according to the commands and variables therein. See readline(3) for details about inputrc files. The default editing mode will be emacs-style, although this can be configured by setting the 'editing-mode' variable within an inputrc file. If all else fails, POE::Wheel::ReadLine will determine the user's favorite editor by examining the EDITOR environment variable. =head1 PUBLIC METHODS =head2 Constructor Most of POE::Wheel::ReadLine's interaction is through its constructor, new(). =head3 new new() creates and returns a new POE::Wheel::ReadLine object. Be sure to instantiate only one, as multiple console readers would conflict. =head4 InputEvent C<InputEvent> names the event that will indicate a new line of console input. See L</PUBLIC EVENTS> for more details. =head4 PutMode C<PutMode> controls how output is displayed when put() is called during user input. When set to "immediate", put() pre-empts the user immediately. The input prompt and user's input to date are redisplayed after put() is done. The "after" C<PutMode> tells put() to wait until after the user enters or cancels her input. Finally, "idle" will allow put() to pre-empt user input if the user stops typing for C</IdleTime> seconds. This mode behaves like "after" if the user can't stop typing long enough. This is POE::Wheel::ReadLine's default mode. =head4 IdleTime C<IdleTime> tells POE::Wheel::ReadLine how long the keyboard must be idle before C<put()> becomes immediate or buffered text is flushed to the display. It is only meaningful when L</InputMode> is "idle". C<IdleTime> defaults to 2 seconds. =head4 AppName C<AppName> registers an application name which is used to retrieve application-specific key bindings from the inputrc file. The default C<AppName> is "poe-readline". # If using POE::Wheel::ReadLine, set # the key mapping to emacs mode and # trigger debugging output on a certain # key sequence. $if poe-readline set keymap emacs Control-xP: poe-wheel-debug $endif =head2 History List Management POE::Wheel::ReadLine supports an input history, with searching. =head3 add_history add_history() accepts a list of lines to add to the input history. Generally it's called with a single line: the last line of input received from the terminal. The C</SYNOPSIS> shows add_history() in action. =head3 get_history get_history() returns a list containing POE::Wheel::ReadLine's current input history. It may not contain everything entered into the wheel TODO - Example. =head3 write_history write_history() writes the current input history to a file. It accepts one optional parameter: the name of the file where the input history will be written. write_history() will write to ~/.history if no file name is specified. Returns true on success, or false if not. The L</SYNOPSIS> shows an example of write_history() and the corresponding read_history(). =head3 read_history read_history(FILENAME, START, END) reads a previously saved input history from a named file, or from ~/.history if no file name is specified. It may also read a subset of the history file if it's given optional START and END parameters. The file will be read from the beginning if START is omitted or zero. It will be read to the end if END is omitted or earlier than START. Returns true on success, or false if not. The L</SYNOPSIS> shows an example of read_history() and the corresponding write_history(). Read the first ten history lines: $_[HEAP]{console}->read_history("filename", 0, 9); =head3 history_truncate_file history_truncate_file() truncates a history file to a certain number of lines. It accepts two parameters: the name of the file to truncate, and the maximum number of history lines to leave in the file. The history file will be cleared entirely if the line count is zero or omitted. The file to be truncated defaults to ~/.history. So calling history_truncate_file() with no parameters clears ~/.history. Returns true on success, or false if not. Note that history_trucate_file() removes the earliest lines from the file. The later lines remain intact since they were the ones most recently entered. Keep ~/.history down to a manageable 100 lines: $_[HEAP]{console}->history_truncate_file(undef, 100); =head2 Key Binding Methods =head3 bind_key bind_key(KEYSTROKE, FUNCTION) binds a FUNCTION to a named KEYSTROKE sequence. The keystroke sequence can be in any of the forms defined within readline(3). The function should either be a pre-defined name, such as "self-insert" or a function reference. The binding is made in the current keymap. Use the rl_set_keymap() method to change keymaps, if desired. =head3 add_defun NAME FN add_defun(NAME, FUNCTION) defines a new global FUNCTION, giving it a specific NAME. The function may then be bound to kestrokes by that NAME. =head2 Console I/O Methods =head3 clear Clears the terminal. =head3 terminal_size Returns what POE::Wheel::ReadLine thinks are the current dimensions of the terminal. Returns a list of two values: the number of columns and number of rows, respectively. sub some_event_handler { my ($columns, $rows) = $_[HEAP]{console}->terminal_size; $_[HEAP]{console}->put( "Terminal columns: $columns", "Terminal rows: $rows", ); } =head3 get get() causes POE::Wheel::ReadLine to display a prompt and then wait for input. Input is not noticed unless get() has enabled the wheel's internal I/O watcher. After get() is called, the next line of input or exception on the console will trigger an C<InputEvent> with the appropriate parameters. POE::Wheel::ReadLine will then enter an inactive state until get() is called again. See the L</SYNOPSIS> for sample usage. =head3 put put() accepts a list of lines to put on the terminal. POE::Wheel::ReadLine is line-based. See L<POE::Wheel::Curses> for more funky display options. Please do not use print() with POE::Wheel::ReadLine. print() invariably gets the newline wrong, leaving an application's output to stairstep down the terminal. Also, put() understands when a user is entering text, and C<PutMode> may be used to avoid interrupting the user. =head2 ReadLine Option Methods =head3 attribs attribs() returns a reference to a hash of readline options. The returned hash may be used to query or modify POE::Wheel::ReadLine's behavior. =head3 option option(NAME) returns a specific member of the hash returned by attribs(). It's a more convenient way to query POE::Wheel::ReadLine options. =head1 PUBLIC EVENTS POE::Wheel::ReadLine emits only a single event. =head2 InputEvent C<InputEvent> names the event that will be emitted upon any kind of complete terminal input. Every C<InputEvent> handler receives three parameters: C<$_[ARG0]> contains a line of input. It may be an empty string if the user entered an empty line. An undefined C<$_[ARG0]> indicates some exception such as end-of-input or the fact that the user canceled their input or pressed C-c (^C). C<$_[ARG1]> describes an exception, if one occurred. It may contain one of the following strings: =over 2 =item cancel The "cancel" exception indicates when a user has canceled a line of input. It's sent when the user triggers the "abort" function, which is bound to C-g (^G) by default. =item eot "eot" is the ASCII code for "end of tape". It's emitted when the user requests that the terminal be closed. By default, it's triggered when the user presses C-d (^D) on an empty line. =item interrupt "interrupt" is sent as a result of the user pressing C-c (^C) or otherwise triggering the "interrupt" function. =back Finally, C<$_[ARG2]> contains the ID for the POE::Wheel::ReadLine object that sent the C<InputEvent>. =head1 CUSTOM BINDINGS POE::Wheel::ReadLine allows custom functions to be bound to keystrokes. The function must be made visible to the wheel before it can be bound. To register a function, use POE::Wheel::ReadLine's add_defun() method: POE::Wheel::ReadLine->add_defun('reverse-line', \&reverse_line); When adding a new defun, an optional third parameter may be provided which is a key sequence to bind to. This should be in the same format as that understood by the inputrc parsing. Bound functions receive three parameters: A reference to the wheel object itself, the key sequence that triggered the function (in printable form), and the raw key sequence. The bound function is expected to dig into the POE::Wheel::ReadLine data members to do its work and display the new line contents itself. This is less than ideal, and it may change in the future. =head1 CUSTOM COMPLETION An application may modify POE::Wheel::ReadLine's "completion_function" in order to customize how input should be completed. The new completion function must accept three scalar parameters: the word being completed, the entire input text, and the position within the input text of the word being completed. The completion function should return a list of possible matches. For example: my $attribs = $wheel->attribs(); $attribs->{completion_function} = sub { my ($text, $line, $start) = @_; return qw(a list of candidates to complete); } This is the only form of completion currently supported. =head1 IMPLEMENTATION DIFFERENCES Although POE::Wheel::ReadLine is modeled after the readline(3) library, there are some areas which have not been implemented. The only option settings which have effect in this implementation are: bell-style, editing-mode, isearch-terminators, comment-begin, print-completions-horizontally, show-all-if-ambiguous and completion_function. The function 'tab-insert' is not implemented, nor are tabs displayed properly. =head1 SEE ALSO L<POE::Wheel> describes the basic operations of all wheels in more depth. You need to know this. readline(3), L<Term::Cap>, L<Term::ReadKey>. The SEE ALSO section in L<POE> contains a table of contents covering the entire POE distribution. L<Term::Visual> is an alternative to POE::Wheel::ReadLine. It provides scrollback and a status bar in addition to editable user input. Term::Visual supports POE despite the lack of "POE" in its name. =head1 BUGS POE::Wheel::ReadLine has some known issues: =head2 Perl 5.8.0 is Broken Non-blocking input with Term::ReadKey does not work with Perl 5.8.0, especially on Linux systems for some reason. Upgrading Perl will fix things. If you can't upgrade Perl, consider alternative input methods, such as Term::Visual. L<http://rt.cpan.org/Ticket/Display.html?id=4524> and related tickets explain the issue in detail. If you suspect your system is one where Term::ReadKey fails, you can run this test program to be sure. #!/usr/bin/perl use Term::ReadKey; print "Press 'q' to quit this test.\n"; ReadMode 5; # Turns off controls keys while (1) { while (not defined ($key = ReadKey(-1))) { print "Didn't get a key. Sleeping 1 second.\015\012"; sleep (1); } print "Got key: $key\015\012"; ($key eq 'q') and last; } ReadMode 0; # Reset tty mode before exiting exit; =head2 Non-Optimal Code Dissociating the input and display cursors introduced a lot of code. Much of this code was thrown in hastily, and things can probably be done with less work. TODO: Apply some thought to what's already been done. TODO: Ensure that the screen updates as quickly as possible, especially on slow systems. Do little or no calculation during displaying; either put it all before or after the display. Do it consistently for each handled keystroke, so that certain pairs of editing commands don't have extra perceived latency. =head2 Unimplemented Features Input editing is not kept on one line. If it wraps, and a terminal cannot wrap back through a line division, the cursor will become lost. Unicode support. I feel real bad about throwing away native representation of all the 8th-bit-set characters. I also have no idea how to do this, and I don't have a system to test this. Patches are very much welcome. =head1 GOTCHAS / FAQ =head2 Lost Prompts Q: Why do I lose my prompt every time I send output to the screen? A: You probably are using print or printf to write screen output. ReadLine doesn't track STDOUT itself, so it doesn't know when to refresh the prompt after you do this. Use ReadLine's put() method to write lines to the console. =head2 Edit Keystrokes Display as ^C Q: None of the editing keystrokes work. Ctrl-C displays "^c" rather than generating an interrupt. The arrow keys don't scroll through my input history. It's generally a bad experience. A: You're probably a vi/vim user. In the absence of a ~/.inputrc file, POE::Wheel::ReadLine checks your EDITOR environment variable for clues about your editing preference. If it sees /vi/ in there, it starts in vi mode. You can override this by creating a ~/.inputrc file containing the line "set editing-mode emacs", or adding that line to your existing ~/.inputrc. While you're in there, you should totally get acquainted with all the other cool stuff you can do with .inputrc files. =head2 Lack of Windows Support Q: Why doesn't POE::Wheel::ReadLine work on Windows? Term::ReadLine does. A: POE::Wheel::ReadLine requires select(), because that's what POE uses by default to detect keystrokes without blocking. About half the flavors of Perl on Windows implement select() in terms of the same function in the WinSock library, which limits select() to working only with sockets. Your console isn't a socket, so select() doesn't work with your version of Perl on Windows. Really good workarounds are possible but don't exist as of this writing. They involve writing a special POE::Loop for Windows that either uses a Win32-specific module for better multiplexing, that polls for input, or that uses blocking I/O watchers in separate threads. =head1 AUTHORS & COPYRIGHTS POE::Wheel::ReadLine was originally written by Rocco Caputo. Nick Williams virtually rewrote it to support a larger subset of GNU readline. Please see L<POE> for more information about other authors and contributors. =cut # rocco // vim: ts=2 sw=2 expandtab
carlgao/lenga
images/lenny64-peon/usr/share/perl5/POE/Wheel/ReadLine.pm
Perl
mit
103,300
use LWP::Simple; my $usage = " perl $0 startDate endDate Note: Download sra.sampleInfo.xml file as specific time region: eg. perl $0 2017/01/01 2017/12/31 "; my $startDate = shift; my $endDate = shift; die $usage unless $startDate and $endDate; my $timeStamp = $startDate."_".$endDate; $timeStamp =~ tr/\//_/; $query='(("green plants"[Organism]) AND ("biomol rna"[Properties])) AND (("rna seq"[Strategy]) NOT ("mirna seq"[Strategy])) AND (("bgiseq"[Platform]) OR ("illumina"[Platform])) AND ("'.$startDate.'"[Publication Date] : "'.$endDate.'"[Publication Date])'; #assemble the esearch URL $base = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/'; $url = $base . "esearch.fcgi?db=sra&term=$query&usehistory=y"; # $url=~s/\s+/+/g; # print "$url\n"; #post the esearch URL $output = get($url); # print $output,"\n"; #parse WebEnv, QueryKey and Count (# records retrieved) $web = $1 if ($output =~ /<WebEnv>(\S+)<\/WebEnv>/); $key = $1 if ($output =~ /<QueryKey>(\d+)<\/QueryKey>/); $count = $1 if ($output =~ /<Count>(\d+)<\/Count>/); #retrieve data in batches of 500 $retmax = 500; for ($retstart = 0; $retstart < $count; $retstart += $retmax) { $efetch_url = $base ."efetch.fcgi?db=sra&WebEnv=$web"; $efetch_url .= "&query_key=$key&retstart=$retstart"; $efetch_url .= "&retmax=$retmax&rettype=xml&retmode=full"; $efetch_out = get($efetch_url); open(OUT, ">sra.".$timeStamp.".".$retstart.".xml") || die "Can't open file!\n"; binmode OUT,":utf8"; print OUT "$efetch_out"; close OUT; # sleep int rand(10)+5; }
CJ-Chen/TBtools-Manual
BioScripts/PerlScript/downloadSRA.pl
Perl
mit
1,525
% Maze connected(1,2). connected(3,4). connected(5,6). connected(7,8). connected(9,10). connected(12,13). connected(13,14). connected(15,16). connected(17,18). connected(19,20). connected(4,1). connected(6,3). connected(4,7). connected(6,11). connected(14,9). connected(11,15). connected(16,12). connected(14,17). connected(16,19). path(X, Y) :- connected(X, Y). path(X, Y) :- path(X, Z), connected(Z, Y). % path(5, 10). % path(1, X). % path(X, 13). % Travel % Valmont CAR saarbrucken TRAIN frankfurt PLANE bangkok PLANE auckland CAR hamilton CAR raglan byCar(auckland,hamilton). byCar(hamilton,raglan). byCar(valmont,saarbruecken). byCar(valmont,metz). byTrain(metz,frankfurt). byTrain(saarbruecken,frankfurt). byTrain(metz,paris). byTrain(saarbruecken,paris). byPlane(frankfurt,bangkok). byPlane(frankfurt,singapore). byPlane(paris,losAngeles). byPlane(bangkok,auckland). byPlane(losAngeles,auckland). go(X, Y) :- byCar(X, Y). go(X, Y) :- byTrain(X, Y). go(X, Y) :- byPlane(X, Y). go(X, Y, byCar) :- byCar(X, Y). go(X, Y, byTrain) :- byTrain(X, Y). go(X, Y, byPlane) :- byPlane(X, Y). travel(X, Y) :- go(X, Y). travel(X, Y) :- travel(X, Z), go(Z, Y). travel(X, Y, Z) :- go(X, Y, Z). travel(X, Y, Z) :- go(X, W, go(W, Y, Z)). travel(X, Y, Z) :- travel(X, W, Z), go(W, Y, Z). travel(X, Y, Z) :- travel(X, W, go(W, Y, Z)). %******************************************* % Maze connected(1,2). connected(3,4). connected(5,6). connected(7,8). connected(9,10). connected(12,13). connected(13,14). connected(15,16). connected(17,18). connected(19,20). connected(4,1). connected(6,3). connected(4,7). connected(6,11). connected(14,9). connected(11,15). connected(16,12). connected(14,17). connected(16,19). path(X, Y) :- connected(X, Y). path(X, Y) :- path(X, Z), connected(Z, Y). % path(5, 10). % path(1, X). % path(X, 13). % Travel % Valmont CAR saarbrucken TRAIN frankfurt PLANE bangkok PLANE auckland CAR hamilton CAR raglan byCar(auckland,hamilton). byCar(hamilton,raglan). byCar(valmont,saarbruecken). byCar(valmont,metz). byTrain(metz,frankfurt). byTrain(saarbruecken,frankfurt). byTrain(metz,paris). byTrain(saarbruecken,paris). byPlane(frankfurt,bangkok). byPlane(frankfurt,singapore). byPlane(paris,losAngeles). byPlane(bangkok,auckland). byPlane(losAngeles,auckland). tr(X, Y) :- byCar(X, Y). tr(X, Y) :- byTrain(X, Y). tr(X, Y) :- byPlane(X, Y). trx(X, Y, byCar) :- byCar(X, Y). trx(X, Y, byTrain) :- byTrain(X, Y). trx(X, Y, byPlane) :- byPlane(X, Y). travel(X, Y) :- tr(X, Y). travel(X, Y) :- travel(X, Z), tr(Z, Y). % B travel(X, Y, go(X, Y)) :- tr(X, Y). travel(X, Y, go(X, Z, T)):- tr(X, Z), travel(Z, Y, T). % C travelx(X, Y, go(X, Y, N)) :- trx(X, Y, N). travelx(X, Y, go(X, Z, N, T)):- trx(X, Z, N), travelx(Z, Y, T). %************************************** % Crossword puzzle word(abalone,a,b,a,l,o,n,e). word(abandon,a,b,a,n,d,o,n). word(enhance,e,n,h,a,n,c,e). word(anagram,a,n,a,g,r,a,m). word(connect,c,o,n,n,e,c,t). word(elegant,e,l,e,g,a,n,t). crosswd(A, B, C, D, E, F) :- word(A, _, A2, _, A4, _, A6, _), word(B, _, B2, _, B4, _, B6, _), word(C, _, C2, _, C4, _, C6, _), word(D, _, D2, _, D4, _, D6, _), word(E, _, E2, _, E4, _, E6, _), word(F, _, F2, _, F4, _, F6, _), A2 = D2, B2 = D4, C2 = D6, A4 = E2, B4 = E4, C4 = E6, A6 = F2, B6 = F4, C6 = F6.
PavelClaudiuStefan/FMI
An_2_Semestru_2/ProgramareLogica/Laboratoare/3/Lab3.pl
Perl
cc0-1.0
3,481
# # Copyright 2015 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 os::aix::local::mode::liststorages; use base qw(centreon::plugins::mode); use strict; use warnings; use centreon::plugins::misc; 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 => { "hostname:s" => { name => 'hostname' }, "remote" => { name => 'remote' }, "ssh-option:s@" => { name => 'ssh_option' }, "ssh-path:s" => { name => 'ssh_path' }, "ssh-command:s" => { name => 'ssh_command', default => 'ssh' }, "timeout:s" => { name => 'timeout', default => 30 }, "sudo" => { name => 'sudo' }, "command:s" => { name => 'command', default => 'df' }, "command-path:s" => { name => 'command_path' }, "command-options:s" => { name => 'command_options', default => '-P -k 2>&1' }, "filter-fs:s" => { name => 'filter_fs', }, "filter-mount:s" => { name => 'filter_mount', }, }); $self->{result} = {}; return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); } sub manage_selection { my ($self, %options) = @_; my $stdout = centreon::plugins::misc::execute(output => $self->{output}, options => $self->{option_results}, sudo => $self->{option_results}->{sudo}, command => $self->{option_results}->{command}, command_path => $self->{option_results}->{command_path}, command_options => $self->{option_results}->{command_options}); my @lines = split /\n/, $stdout; # Header not needed shift @lines; foreach my $line (@lines) { next if ($line !~ /^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.*)/); my ($fs, $size, $used, $available, $percent, $mount) = ($1, $2, $3, $4, $5, $6); if (defined($self->{option_results}->{filter_fs}) && $self->{option_results}->{filter_fs} ne '' && $fs !~ /$self->{option_results}->{filter_fs}/) { $self->{output}->output_add(long_msg => "Skipping storage '" . $mount . "': no matching filter fs"); next; } if (defined($self->{option_results}->{filter_mount}) && $self->{option_results}->{filter_mount} ne '' && $mount !~ /$self->{option_results}->{filter_mount}/) { $self->{output}->output_add(long_msg => "Skipping storage '" . $mount . "': no matching filter mount"); next; } $self->{result}->{$mount} = {fs => $fs}; } } sub run { my ($self, %options) = @_; $self->manage_selection(); foreach my $name (sort(keys %{$self->{result}})) { $self->{output}->output_add(long_msg => "'" . $name . "' [fs = " . $self->{result}->{$name}->{fs} . ']'); } $self->{output}->output_add(severity => 'OK', short_msg => 'List storages:'); $self->{output}->display(nolabel => 1, force_ignore_perfdata => 1, force_long_output => 1); $self->{output}->exit(); } sub disco_format { my ($self, %options) = @_; $self->{output}->add_disco_format(elements => ['name', 'fs']); } sub disco_show { my ($self, %options) = @_; $self->manage_selection(); foreach my $name (sort(keys %{$self->{result}})) { $self->{output}->add_disco_entry(name => $name, fs => $self->{result}->{$name}->{fs}, ); } } 1; __END__ =head1 MODE List storages. =over 8 =item B<--remote> Execute command remotely in 'ssh'. =item B<--hostname> Hostname to query (need --remote). =item B<--ssh-option> Specify multiple options like the user (example: --ssh-option='-l=centreon-engine' --ssh-option='-p=52'). =item B<--ssh-path> Specify ssh command path (default: none) =item B<--ssh-command> Specify ssh command (default: 'ssh'). Useful to use 'plink'. =item B<--timeout> Timeout in seconds for the command (Default: 30). =item B<--sudo> Use 'sudo' to execute the command. =item B<--command> Command to get information (Default: 'df'). Can be changed if you have output in a file. =item B<--command-path> Command path (Default: none). =item B<--command-options> Command options (Default: '-P -k 2>&1'). =item B<--filter-fs> Filter filesystem (regexp can be used). =item B<--filter-mount> Filter mount point (regexp can be used). =back =cut
s-duret/centreon-plugins
os/aix/local/mode/liststorages.pm
Perl
apache-2.0
5,891
package Search::Elasticsearch::Plugin::XPack::5_0::Watcher; use Moo; with 'Search::Elasticsearch::Plugin::XPack::5_0::Role::API'; with 'Search::Elasticsearch::Role::Client::Direct'; use namespace::clean; __PACKAGE__->_install_api('watcher'); 1; # ABSTRACT: Plugin providing Watcher API for Search::Elasticsearch 2.x =head1 SYNOPSIS use Search::Elasticsearch(); my $es = Search::Elasticsearch->new( nodes => \@nodes, plugins => ['XPack'] ); my $response = $es->watcher->info(); =head2 DESCRIPTION This class extends the L<Search::Elasticsearch> client with a C<watcher> namespace, to support the API for the L<Watcher|https://www.elastic.co/products/watcher> plugin for Elasticsearch. In other words, it can be used as follows: use Search::Elasticsearch(); my $es = Search::Elasticsearch->new( nodes => \@nodes, plugins => ['Watcher'] ); my $response = $es->watcher->info(); =head1 METHODS The full documentation for the Watcher plugin is available here: L<http://www.elastic.co/guide/en/watcher/current/> =head2 C<put_watch()> $response = $es->watcher->put_watch( id => $watch_id, # required body => {...} # required ); The C<put_watch()> method is used to register a new watcher or to update an existing watcher. See the L<put_watch docs|http://www.elastic.co/guide/en/watcher/current/api-rest.html#api-rest-put-watch> for more information. Query string parameters: C<active>, C<master_timeout> =head2 C<get_watch()> $response = $es->watcher->get_watch( id => $watch_id, # required ); The C<get_watch()> method is used to retrieve a watch by ID. See the L<get_watch docs|http://www.elastic.co/guide/en/watcher/current/api-rest.html#api-rest-get-watch> for more information. =head2 C<delete_watch()> $response = $es->watcher->delete_watch( id => $watch_id, # required ); The C<delete_watch()> method is used to delete a watch by ID. Query string parameters: C<force>, C<master_timeout> See the L<delete_watch docs|http://www.elastic.co/guide/en/watcher/current/api-rest.html#api-rest-delete-watch> for more information. =head2 C<execute_watch()> $response = $es->watcher->execute_watch( id => $watch_id, # optional body => {...} # optional ); The C<execute_watch()> method forces the execution of a previously registered watch. Optional parameters may be passed in the C<body>. Query string parameters: C<debug> See the L<execute_watch docs|http://www.elastic.co/guide/en/watcher/current/api-rest.html#api-rest-execute-watch> for more information. =head2 C<ack_watch()> $response = $es->watcher->ack_watch( watch_id => $watch_id, # required action_id => $action_id | \@action_ids # optional ); The C<ack_watch()> method is used to manually throttle the execution of a watch. Query string parameters: C<master_timeout> See the L<ack_watch docs|http://www.elastic.co/guide/en/watcher/current/api-rest.html#api-rest-ack-watch> for more information. =head2 C<activate_watch()> $response = $es->watcher->activate_watch( watch_id => $watch_id, # required ); The C<activate_watch()> method is used to activate a deactive watch. Query string parameters: C<master_timeout> See the L<activate_watch docs|http://www.elastic.co/guide/en/watcher/current/api-rest.html#api-rest-activate-watch> for more information. =head2 C<deactivate_watch()> $response = $es->watcher->deactivate_watch( watch_id => $watch_id, # required ); The C<deactivate_watch()> method is used to deactivate an active watch. Query string parameters: C<master_timeout> See the L<deactivate_watch docs|http://www.elastic.co/guide/en/watcher/current/api-rest.html#api-rest-deactivate-watch> for more information. =head2 C<info()> $response = $es->watcher->info(); The C<info()> method returns basic information about the watcher plugin that is installed. See the L<info docs|http://www.elastic.co/guide/en/watcher/current/api-rest.html#api-rest-info> for more information. =head2 C<stats()> $response = $es->watcher->stats( metric => $metric # optional ); The C<stats()> method returns information about the status of the watcher plugin. See the L<stats docs|http://www.elastic.co/guide/en/watcher/current/api-rest.html#api-rest-stats> for more information. =head2 C<stop()> $response = $es->watcher->stop(); The C<stop()> method stops the watcher service if it is running. See the L<stop docs|http://www.elastic.co/guide/en/watcher/current/api-rest.html#api-rest-stop> for more information. =head2 C<start()> $response = $es->watcher->start(); The C<start()> method starts the watcher service if it is not already running. See the L<start docs|http://www.elastic.co/guide/en/watcher/current/api-rest.html#api-rest-start> for more information. =head2 C<restart()> $response = $es->watcher->restart(); The C<restart()> method stops then starts the watcher service. See the L<restart docs|http://www.elastic.co/guide/en/watcher/current/api-rest.html#api-rest-restart> for more information.
adjust/elasticsearch-perl
lib/Search/Elasticsearch/Plugin/XPack/5_0/Watcher.pm
Perl
apache-2.0
5,291
package Paws::CloudSearch::LiteralOptions; use Moose; has DefaultValue => (is => 'ro', isa => 'Str'); has FacetEnabled => (is => 'ro', isa => 'Bool'); has ReturnEnabled => (is => 'ro', isa => 'Bool'); has SearchEnabled => (is => 'ro', isa => 'Bool'); has SortEnabled => (is => 'ro', isa => 'Bool'); has SourceField => (is => 'ro', isa => 'Str'); 1; ### main pod documentation begin ### =head1 NAME Paws::CloudSearch::LiteralOptions =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::CloudSearch::LiteralOptions object: $service_obj->Method(Att1 => { DefaultValue => $value, ..., SourceField => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::CloudSearch::LiteralOptions object: $result = $service_obj->Method(...); $result->Att1->DefaultValue =head1 DESCRIPTION Options for literal field. Present if C<IndexFieldType> specifies the field is of type C<literal>. All options are enabled by default. =head1 ATTRIBUTES =head2 DefaultValue => Str A value to use for the field if the field isn't specified for a document. =head2 FacetEnabled => Bool Whether facet information can be returned for the field. =head2 ReturnEnabled => Bool Whether the contents of the field can be returned in the search results. =head2 SearchEnabled => Bool Whether the contents of the field are searchable. =head2 SortEnabled => Bool Whether the field can be used to sort the search results. =head2 SourceField => Str =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::CloudSearch> =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/CloudSearch/LiteralOptions.pm
Perl
apache-2.0
2,105
# # 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 network::cyberoam::snmp::mode::services; use base qw(centreon::plugins::templates::hardware); use strict; use warnings; sub set_system { my ($self, %options) = @_; $self->{regexp_threshold_overload_check_section_option} = '^(service)$'; $self->{cb_hook2} = 'snmp_execute'; $self->{thresholds} = { default => [ ['untouched', 'OK'], ['stopped', 'CRITICAL'], ['initializing', 'OK'], ['running', 'OK'], ['exiting', 'CRITICAL'], ['dead', 'CRITICAL'], ['unregistered', 'OK'], ], }; $self->{components_path} = 'network::cyberoam::snmp::mode::components'; $self->{components_module} = ['service']; } sub snmp_execute { my ($self, %options) = @_; $self->{snmp} = $options{snmp}; $self->{results} = $self->{snmp}->get_multiple_table(oids => $self->{request}); } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options, no_absent => 1, no_performance => 1); bless $self, $class; $self->{version} = '1.0'; $options{options}->add_options(arguments => { }); return $self; } 1; __END__ =head1 MODE Check services. =over 8 =item B<--component> Which component to check (Default: '.*'). Can be: 'service'. =item B<--filter> Exclude some parts (comma seperated list) Can also exclude specific instance: --filter=service,pop =item B<--no-component> Return an error if no compenents are checked. If total (with skipped) is 0. (Default: 'critical' returns). =item B<--threshold-overload> Set to overload default threshold values (syntax: section,[instance,]status,regexp) It used before default thresholds (order stays). Example: --threshold-overload='service,imap4,OK,stopped' =back =cut
wilfriedcomte/centreon-plugins
network/cyberoam/snmp/mode/services.pm
Perl
apache-2.0
2,677
new12(A,B,C,D) :- A=0. new7(A,B,C) :- D=1, B=0, new6(A,B,D). new7(A,B,C) :- D=0, B=< -1, new6(A,B,D). new7(A,B,C) :- D=0, B>=1, new6(A,B,D). new6(A,B,C) :- new12(C,A,B,C). new5(A,B,C) :- D=1, B=16, new6(A,B,D). new5(A,B,C) :- B=<15, new7(A,B,C). new5(A,B,C) :- B>=17, new7(A,B,C). new3(A,B,C) :- D=1+A, E=2+B, A=<8, new3(D,E,C). new3(A,B,C) :- A>=9, new5(A,B,C). new2 :- A=1, B=0, new3(A,B,C). new1 :- new2. false :- new1.
bishoksan/RAHFT
benchmarks_scp/misc/programs-clp/SVCOMP13-loops-sum04_safe.map.c.map.pl
Perl
apache-2.0
423
# 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::V9::Enums::ProductChannelEnum; use strict; use warnings; use Const::Exporter enums => [ UNSPECIFIED => "UNSPECIFIED", UNKNOWN => "UNKNOWN", ONLINE => "ONLINE", LOCAL => "LOCAL" ]; 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V9/Enums/ProductChannelEnum.pm
Perl
apache-2.0
817
=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 <dev@ensembl.org>. Questions may also be sent to the Ensembl help desk at <helpdesk@ensembl.org>. =cut =head1 NAME Bio::EnsEMBL::OntologyTerm =head1 DESCRIPTION An ontology term object, (most often) created by Bio::EnsEMBL::DBSQL::GOTermAdaptor and used in querying for transcripts, genes, and translations using the relevant adaptors and methods. =head1 METHODS =cut package Bio::EnsEMBL::OntologyTerm; use strict; use warnings; use Bio::EnsEMBL::Utils::Argument qw( rearrange ); use base qw( Bio::EnsEMBL::Storable ); =head2 new Arg [-ACCESSION] : String The accession of the ontology term. Arg [-ONTOLOGY] : String The ontology that the term belongs to. Arg [-NAMESPACE] : String The namespace of the ontology term. Arg [-NAME] : String The name of the ontology term. Arg [-SUBSETS] : (optional) Listref of strings The subsets within the ontology to which this term belongs. Arg [-DEFINITION] : (optional) String The definition of the ontology term. Arg [-SYNONYMS] : (optional) Listref of strings The synonyms of this term. Arg : Further arguments required for parent class Bio::EnsEMBL::Storable. Description : Creates an ontology term object. Example : my $term = Bio::EnsEMBL::OntologyTerm->new( '-accession' => 'GO:0021785', '-ontology' => 'GO', '-namespace' => 'biological_process', '-name' => 'branchiomotor neuron axon guidance', '-definition' => 'The process in which a branchiomotor ' . 'neuron growth cone is directed to a specific target site. ' . 'Branchiomotor neurons are located in the hindbrain and ' . 'innervate branchial arch-derived muscles that control jaw ' . 'movements, facial expression, the larynx, and the pharynx.', '-synonyms' => [ 'BMN axon guidance', 'branchial motor axon guidance', 'special visceral motor neuron axon guidance' ] # ... other arguments required by Bio::EnsEMBL::Storable. ); Return type : Bio::EnsEMBL::OntologyTerm =cut sub new { my $proto = shift(@_); my $this = $proto->SUPER::new(@_); my ( $accession, $ontology, $namespace, $name, $definition, $subsets ) = rearrange( [ 'ACCESSION', 'ONTOLOGY', 'NAMESPACE', 'NAME', 'DEFINITION', 'SUBSETS' ], @_ ); $this->{'accession'} = $accession; $this->{'ontology'} = $ontology; $this->{'namespace'} = $namespace; $this->{'name'} = $name; $this->{'definition'} = $definition; $this->{'subsets'} = [ @{$subsets} ]; $this->{'child_terms_fetched'} = 0; $this->{'parent_terms_fetched'} = 0; return $this; } =head2 accession Arg : None Description : Returns the accession for the ontology term in question. Example : my $accession = $term->accession(); Return type : String =cut sub accession { my ($this) = @_; return $this->{'accession'}; } =head2 ontology Arg : None Description : Returns the ontology for the ontology term in question. Example : my $ontology = $term->ontology(); Return type : String =cut sub ontology { my ($this) = @_; return $this->{'ontology'}; } =head2 namespace Arg : None Description : Returns the namespace for the ontology term in question. Example : my $acc = $term->namespace(); Return type : String =cut sub namespace { my ($this) = @_; return $this->{'namespace'}; } =head2 name Arg : None Description : Returns the name for the ontology term in question. Example : my $name = $term->name(); Return type : String =cut sub name { my ($this) = @_; return $this->{'name'}; } =head2 definition Arg : None Description : Returns the definition for the ontology term in question. Example : my $definition = $term->definition(); Return type : String =cut sub definition { my ($this) = @_; return $this->{'definition'}; } =head2 synonyms Arg : None Description : Returns the list of synonyms defined for this term (if any). Example : my @synonyms = @{ $term->synonyms() }; Return type : Listref of strings =cut sub synonyms { my ($this) = @_; if ( !exists( $this->{'synonyms'} ) ) { $this->{'synonyms'} = $this->adaptor()->_fetch_synonyms_by_dbID( $this->dbID() ); } return $this->{'synonyms'}; } =head2 subsets Arg : None Description : Returns a list of subsets that this term is part of. The list might be empty. Example : my @subsets = @{ $term->subsets() }; Return type : listref of strings =cut sub subsets { my ($this) = @_; return $this->{'subsets'}; } =head2 children Arg : (optional) List of strings The type of relations to retrieve children for. Description : Returns the children terms of this ontology term. Example : my @children = @{ $term->children( 'is_a', 'part_of' ) }; Return type : listref of Bio::EnsEMBL::OntologyTerm =cut sub children { my ( $this, @relations ) = @_; my @terms = @{ $this->adaptor()->fetch_all_by_parent_term($this) }; if (@relations) { @terms = (); foreach my $relation (@relations) { if ( exists( $this->{'children'}{$relation} ) ) { push( @terms, @{ $this->{'children'}{$relation} } ); } } } return \@terms; } =head2 descendants Arg : None Description : Returns the complete set of 'is_a' and 'part_of' descendant terms of this ontology term, down to and including any leaf terms. Example : my @descendants = @{ $term->descendants() }; Return type : listref of Bio::EnsEMBL::OntologyTerm =cut sub descendants { my ($this) = @_; return $this->adaptor()->fetch_all_by_ancestor_term($this); } =head2 parents Arg : (optional) List of strings The type of relations to retrieve parents for. Description : Returns the parent terms of this ontology term. Example : my @parents = @{ $term->parents( 'is_a', 'part_of' ) }; Return type : listref of Bio::EnsEMBL::OntologyTerm =cut sub parents { my ( $this, @relations ) = @_; my @terms = @{ $this->adaptor()->fetch_all_by_child_term($this) }; if (@relations) { @terms = (); foreach my $relation (@relations) { if ( exists( $this->{'parents'}{$relation} ) ) { push( @terms, @{ $this->{'parents'}{$relation} } ); } } } return \@terms; } =head2 ancestors Arg : None Description : Returns the complete set of 'is_a' and 'part_of' ancestor terms of this ontology term, up to and including the root term. Example : my @ancestors = @{ $term->ancestors() }; Return type : listref of Bio::EnsEMBL::OntologyTerm =cut sub ancestors { my ($this) = @_; return $this->adaptor()->fetch_all_by_descendant_term($this); } 1;
adamsardar/perl-libs-custom
EnsemblAPI/ensembl/modules/Bio/EnsEMBL/OntologyTerm.pm
Perl
apache-2.0
7,721
=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::Parsers::NCBIBLAST; use strict; use warnings; use Bio::EnsEMBL::DBSQL::DBAdaptor; use EnsEMBL::Web::Utils::FileHandler qw(file_get_contents); use parent qw(EnsEMBL::Web::Parsers); sub new { my $self = shift->SUPER::new(@_); $self->{'dba'} = Bio::EnsEMBL::DBSQL::DBAdaptor->new(%{$self->runnable->param('dba')}); return $self; } sub disconnect_dbc { my $self = shift; $self->{'dba'}->dbc->disconnect_if_idle; } sub get_adapter { my ($self, $feature_type) = @_; return $self->{"_adaptor_$feature_type"} ||= $self->{'dba'}->get_adaptor($feature_type); } sub parse { my ($self, $file) = @_; my $runnable = $self->runnable; my $species = $runnable->param('species'); my $source_type = $runnable->param('source'); my $max_hits = $runnable->param('__max_hits'); my @results = file_get_contents($file, sub { chomp; my @hit_data = split /\t/, $_; my $q_ori = $hit_data[1] < $hit_data[2] ? 1 : -1; my $t_ori = $hit_data[4] < $hit_data[5] ? 1 : -1; my $tstart = $hit_data[4] < $hit_data[5] ? $hit_data[4] : $hit_data[5]; my $tend = $hit_data[4] < $hit_data[5] ? $hit_data[5] : $hit_data[4]; return { qid => $hit_data[0], qstart => $hit_data[1], qend => $hit_data[2], qori => $q_ori, qframe => $hit_data[11], tid => $hit_data[3] =~ s/\..+//r, # without any version info v_tid => $hit_data[3], # possibly versioned tstart => $tstart, tend => $tend, tori => $t_ori, tframe => $hit_data[12], score => $hit_data[6], evalue => $hit_data[7], pident => $hit_data[8], len => $hit_data[9], aln => $hit_data[10], }; }); @results = sort { $a->{'evalue'} <=> $b->{'evalue'} } @results; @results = splice @results, 0, $max_hits if $max_hits && @results > $max_hits; # only keep the requested number of hits @results = map $self->map_to_genome($_, $species, $source_type), @results; $self->disconnect_dbc; return \@results; } sub map_to_genome { my ($self, $hit, $species, $source_type) = @_; my ($g_id, $g_start, $g_end, $g_ori, $g_coords, $feature_type); if ($source_type =~/LATESTGP/) { $g_id = $hit->{'tid'}; $g_start = $hit->{'tstart'}; $g_end = $hit->{'tend'}; $g_ori = $hit->{'tori'}; } else { $feature_type = $source_type =~ /abinitio/i ? 'PredictionTranscript' : $source_type =~ /pep/i ? 'Translation' : 'Transcript'; my $mapper = $source_type =~ /pep/i ? 'pep2genomic' : 'cdna2genomic'; my $adaptor = $self->get_adapter($feature_type); # if object is not found against un-versioned id, try the one which looked like versioned and retain it as tid if object is found my $object; $object = $adaptor->fetch_by_stable_id($_) and $hit->{'tid'} = $_ and last for $hit->{'tid'}, $hit->{'v_tid'}; if ($object) { $object = $object->transcript if $feature_type eq 'Translation'; my @coords = sort { $a->start <=> $b->start } grep { !$_->isa('Bio::EnsEMBL::Mapper::Gap') } $object->$mapper($hit->{'tstart'}, $hit->{'tend'}); $g_id = $object->seq_region_name; $g_start = $coords[0]->start; $g_end = $coords[-1]->end; $g_ori = $object->strand; $g_coords = \@coords; } else { $g_id = 'Unmapped'; $g_start = 'N/A'; $g_end = 'N/A'; $g_ori = 'N/A' } } delete $hit->{'v_tid'} if $feature_type && $feature_type ne 'Transcript'; # we need versioning for transcript only $hit->{'gid'} = $g_id; $hit->{'gstart'} = $g_start; $hit->{'gend'} = $g_end; $hit->{'gori'} = $g_ori; $hit->{'species'} = $species; $hit->{'source'} = $source_type; $hit->{'g_coords'} = $g_coords if $g_coords; return $hit; } 1;
Ensembl/public-plugins
tools_hive/modules/EnsEMBL/Web/Parsers/NCBIBLAST.pm
Perl
apache-2.0
4,724
#!/usr/bin/env perl ######################################################################################### # # # Application: discovery.pl # # Summary: A System Discovery Tool # # Author: Gary L. Greene, Jr. <greeneg@yggdrasilsoft.com> # # Copyright: 2011-2019 YggdrasilSoft, LLC. # # License: Apache Public License, v2 # # # #=======================================================================================# # # # 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 Discovery::Plugins::Uptime; use strict; use warnings; use feature ":5.22"; # Add features to system for lexical subs and signatures # disable all warnings for these as they are still experimental # (likely won't change much though in the future...) no warnings "experimental::lexical_subs"; no warnings "experimental::signatures"; use feature 'lexical_subs'; use feature 'signatures'; use English; use utf8; use FindBin; use lib "$FindBin::Bin/../lib"; use boolean; BEGIN { if ($OSNAME eq 'Linux' || $OSNAME eq 'Darwin') { use Unix::Uptime; } elsif ($OSNAME eq 'Win32') { require Win32::Uptime; import Win32::Uptime; } } sub new ($class) { my $self = {}; bless $self, $class; return $self; } my sub uptime_days ($seconds) { my $days = $seconds / 86400; return int $days; } my sub uptime_hours ($seconds) { my $hours = $seconds / 3600; return int $hours; } our sub runme ($self, $os, $debug) { my $sub = (caller(0))[3]; my $seconds; my $hours; my $days; my %uptime; if ($os eq "linux" || $os eq 'darwin') { $seconds = Unix::Uptime->uptime(); $days = uptime_days($seconds); $hours = uptime_hours($seconds); %uptime = ( 'hours' => $hours, 'days' => $days, 'seconds' => $seconds, ); } elsif ($os eq "win32") { my $msecs = Win32::Uptime->uptime(); # process into seconds $seconds = $msecs / 1000; $days = uptime_days($seconds); $hours = uptime_hours($seconds); %uptime = ( 'hours' => $hours, 'days' => $days, 'seconds' => $seconds, ); } my %values; $values{'Uptime'}->{'multi_value'} = { 'seconds' => $seconds, 'hours' => $hours, 'days' => $days, 'uptime' => "$days days" }; $values{'Uptime'}->{'uptime'} = "$days days"; $values{'Uptime'}->{'days'} = $days; $values{'Uptime'}->{'hours'} = $hours; $values{'Uptime'}->{'seconds'} = $seconds; return %values; } true;
greeneg/discovery
lib/Discovery/Plugins/Uptime.pm
Perl
apache-2.0
4,338
package Paws::Organizations::ListAccountsForParent; use Moose; has MaxResults => (is => 'ro', isa => 'Int'); has NextToken => (is => 'ro', isa => 'Str'); has ParentId => (is => 'ro', isa => 'Str', required => 1); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'ListAccountsForParent'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::Organizations::ListAccountsForParentResponse'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::Organizations::ListAccountsForParent - Arguments for method ListAccountsForParent on Paws::Organizations =head1 DESCRIPTION This class represents the parameters used for calling the method ListAccountsForParent on the AWS Organizations service. Use the attributes of this class as arguments to method ListAccountsForParent. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to ListAccountsForParent. As an example: $service_obj->ListAccountsForParent(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 MaxResults => Int (Optional) Use this to limit the number of results you want included in the response. If you do not include this parameter, it defaults to a value that is specific to the operation. If additional items exist beyond the maximum you specify, the C<NextToken> response element is present and has a value (is not null). Include that value as the C<NextToken> request parameter in the next call to the operation to get the next part of the results. Note that Organizations might return fewer results than the maximum even when there are more results available. You should check C<NextToken> after every operation to ensure that you receive all of the results. =head2 NextToken => Str Use this parameter if you receive a C<NextToken> response in a previous request that indicates that there is more output available. Set it to the value of the previous call's C<NextToken> response to indicate where the output should continue from. =head2 B<REQUIRED> ParentId => Str The unique identifier (ID) for the parent root or organization unit (OU) whose accounts you want to list. =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method ListAccountsForParent in L<Paws::Organizations> =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/Organizations/ListAccountsForParent.pm
Perl
apache-2.0
2,818
# 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::V9::Common::ProductBiddingCategoryInfo; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = { countryCode => $args->{countryCode}, id => $args->{id}, level => $args->{level}}; # 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/V9/Common/ProductBiddingCategoryInfo.pm
Perl
apache-2.0
1,108
# # 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 storage::emc::celerra::local::mode::components::datamover; use strict; use warnings; my %map_dm_status = ( 0 => 'Reset (or unknown state)', 1 => 'DOS boot phase, BIOS check, boot sequence', 2 => 'SIB POST failures (that is, hardware failures)', 3 => 'DART is loaded on Data Mover, DOS boot and execution of boot.bat, boot.cfg', 4 => 'DART is ready on Data Mover, running, and MAC threads started', 5 => 'DART is in contact with Control Station box monitor', 7 => 'DART is in panic state', 9 => 'DART reboot is pending or in halted state', 13 => 'DART panicked and completed memory dump', 14 => 'DM Misc problems', 15 => 'Data Mover is flashing firmware. DART is flashing BIOS and/or POST firmware. Data Mover cannot be reset', 17 => 'Data Mover Hardware fault detected', 18 => 'DM Memory Test Failure. BIOS detected memory error', 19 => 'DM POST Test Failure. General POST error', 20 => 'DM POST NVRAM test failure. Invalid NVRAM content error', 21 => 'DM POST invalid peer Data Mover type', 22 => 'DM POST invalid Data Mover part number', 23 => 'DM POST Fibre Channel test failure. Error in blade Fibre connection', 24 => 'DM POST network test failure. Error in Ethernet controller', 25 => 'DM T2NET Error. Unable to get blade reason code due to management switch problems', ); sub load { } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking data movers"); $self->{components}->{datamover} = {name => 'data movers', total => 0, skip => 0}; return if ($self->check_filter(section => 'datamover')); foreach my $line (split /\n/, $self->{stdout}) { next if ($line !~ /^\s*(\d+)\s+-\s+(\S+)/); my ($code, $instance) = ($1, $2); next if (!defined($map_dm_status{$code})); return if ($self->check_filter(section => 'datamover', instance => $instance)); $self->{components}->{datamover}->{total}++; $self->{output}->output_add(long_msg => sprintf("Data mover '%s' status is '%s'", $instance, $map_dm_status{$code})); my $exit = $self->get_severity(section => 'datamover', instance => $instance, value => $map_dm_status{$code}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Data mover '%s' status is '%s'", $instance, $map_dm_status{$code})); } } } 1;
wilfriedcomte/centreon-plugins
storage/emc/celerra/local/mode/components/datamover.pm
Perl
apache-2.0
3,397
=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. =pod =head1 NAME Bio::EnsEMBL::Production::Pipeline::Common::DatabaseDumper =head1 DESCRIPTION This is a simple wrapper around the Hive module; all it's really doing is creating an appropriate dbconn for that modules =head1 Author James Allen =cut package Bio::EnsEMBL::Production::Pipeline::Common::DatabaseDumper; use strict; use warnings; use File::Basename qw(dirname); use File::Path qw(make_path); use Bio::EnsEMBL::Hive::DBSQL::DBConnection; use base ( 'Bio::EnsEMBL::Hive::RunnableDB::DatabaseDumper', 'Bio::EnsEMBL::Production::Pipeline::Common::Base' ); sub param_defaults { my ($self) = @_; return { %{$self->SUPER::param_defaults}, 'db_type' => 'core', 'overwrite' => 0, }; } sub fetch_input { my $self = shift @_; my $output_file = $self->param('output_file'); if (defined $output_file) { if (-e $output_file) { if ($self->param('overwrite')) { $self->warning("Output file '$output_file' already exists, and will be overwritten."); } else { $self->warning("Output file '$output_file' already exists, and won't be overwritten."); $self->param('skip_dump', 1); } } else { my $output_dir = dirname($output_file); if (!-e $output_dir) { $self->warning("Output directory '$output_dir' does not exist. I shall create it."); make_path($output_dir) or $self->throw("Failed to create output directory '$output_dir'"); } } } my $db_type = $self->param('db_type'); if ($db_type eq 'hive') { $self->param('src_db_conn', $self->dbc); } else { $self->param('exclude_ehive', 1); my $hive_style_dbc = Bio::EnsEMBL::Hive::DBSQL::DBConnection->new( -dbconn => $self->get_DBAdaptor($db_type)->dbc, ); $self->param('src_db_conn', $hive_style_dbc); } $self->SUPER::fetch_input(); } 1;
Ensembl/ensembl-production
modules/Bio/EnsEMBL/Production/Pipeline/Common/DatabaseDumper.pm
Perl
apache-2.0
2,567
# # Copyright 2015 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package hardware::server::dell::openmanage::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; # $options->{options} = options object $self->{version} = '1.0'; %{$self->{modes}} = ( 'hardware' => 'hardware::server::dell::openmanage::snmp::mode::hardware', ); return $self; } 1; __END__ =head1 PLUGIN DESCRIPTION Check Dell servers in SNMP thanks to Dell Openmanage. =cut
s-duret/centreon-plugins
hardware/server/dell/openmanage/snmp/plugin.pm
Perl
apache-2.0
1,376
package Paws::SimpleWorkflow::MarkerRecordedEventAttributes; use Moose; has DecisionTaskCompletedEventId => (is => 'ro', isa => 'Int', request_name => 'decisionTaskCompletedEventId', traits => ['NameInRequest'], required => 1); has Details => (is => 'ro', isa => 'Str', request_name => 'details', traits => ['NameInRequest']); has MarkerName => (is => 'ro', isa => 'Str', request_name => 'markerName', traits => ['NameInRequest'], required => 1); 1; ### main pod documentation begin ### =head1 NAME Paws::SimpleWorkflow::MarkerRecordedEventAttributes =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::SimpleWorkflow::MarkerRecordedEventAttributes object: $service_obj->Method(Att1 => { DecisionTaskCompletedEventId => $value, ..., MarkerName => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::SimpleWorkflow::MarkerRecordedEventAttributes object: $result = $service_obj->Method(...); $result->Att1->DecisionTaskCompletedEventId =head1 DESCRIPTION Provides the details of the C<MarkerRecorded> event. =head1 ATTRIBUTES =head2 B<REQUIRED> DecisionTaskCompletedEventId => Int The ID of the C<DecisionTaskCompleted> event corresponding to the decision task that resulted in the C<RecordMarker> decision that requested this marker. This information can be useful for diagnosing problems by tracing back the chain of events leading up to this event. =head2 Details => Str The details of the marker. =head2 B<REQUIRED> MarkerName => Str The name of the marker. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::SimpleWorkflow> =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/SimpleWorkflow/MarkerRecordedEventAttributes.pm
Perl
apache-2.0
2,148
package Error::Pure::Error; # Pragmas. use base qw(Exporter); use strict; use warnings; # Modules. use Error::Pure::Utils qw(err_helper); use Error::Pure::Output::Text qw(err_line); use List::MoreUtils qw(none); use Readonly; # Constants. Readonly::Array our @EXPORT_OK => qw(err); Readonly::Scalar my $EVAL => 'eval {...}'; # Version. our $VERSION = 0.22; # Process error. sub err { my @msg = @_; # Get errors structure. my @errors = err_helper(@msg); # Finalize in main on last err. my $stack_ar = $errors[-1]->{'stack'}; if ($stack_ar->[-1]->{'class'} eq 'main' && none { $_ eq $EVAL || $_ =~ m/^eval '/ms } map { $_->{'sub'} } @{$stack_ar}) { die err_line(@errors); # Die for eval. } else { die "$errors[-1]->{'msg'}->[0]\n"; } return; } 1; __END__ =pod =encoding utf8 =head1 NAME Error::Pure::Error - Error::Pure module with error on one line with informations. =head1 SYNOPSIS use Error::Pure::Error qw(err); err 'This is a fatal error', 'name', 'value'; =head1 SUBROUTINES =over 8 =item C<err(@messages)> Process error with messages @messages. =back =head1 EXAMPLE1 # Pragmas. use strict; use warnings; # Modules. use Error::Pure::Error qw(err); # Error. err '1'; # Output: # #Error [example1.pl:9] 1 =head1 EXAMPLE2 # Pragmas. use strict; use warnings; # Modules. use Error::Pure::Error qw(err); # Error. err '1', '2', '3'; # Output: # #Error [example2.pl:9] 1 =head1 DEPENDENCIES L<Error::Pure::Utils>, L<Error::Pure::Output::Text>, L<Exporter>, L<List::MoreUtils>, L<Readonly>. =head1 SEE ALSO L<Error::Pure>, L<Error::Pure::AllError>, L<Error::Pure::Die>, L<Error::Pure::ErrorList>, L<Error::Pure::HTTP::AllError>, L<Error::Pure::HTTP::Error>, L<Error::Pure::HTTP::ErrorList>, L<Error::Pure::HTTP::Print>, L<Error::Pure::Output::Text>, L<Error::Pure::Print>, L<Error::Pure::PrintVar>, L<Error::Pure::Utils>. =head1 REPOSITORY L<https://github.com/tupinek/Error-Pure> =head1 AUTHOR Michal Špaček L<mailto:skim@cpan.org> L<http://skim.cz> =head1 LICENSE AND COPYRIGHT © 2008-2014 Michal Špaček BSD 2-Clause License =head1 VERSION 0.22 =cut
gitpan/Error-Pure
Pure/Error.pm
Perl
bsd-2-clause
2,142
#!/usr/bin/perl -w # # MD5 optimized for AMD64. # # Author: Marc Bevand <bevand_m (at) epita.fr> # Licence: I hereby disclaim the copyright on this code and place it # in the public domain. # use strict; my $code; # round1_step() does: # dst = x + ((dst + F(x,y,z) + X[k] + T_i) <<< s) # %r10d = X[k_next] # %r11d = z' (copy of z for the next step) # Each round1_step() takes about 5.3 clocks (9 instructions, 1.7 IPC) sub round1_step { my ($pos, $dst, $x, $y, $z, $k_next, $T_i, $s) = @_; $code .= " mov 0*4(%rsi), %r10d /* (NEXT STEP) X[0] */\n" if ($pos == -1); $code .= " mov %edx, %r11d /* (NEXT STEP) z' = %edx */\n" if ($pos == -1); $code .= <<EOF; xor $y, %r11d /* y ^ ... */ lea $T_i($dst,%r10d),$dst /* Const + dst + ... */ and $x, %r11d /* x & ... */ xor $z, %r11d /* z ^ ... */ mov $k_next*4(%rsi),%r10d /* (NEXT STEP) X[$k_next] */ add %r11d, $dst /* dst += ... */ rol \$$s, $dst /* dst <<< s */ mov $y, %r11d /* (NEXT STEP) z' = $y */ add $x, $dst /* dst += x */ EOF } # round2_step() does: # dst = x + ((dst + G(x,y,z) + X[k] + T_i) <<< s) # %r10d = X[k_next] # %r11d = z' (copy of z for the next step) # %r12d = z' (copy of z for the next step) # Each round2_step() takes about 5.4 clocks (11 instructions, 2.0 IPC) sub round2_step { my ($pos, $dst, $x, $y, $z, $k_next, $T_i, $s) = @_; $code .= " mov 1*4(%rsi), %r10d /* (NEXT STEP) X[1] */\n" if ($pos == -1); $code .= " mov %edx, %r11d /* (NEXT STEP) z' = %edx */\n" if ($pos == -1); $code .= " mov %edx, %r12d /* (NEXT STEP) z' = %edx */\n" if ($pos == -1); $code .= <<EOF; not %r11d /* not z */ lea $T_i($dst,%r10d),$dst /* Const + dst + ... */ and $x, %r12d /* x & z */ and $y, %r11d /* y & (not z) */ mov $k_next*4(%rsi),%r10d /* (NEXT STEP) X[$k_next] */ or %r11d, %r12d /* (y & (not z)) | (x & z) */ mov $y, %r11d /* (NEXT STEP) z' = $y */ add %r12d, $dst /* dst += ... */ mov $y, %r12d /* (NEXT STEP) z' = $y */ rol \$$s, $dst /* dst <<< s */ add $x, $dst /* dst += x */ EOF } # round3_step() does: # dst = x + ((dst + H(x,y,z) + X[k] + T_i) <<< s) # %r10d = X[k_next] # %r11d = y' (copy of y for the next step) # Each round3_step() takes about 4.2 clocks (8 instructions, 1.9 IPC) sub round3_step { my ($pos, $dst, $x, $y, $z, $k_next, $T_i, $s) = @_; $code .= " mov 5*4(%rsi), %r10d /* (NEXT STEP) X[5] */\n" if ($pos == -1); $code .= " mov %ecx, %r11d /* (NEXT STEP) y' = %ecx */\n" if ($pos == -1); $code .= <<EOF; lea $T_i($dst,%r10d),$dst /* Const + dst + ... */ mov $k_next*4(%rsi),%r10d /* (NEXT STEP) X[$k_next] */ xor $z, %r11d /* z ^ ... */ xor $x, %r11d /* x ^ ... */ add %r11d, $dst /* dst += ... */ rol \$$s, $dst /* dst <<< s */ mov $x, %r11d /* (NEXT STEP) y' = $x */ add $x, $dst /* dst += x */ EOF } # round4_step() does: # dst = x + ((dst + I(x,y,z) + X[k] + T_i) <<< s) # %r10d = X[k_next] # %r11d = not z' (copy of not z for the next step) # Each round4_step() takes about 5.2 clocks (9 instructions, 1.7 IPC) sub round4_step { my ($pos, $dst, $x, $y, $z, $k_next, $T_i, $s) = @_; $code .= " mov 0*4(%rsi), %r10d /* (NEXT STEP) X[0] */\n" if ($pos == -1); $code .= " mov \$0xffffffff, %r11d\n" if ($pos == -1); $code .= " xor %edx, %r11d /* (NEXT STEP) not z' = not %edx*/\n" if ($pos == -1); $code .= <<EOF; lea $T_i($dst,%r10d),$dst /* Const + dst + ... */ or $x, %r11d /* x | ... */ xor $y, %r11d /* y ^ ... */ add %r11d, $dst /* dst += ... */ mov $k_next*4(%rsi),%r10d /* (NEXT STEP) X[$k_next] */ mov \$0xffffffff, %r11d rol \$$s, $dst /* dst <<< s */ xor $y, %r11d /* (NEXT STEP) not z' = not $y */ add $x, $dst /* dst += x */ EOF } my $flavour = shift; my $output = shift; if ($flavour =~ /\./) { $output = $flavour; undef $flavour; } $0 =~ m/(.*[\/\\])[^\/\\]+$/; my $dir=$1; my $xlate; ( $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"; no warnings qw(uninitialized); open OUT,"| \"$^X\" $xlate $flavour $output"; *STDOUT=*OUT; $code .= <<EOF; .text .align 16 .globl md5_block_asm_data_order .type md5_block_asm_data_order,\@function,3 md5_block_asm_data_order: push %rbp push %rbx push %r12 push %r14 push %r15 .Lprologue: # rdi = arg #1 (ctx, MD5_CTX pointer) # rsi = arg #2 (ptr, data pointer) # rdx = arg #3 (nbr, number of 16-word blocks to process) mov %rdi, %rbp # rbp = ctx shl \$6, %rdx # rdx = nbr in bytes lea (%rsi,%rdx), %rdi # rdi = end mov 0*4(%rbp), %eax # eax = ctx->A mov 1*4(%rbp), %ebx # ebx = ctx->B mov 2*4(%rbp), %ecx # ecx = ctx->C mov 3*4(%rbp), %edx # edx = ctx->D # end is 'rdi' # ptr is 'rsi' # A is 'eax' # B is 'ebx' # C is 'ecx' # D is 'edx' cmp %rdi, %rsi # cmp end with ptr je .Lend # jmp if ptr == end # BEGIN of loop over 16-word blocks .Lloop: # save old values of A, B, C, D mov %eax, %r8d mov %ebx, %r9d mov %ecx, %r14d mov %edx, %r15d EOF round1_step(-1,'%eax','%ebx','%ecx','%edx', '1','0xd76aa478', '7'); round1_step( 0,'%edx','%eax','%ebx','%ecx', '2','0xe8c7b756','12'); round1_step( 0,'%ecx','%edx','%eax','%ebx', '3','0x242070db','17'); round1_step( 0,'%ebx','%ecx','%edx','%eax', '4','0xc1bdceee','22'); round1_step( 0,'%eax','%ebx','%ecx','%edx', '5','0xf57c0faf', '7'); round1_step( 0,'%edx','%eax','%ebx','%ecx', '6','0x4787c62a','12'); round1_step( 0,'%ecx','%edx','%eax','%ebx', '7','0xa8304613','17'); round1_step( 0,'%ebx','%ecx','%edx','%eax', '8','0xfd469501','22'); round1_step( 0,'%eax','%ebx','%ecx','%edx', '9','0x698098d8', '7'); round1_step( 0,'%edx','%eax','%ebx','%ecx','10','0x8b44f7af','12'); round1_step( 0,'%ecx','%edx','%eax','%ebx','11','0xffff5bb1','17'); round1_step( 0,'%ebx','%ecx','%edx','%eax','12','0x895cd7be','22'); round1_step( 0,'%eax','%ebx','%ecx','%edx','13','0x6b901122', '7'); round1_step( 0,'%edx','%eax','%ebx','%ecx','14','0xfd987193','12'); round1_step( 0,'%ecx','%edx','%eax','%ebx','15','0xa679438e','17'); round1_step( 1,'%ebx','%ecx','%edx','%eax', '0','0x49b40821','22'); round2_step(-1,'%eax','%ebx','%ecx','%edx', '6','0xf61e2562', '5'); round2_step( 0,'%edx','%eax','%ebx','%ecx','11','0xc040b340', '9'); round2_step( 0,'%ecx','%edx','%eax','%ebx', '0','0x265e5a51','14'); round2_step( 0,'%ebx','%ecx','%edx','%eax', '5','0xe9b6c7aa','20'); round2_step( 0,'%eax','%ebx','%ecx','%edx','10','0xd62f105d', '5'); round2_step( 0,'%edx','%eax','%ebx','%ecx','15', '0x2441453', '9'); round2_step( 0,'%ecx','%edx','%eax','%ebx', '4','0xd8a1e681','14'); round2_step( 0,'%ebx','%ecx','%edx','%eax', '9','0xe7d3fbc8','20'); round2_step( 0,'%eax','%ebx','%ecx','%edx','14','0x21e1cde6', '5'); round2_step( 0,'%edx','%eax','%ebx','%ecx', '3','0xc33707d6', '9'); round2_step( 0,'%ecx','%edx','%eax','%ebx', '8','0xf4d50d87','14'); round2_step( 0,'%ebx','%ecx','%edx','%eax','13','0x455a14ed','20'); round2_step( 0,'%eax','%ebx','%ecx','%edx', '2','0xa9e3e905', '5'); round2_step( 0,'%edx','%eax','%ebx','%ecx', '7','0xfcefa3f8', '9'); round2_step( 0,'%ecx','%edx','%eax','%ebx','12','0x676f02d9','14'); round2_step( 1,'%ebx','%ecx','%edx','%eax', '0','0x8d2a4c8a','20'); round3_step(-1,'%eax','%ebx','%ecx','%edx', '8','0xfffa3942', '4'); round3_step( 0,'%edx','%eax','%ebx','%ecx','11','0x8771f681','11'); round3_step( 0,'%ecx','%edx','%eax','%ebx','14','0x6d9d6122','16'); round3_step( 0,'%ebx','%ecx','%edx','%eax', '1','0xfde5380c','23'); round3_step( 0,'%eax','%ebx','%ecx','%edx', '4','0xa4beea44', '4'); round3_step( 0,'%edx','%eax','%ebx','%ecx', '7','0x4bdecfa9','11'); round3_step( 0,'%ecx','%edx','%eax','%ebx','10','0xf6bb4b60','16'); round3_step( 0,'%ebx','%ecx','%edx','%eax','13','0xbebfbc70','23'); round3_step( 0,'%eax','%ebx','%ecx','%edx', '0','0x289b7ec6', '4'); round3_step( 0,'%edx','%eax','%ebx','%ecx', '3','0xeaa127fa','11'); round3_step( 0,'%ecx','%edx','%eax','%ebx', '6','0xd4ef3085','16'); round3_step( 0,'%ebx','%ecx','%edx','%eax', '9', '0x4881d05','23'); round3_step( 0,'%eax','%ebx','%ecx','%edx','12','0xd9d4d039', '4'); round3_step( 0,'%edx','%eax','%ebx','%ecx','15','0xe6db99e5','11'); round3_step( 0,'%ecx','%edx','%eax','%ebx', '2','0x1fa27cf8','16'); round3_step( 1,'%ebx','%ecx','%edx','%eax', '0','0xc4ac5665','23'); round4_step(-1,'%eax','%ebx','%ecx','%edx', '7','0xf4292244', '6'); round4_step( 0,'%edx','%eax','%ebx','%ecx','14','0x432aff97','10'); round4_step( 0,'%ecx','%edx','%eax','%ebx', '5','0xab9423a7','15'); round4_step( 0,'%ebx','%ecx','%edx','%eax','12','0xfc93a039','21'); round4_step( 0,'%eax','%ebx','%ecx','%edx', '3','0x655b59c3', '6'); round4_step( 0,'%edx','%eax','%ebx','%ecx','10','0x8f0ccc92','10'); round4_step( 0,'%ecx','%edx','%eax','%ebx', '1','0xffeff47d','15'); round4_step( 0,'%ebx','%ecx','%edx','%eax', '8','0x85845dd1','21'); round4_step( 0,'%eax','%ebx','%ecx','%edx','15','0x6fa87e4f', '6'); round4_step( 0,'%edx','%eax','%ebx','%ecx', '6','0xfe2ce6e0','10'); round4_step( 0,'%ecx','%edx','%eax','%ebx','13','0xa3014314','15'); round4_step( 0,'%ebx','%ecx','%edx','%eax', '4','0x4e0811a1','21'); round4_step( 0,'%eax','%ebx','%ecx','%edx','11','0xf7537e82', '6'); round4_step( 0,'%edx','%eax','%ebx','%ecx', '2','0xbd3af235','10'); round4_step( 0,'%ecx','%edx','%eax','%ebx', '9','0x2ad7d2bb','15'); round4_step( 1,'%ebx','%ecx','%edx','%eax', '0','0xeb86d391','21'); $code .= <<EOF; # add old values of A, B, C, D add %r8d, %eax add %r9d, %ebx add %r14d, %ecx add %r15d, %edx # loop control add \$64, %rsi # ptr += 64 cmp %rdi, %rsi # cmp end with ptr jb .Lloop # jmp if ptr < end # END of loop over 16-word blocks .Lend: mov %eax, 0*4(%rbp) # ctx->A = A mov %ebx, 1*4(%rbp) # ctx->B = B mov %ecx, 2*4(%rbp) # ctx->C = C mov %edx, 3*4(%rbp) # ctx->D = D mov (%rsp),%r15 mov 8(%rsp),%r14 mov 16(%rsp),%r12 mov 24(%rsp),%rbx mov 32(%rsp),%rbp add \$40,%rsp .Lepilogue: ret .size md5_block_asm_data_order,.-md5_block_asm_data_order EOF print $code; close STDOUT;
GaloisInc/hacrypto
src/C/libssl/HEAD/src/crypto/md5/asm/md5-x86_64.pl
Perl
bsd-3-clause
10,043
#!/usr/bin/env perl ###################################################################### # Copyright (c) 2012, Yahoo! Inc. All rights reserved. # # This program is free software. You may copy or redistribute it under # the same terms as Perl itself. Please see the LICENSE.Artistic file # included with this project for the terms of the Artistic License # under which this project is licensed. ###################################################################### TestDelayWorker->new($ARGV[0])->run(); package TestDelayWorker; use strict; use warnings; use Gearbox::Worker; use JSON; use base qw(Gearbox::Worker); use constant DBDIR => "/var/gearbox/db/test-delay-perl/"; sub new { my $self = shift->SUPER::new(@_); $self->register_handler( "do_get_testdelayperl_counter_v1" ); $self->register_handler( "do_post_testdelayperl_counter_v1" ); $self->register_handler( "do_delete_testdelayperl_counter_v1" ); $self->register_handler( "do_increment_testdelayperl_counter_v1" ); return $self; } my $json; sub json { return $json || ($json = JSON->new->allow_nonref); } sub do_get_testdelayperl_counter_v1 { my ( $self, $job, $resp ) = @_; $resp->content( slurp( DBDIR . $job->resource_name() ) ); return $WORKER_SUCCESS; } sub do_post_testdelayperl_counter_v1 { my ( $self, $job, $resp ) = @_; my $matrix = $job->matrix_arguments(); my $start = 0; if( exists $matrix->{"start"} ) { $start = $matrix->{"start"}; } write_file( DBDIR . $job->resource_name(), $start); $self->afterwards($job, "do_increment_testdelayperl_counter_v1", int $job->matrix_arguments()->{"delay"} || 1); return $WORKER_CONTINUE; } sub do_delete_testdelayperl_counter_v1 { my ( $self, $job, $resp ) = @_; unlink(DBDIR . $self->arguments()->[0]); return $WORKER_SUCCESS; } sub do_increment_testdelayperl_counter_v1 { my ($self,$job,$resp) = @_; my $newval = 1 + slurp(DBDIR . $job->resource_name()); write_file( DBDIR . $job->resource_name(), $newval ); my $matrix = $job->matrix_arguments(); my $start = 0; if( exists $matrix->{"start"} ) { $start = $matrix->{"start"}; } my $end = 10; if( exists $matrix->{"end"} ) { $end = $matrix->{"end"}; } $resp->status()->add_message("set to " . $newval); if( $newval == $end ) { return $WORKER_SUCCESS; } else { $resp->status()->progress( $resp->status()->progress() + ($end - $start) ); } if ( $job->matrix_arguments()->{"retry"} ) { $resp->status()->add_message( "retry attempt number " . ($resp->status()->failures()+1) ); return $WORKER_RETRY; } else { $self->afterwards($job, int $job->matrix_arguments()->{"delay"} || 1); } return $WORKER_CONTINUE; } # # Helper Routines # sub slurp { my $file = shift; return do { local $/ = undef; open my $fh, '<', $file or die "can't read contents of $file: $!\n"; <$fh>; }; } sub write_file { my $file = shift; my $contents = shift; open my $fh, ">", $file or die "Couldn't open $file to write: $!\n"; print $fh $contents; close $fh; return; } 1;
getgearbox/gearbox
workers/test-delay/perl/workerTestDelay.pl
Perl
bsd-3-clause
3,213
#!/usr/bin/env perl use strict; use warnings; use File::Slurp qw/read_file/; use Algorithm::Combinatorics qw/permutations combinations/; use List::Util qw/min/; use Data::Dumper; my ($a, $b) = (gen(289, 16807),gen(629, 48271)); #my ($a, $b) = ({val=>65, fac=>16807, div=>2147483647},{val=>8921, fac=>48271, div=>2147483647}); sub gen { my ($val, $fac) = @_; return sub { $val *= $fac; $val %= 2147483647; return $val & 0xffff; } } $|=1; my $res = 0; for (my $i = 0; $i < 40000000; $i++) { $res++ if $a->() == $b->(); # print "\r$i " unless $i % 1000; } print "\rPart One Result: $res\n"; $res = 0; my (@a, @b) = ((),()); ($a, $b) = (gen(289, 16807),gen(629, 48271)); my $count = 0; for ($count = min(scalar @a, scalar @b); $count < 5000000; $count = min(scalar @a, scalar @b)) { my $a_val = $a->(); my $b_val = $b->(); push @a, $a_val unless $a_val % 4; push @b, $b_val unless $b_val % 8; # print "\r$count " unless $count % 1000; } for (my $i = 0; $i < $count; $i++) { $res++ if $a[$i] == $b[$i]; } print "\rPart Two Result: $res\n";
Aneurysm9/advent
2017/day15/day15.pl
Perl
bsd-3-clause
1,077
=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::REST::Controller::Root; use Moose; use namespace::autoclean; BEGIN { extends 'Catalyst::Controller::REST' } # # Sets the actions in this controller to be registered with no prefix # so they function identically to actions created in MyApp.pm # __PACKAGE__->config( namespace => '', ); sub index : Path : Args(0) { my ( $self, $c ) = @_; $c->go('EnsEMBL::REST::Controller::Documentation','index'); } =head2 default Standard 404 error page =cut sub default : Path { my ( $self, $c ) = @_; my $url = $c->uri_for('/'); $c->go( 'ReturnError', 'not_found', [qq{page not found. Please check your uri and refer to our documentation $url}] ); } =head2 end Attempt to render a view, if needed. =cut sub end : ActionClass('RenderView') {} __PACKAGE__->meta->make_immutable; 1;
ens-lgil/ensembl-rest
lib/EnsEMBL/REST/Controller/Root.pm
Perl
apache-2.0
1,521
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the 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>. =head1 NAME Bio::EnsEMBL::Compara::RunnableDB::PairAligner::UcscToEnsemblMapping =head1 DESCRIPTION Convert UCSC names to ensembl names (reference only chromosomes and supercontigs, ie no haplotypes) First check the names using chromInfo.txt and then go to mapping file if necessary eg ctgPos.txt for human Download from: http://hgdownload.cse.ucsc.edu/downloads.html Choose species Choose Annotation database wget http://hgdownload.cse.ucsc.edu/goldenPath/ponAbe2/database/chromInfo.txt.gz =cut package Bio::EnsEMBL::Compara::RunnableDB::PairAligner::UcscToEnsemblMapping; use strict; use Bio::EnsEMBL::Compara::MethodLinkSpeciesSet; use base ('Bio::EnsEMBL::Compara::RunnableDB::BaseRunnable'); ############################################################ =head2 fetch_input Title : fetch_input Usage : $self->fetch_input Returns : nothing Args : none =cut sub fetch_input { my( $self) = @_; #Must define chromInfo file return if (!defined $self->param('chromInfo_file') || $self->param('chromInfo_file') eq ""); my $gdba = $self->compara_dba->get_GenomeDBAdaptor; my $genome_db = $gdba->fetch_by_name_assembly($self->param('species')); $self->param('genome_db', $genome_db); #Get slice adaptor my $slice_adaptor = $genome_db->db_adaptor->get_SliceAdaptor; my $ensembl_names; my $ucsc_to_ensembl_mapping; #Get all toplevel slices my $ref_slices = $slice_adaptor->fetch_all("toplevel"); foreach my $this_slice ( @$ref_slices ) { $ensembl_names->{$this_slice->seq_region_name} = 1; } #Open UCSC chromInfo file open UCSC, $self->param('chromInfo_file') or die ("Unable to open " . $self->param('chromInfo_file')); while (<UCSC>) { my ($ucsc_chr, $size, $file) = split " "; my $chr = $ucsc_chr; $chr =~ s/chr//; if ($ensembl_names->{$chr}) { $ensembl_names->{$chr} = 2; $ucsc_to_ensembl_mapping->{$ucsc_chr} = $chr; } elsif ($chr eq "M") { #Special case for MT $ensembl_names->{"MT"} = 2; $ucsc_to_ensembl_mapping->{$ucsc_chr} = "MT"; } else { #Try extracting gl from filename if (defined $self->param('ucsc_map')) { read_ucsc_map($self->param('ucsc_map'), $ensembl_names, $ucsc_to_ensembl_mapping); } else { die ("You must provide a UCSC mapping file"); } } } close UCSC; foreach my $chr (keys %$ensembl_names) { if ($ensembl_names->{$chr} != 2) { die ("Failed to find $chr in UCSC"); } } $self->param('ucsc_to_ensembl_mapping', $ucsc_to_ensembl_mapping); } sub read_ucsc_map { my ($ucsc_map, $ensembl_names, $ucsc_to_ensembl_mapping) = @_; open MAP, $ucsc_map or die ("Unable to open " . $ucsc_map); while (<MAP>) { my ($contig, $size, $chrom, $chromStart, $chromEnd) = split " "; if ($ensembl_names->{$contig}) { #print "FOUND $contig\n"; $ensembl_names->{$contig} = 2; $ucsc_to_ensembl_mapping->{$chrom} = $contig; } } close MAP; } sub run { my $self = shift; } sub write_output { my ($self) = shift; return if (!defined $self->param('chromInfo_file') || $self->param('chromInfo_file') eq ""); my $genome_db_id = $self->param('genome_db')->dbID; #Insert into ucsc_to_ensembl_mapping table my $sql = "INSERT INTO ucsc_to_ensembl_mapping (genome_db_id, ucsc, ensembl) VALUES (?,?,?)"; my $sth = $self->compara_dba->dbc->prepare($sql); my $ucsc_to_ensembl_mapping = $self->param('ucsc_to_ensembl_mapping'); foreach my $ucsc_chr (keys %$ucsc_to_ensembl_mapping) { #print "$ucsc_chr " . $ucsc_to_ensembl_mapping->{$ucsc_chr} . "\n"; $sth->execute($genome_db_id, $ucsc_chr, $ucsc_to_ensembl_mapping->{$ucsc_chr}); } $sth->finish(); } 1;
kumarsaurabh20/ensembl-compara
modules/Bio/EnsEMBL/Compara/RunnableDB/PairAligner/UcscToEnsemblMapping.pm
Perl
apache-2.0
4,639
package Paws::CloudHSMv2::UntagResourceResponse; use Moose; has _request_id => (is => 'ro', isa => 'Str'); ### main pod documentation begin ### =head1 NAME Paws::CloudHSMv2::UntagResourceResponse =head1 ATTRIBUTES =head2 _request_id => Str =cut 1;
ioanrogers/aws-sdk-perl
auto-lib/Paws/CloudHSMv2/UntagResourceResponse.pm
Perl
apache-2.0
262
package DDG::Spice::Mtg; # ABSTRACT: Information on 'Magic The Gathering' cards use strict; use DDG::Spice; triggers start => 'mtg', 'magic card', 'magic cards', 'magic the gathering'; spice to => 'http://api.mtgdb.info/cards/$1'; spice wrap_jsonp_callback => 1; handle remainder => sub { $_ =~ s/\://; return $_ if $_; return; }; 1;
andrey-p/zeroclickinfo-spice
lib/DDG/Spice/Mtg.pm
Perl
apache-2.0
351
package Google::Ads::AdWords::v201409::Budget::BudgetStatus; use strict; use warnings; sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201409'}; # derivation by restriction use base qw( SOAP::WSDL::XSD::Typelib::Builtin::string); 1; __END__ =pod =head1 NAME =head1 DESCRIPTION Perl data type class for the XML Schema defined simpleType Budget.BudgetStatus from the namespace https://adwords.google.com/api/adwords/cm/v201409. This clase is derived from SOAP::WSDL::XSD::Typelib::Builtin::string . SOAP::WSDL's schema implementation does not validate data, so you can use it exactly like it's base type. # Description of restrictions not implemented yet. =head1 METHODS =head2 new Constructor. =head2 get_value / set_value Getter and setter for the simpleType's value. =head1 OVERLOADING Depending on the simple type's base type, the following operations are overloaded Stringification Numerification Boolification Check L<SOAP::WSDL::XSD::Typelib::Builtin> for more information. =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201409/Budget/BudgetStatus.pm
Perl
apache-2.0
1,077
package # Date::Manip::Offset::off352; # Copyright (c) 2008-2014 Sullivan Beck. All rights reserved. # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. # This file was automatically generated. Any changes to this file will # be lost the next time 'tzdata' is run. # Generated on: Fri Nov 21 11:03:46 EST 2014 # Data version: tzdata2014j # Code version: tzcode2014j # This module contains data from the zoneinfo time zone database. The original # data was obtained from the URL: # ftp://ftp.iana.orgtz use strict; use warnings; require 5.010000; our ($VERSION); $VERSION='6.48'; END { undef $VERSION; } our ($Offset,%Offset); END { undef $Offset; undef %Offset; } $Offset = '-05:44:38'; %Offset = ( 0 => [ 'america/indiana/indianapolis', ], ); 1;
nriley/Pester
Source/Manip/Offset/off352.pm
Perl
bsd-2-clause
866